Captcha Failed on Custom Validation I have my own validation on user form login like this :

if ($form_id == 'user_login') {
        $form['#validate'][] = 'wemusic_user_login_validate';
        $form['#submit'] = array();
        array_unshift($form['#submit'], 'wemusic_user_login_submit');
    }

function wemusic_user_login_validate($form, &$form_state){
    $username = $form['name']['#value'];
    $user = user_load_by_name($username);
    if ($user){
        if($user->status == "1"){
            $form_state = array();
            $form_state['uid'] = $user->uid;
            user_login_submit(array(), $form_state);
        }else{

            drupal_goto('registration/confirm', array('query'=>array(
                'user'=>$username,
            )));
        }

    }else{
        drupal_goto('user/register');
    }
}

with this code CAPTCHA failed , how can I call CAPTCHA validation in my custom function ?

This a improved version of your code

  if ($form_id == 'user_login') {
        $form['#validate'][] = 'wemusic_user_login_validate';
        $form['#submit'] = array();
        array_unshift($form['#submit'], 'wemusic_user_login_submit');
    }

function wemusic_user_login_validate($form, &$form_state){
    $username = $form['name']['#value'];
    $user = user_load_by_name($username);
    if ($user && $user->status != "1"){
            drupal_set_message("Baba Taid kon bad boro to",'error');
            drupal_goto('registration/confirm', array('query'=>array(
                'user'=>$username,
            )));
    }
   else {
        drupal_set_message("Sabenam nakarde mikhay beri to akhe amo ?!!!",'error');
        drupal_goto('user/register');
    }
}

When you are in user_login and user is going to login don't empty $form_state  with $form_state = array(); Let Drupal Handle it's way to log on user  you just check what you want before it.

This will work for you , but I think is better when the situation is not satisfied in validator set error and set a destination variable on $form_state  ( maybe $form_state['redirect'] or your custom $form_state['my_redirect'] )  then in form_alter  check if  your error exists redirect to that destination with Drupal_goto.

Any way mentioned code ( up code) satisfy what you want.


How to pull out Twig variables? Trying to use some Twig variables (simple strings) in a template that I created from a custom module. Using the Devel and Kint modules I can see the info under Iterator contents with:

{{kint(transaction[0])}}

I just can't get the template to print it out on the page.

I tried this:

$ {{transaction.amount }} total donation

and

$ {{transaction[0].amount }} total donation

Either way comes up empty. Not sure what I'm missing here. It works in other modules just fine. Maybe I'm too high on the Twig templates? I don't understand the tree structure very well. I created a template called transaction.html.twig.

This is what my controller looks like.

This is the .module file. It's passing over from the controller to this theme which then passes it to the twig file. At least this is how all the tutorials tell me to do it. I create this same thing on another module and it works fine.

function touchdownclub_theme($existing, $type, $theme, $path) {

 return array(
    'touchdownclubtransaction' => array(
      'variables' => array(
        'transaction' => NULL,
      ),
       'template' => 'touchdownclubtransaction',
    ),
  );
}

I looked at some other modules controllers and saw that in the controller they used

$result = db_query
$output = $result->fetchAll();

Before pushing the code to the return array. I tried it and it worked for me like it should. Problem solved.


Generate breadcrumb based on a given Path How can I know the breadcrumb that will be generated in a page without visiting that page? Is this possible?

It really depends on what module/configuration you are using to generate the breadcrumb, sometimes some basic configuration is set in the base theme you are using as well, you might wanna check that out in your page.tpl.php file. basically your question is so vague it's hard to answer.

but mostly in most of themes the breadcrumb is being generated like this:

Home > Node title

Home > Taxonomy Term > Node title


How to hide a block in a view when an exposed filter is being applied? I have built a view with exposed filters. There is a 'popular content' block on this page which I am controlling using the Context module (https://www.drupal.org/project/context)

I would like it so that the popular content displays, but only if no filters are being applied to the view. If a filter is applied then the block should not show.

I can see that the Context module has a query string condition option which I've tried to apply but without success. I've tried adding things like ~?title=* or ~*?title=** here but I can't seem to get the behaviour I'm after.

Any help would be appreciated.

UPDATE

I've used the answer from @Pierr.Vriens to create a rule component. However, the block now isn't showing on the /MyViewPath page (which is /courses on my site). I've put the export of the rule I created below. I'm surprised that it's not showing on the page now at all. The block is being set in the correct region, the 'rules' component has been added to the block settings itself and I've disabled the context module from messing with it too.

Here is an export of the rule I created:

{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "courses " } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

UPDATE 2

So it was the space at the end of "courses " that was causing the problem. The exported rule below did the trick:

{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "courses",
          "operation" : "ends"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

You can use the Rules block visibility module for this. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown for the page with an URL that matches with your view without any filters applied).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". If you look at the example included there, just replace its Rules Condition by a Text comparison with Parameter: Text: [site:current-page:path], Matching text: MyViewPath (assuming that /MyViewPath is the path of your view without any filters applied).

Update: looking at your exported rule (in revision 3 of your updated question, so without "UPDATE 2" you added to it ), I noticed that there is a space (blank) at the end of "course ". Not sure why that is there, but I'd first try with removing that space. If that doesn't make a difference, I suggest you try a variation of your rule that looks like so (only the Rules Condition differs from what you have in your updated question):

{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "courses" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

If that also doesn't help, then it's time for Rules debugging. For that, refer to my answer to "How can I display the value of a variable inside a condition?".

PS: This answer applies to D7 ...


How to identify item_selector for Migrate API JSON imports Trying to import articles from an external JSON feed of "members" with a structure like this:

{
   "status":"OK",
   "results":[
      {
         "num_results": 10,
         "offset": 0,
         "articles": [
              {
                 "id": "1",
                 "title": "First article",
...

And I haven't been able to isolate the correct values to use for item_selector to get it to point to the array of "articles":

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: http://example.com/eample.json
  item_selector: /results/members/

The error I continually get in the console is:

  [error]  Could not retrieve source count from import_your node: Passed
  variable is not an array or object

Would be grateful for an explanation of exactly how item_selector is defined or a pointer to documentation for the same.

Think I have a solution, posting here in case it helps others. I tried to find a solution using xpath by using JSON browser like http://jsonpathfinder.com/ which gave me a path like this to find a field:

  results[0].members[0].id

The source JSON is coming in as an array but it doesn't appear that the way migrate_plus is handling selectors (splitting on the '/' symbol) is able to handle an xpath array designation, which was flagged in this issue https://www.drupal.org/node/2883803.

To get around this, I thought it would be easier if I could just change the source JSON to fit what migrate_tools can handle so I setup a simple router on my site:

import.my_wrapper:
  path: '/json/wrapper/my.json'
  defaults:
    _controller: '\Drupal\import\Controller\WrapperController::MyWrapper'
  requirements:
    _permission: 'access content'

Then built out the controller to use Guzzle to pull down my source URL normally and then flatten it so that migrate_tools can handle it:

  private function PrepJSONData($data) {
    $data_array = json_decode($data);
    $data_array = $data_array->results[0];
    $data = json_encode($data_array, JSON_UNESCAPED_SLASHES);
    return $data;
  }

I then updated my fetcher in my migrate yaml files to point to the route I had defined on my local site:

  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: https://example/json/wrapper/my.json

Leaving this question open in case anyone else can propose a more efficient approach.


How to add a "Last Updated at" field in footer area? I wanted to add a field in my website (in footer area), which can automatically display the "last updated" date.

I found the same question in SO but it is not working properly. While accessing some pages, I can see this field as blank with follow errors-

Notice: Undefined variable: node in include() (line 207 of O:\xampp\htdocs\rutag\sites\all\themes\skeletontheme\templates\page.tpl.php).
Notice: Trying to get property of non-object in include() (line 207 of O:\xampp\htdocs\rutag\sites\all\themes\skeletontheme\templates\page.tpl.php).

By saying "Last Updated at", I mean to say that the last date on which admin has updated (published/modified any content) the website.

Not all page types have a a $node object associated (the user page, for one does not).  You can get rid of the error message that says:

Notice: Undefined variable: node

by wrapping the call to format_date in an if-statement like this:

<?php
if (isset($node->changed)) {
  print "Last modified date: " . format_date($node->changed);
}
?>


Why doesn't "composer update drupal/drupal" work? I installed a Drupal 8.2.0 site with composer create-project drupal/drupal testsite.

Now I would like to upgrade it to Drupal 8.2.1. However, running composer update drupal/drupal  doesn't work. It prints the following error:

  Package "drupal/drupal" listed for update is not installed. Ignoring.

How do I do this? The support is clearly documented in example.gitignore.

# Ignore core when managing all of a project's dependencies with Composer
# including Drupal core.
# core

So there has to be some way to do this with composer, but how?

Edit: this is probably not helpful b/c I just re-read your statement and you didn't have the same case as mine where I was coming from an old Drupal 8 install but I will leave this up in case anyone else has this issue and try to see if I can find the specific issue you are having. Sorry.

I had this issue when dealing with a recent update and this was my issue but YMMV so if it doesn't work just let me know.

This may be a problem of that you composer file is set to the old repository listing on composer.org. Recently, Drupal setup their own composer endpoints, one for Drupal 7 and another for Drupal 8. You can read more about that change here: https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-packages-through-drupalorg

This is the command that needs to be ran to swap the repository over the Drupal.org's.

$ composer config repositories.0
$ composer https://packages.drupal.org/8


CPN: Replacing tokens in physical css/js files Hi I have some css / js attached to a box with Code Per Node. CPN creates physical files for the code. In hook_preprocess_node I can see the CPN output, for example:

$vars['cpn']['css'] = token_replace($vars['cpn']['css']);
$vars['cpn']['js'] = token_replace($vars['cpn']['js']);

This successfully replaces the tokens in memory but the physical file is loaded up in the header and so the tokens aren't replaced in there and cause an error. Any ideas?

Thanks

Both drupal_add_js and drupal_add_css have an option to add code "inline".  You can try his in a template_preprocess_node:

function mytheme_proprocess_node (&$variables)
{
  drupal_add_js($variables['cpn']['js'], 'inline');
  drupal_add_css($variables['cpn']['css'], 'inline');
}

If you do this in a theme, then the CPN hook should have already been fired.  If you do it from a module, you may need to play with the module weights to get yours to follow.


Expiration of cached pages stuck at 6 hours No matter what I change in the GUI, after clicking save the Expiration of cached pages under Performance options is reset to 6 hours. I checked my default VCL for Varnish suspecting this might be something set there, but couldn't find a 6 (hours) or value of 21600 (6 hours in seconds) there.

I'm pretty new to Varnish so not sure if it might be some default value, or what that could be called (or if Varnish is the culprit here at all, just a hunch).

We need to have Varnish keeping pages cached indefinately by default, and caches to only get cleared when content updates.

The settings.php file contained the following line, which caused the behavior I was observing.

$conf['page_cache_maximum_age'] = 21600;


Redirect if URL does not match I am using D7.

I am attempting to create a redirect in my .htaccess file that will redirect the page if the path doesn't match a pattern.

# only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# only if URI contains "library"
RewriteCond %{REQUEST_URI} !^/Library$ [NC]
# rewrite the URL
RewriteRule ^(.*)$ http://otherdomain.org/$1 [R=301,L]

This works fine for most of the site (e.g. http://mysite.domain.org/blogs is redirected to http://otherdomain.org/blogs

However, http://mysite.domain.org/Library?id=1234 is being redirected but to http://otherdomain.org?id=1234 ("library" in URI is missing but this shouldn't redirect at all)

What am I missing?  Am I running into Drupal URL rewriting rules?

Try this:

# only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# rewrite the URL
RewriteRule ^((?!Library).*)$ http://otherdomain.org/$1 [R=301,L]

The (?!Library) should look ahead, and the match should fail if "Library" is present. Hope this works for you.


fetching user photo or image URL i am trying to fetch loged in users photo to make a welcome block. i have applied a code which is not working

$userphoto = $user->picture;

so what to do to fetching user photo or image URL, any idea?

The picture property of the user entity is the file ID (a reference to the fid column in the file_managed table).

You can load the file explicitly with file_load() like so:

$file = file_load($user->picture);

And render it to an image using theme_image():

$image = theme('image', array(
  'path' => $file->uri,
  'alt' => 'Some alt',
  // etc...
));

Alternatively you could dispense with the above and just use the handy theme_user_picture() function:

$image = theme('user_picture', array('account' => $account));


Simple Drupal page loads very slowly; slow 'DrupalDatabaseCache::getMultiple' query I've installed Drupal (and CiviCRM within Drupal) on shared hosting my group's host assures me is adequate (though they refuse to enable PHP caching like APC on it). It's generally far slower than my installs on other servers or my home Mac. Even the simple, completely default Drupal front page (which just shows one promoted story, the only extra blocks being from the Devel module) loads slowly. Just now it took a minute, and the Devel block reported the following slow queries. Any help solving or at least diagnosing the problem very welcome!

  ms | # | where | ops | query | target

  41.05 | 21 | DrupalDatabaseCache::getMultiple | P A E |
  SELECT cid, data, created, expire, serialized FROM drupal_cache_menu WHERE cid IN (:cids_0)
  default

  32.97 | 21 | DrupalDatabaseCache::getMultiple | P A E |
  SELECT cid, data, created, expire, serialized FROM drupal_cache_menu WHERE cid IN (:cids_0)
  default

  28.13 | 21 | DrupalDatabaseCache::getMultiple | P A E |
  SELECT cid, data, created, expire, serialized FROM drupal_cache_menu WHERE cid IN (:cids_0)
  default

Devel is telling you how slow the query is. From what you wrote on your question it does not appear however to be telling you what is executing that query. I would attempt to locate the source of that query first, since your doctor can't issue you a prescription, if he does not know your ailment first.

I tried searching my D7 codebase for the string "drupal_cache_menu" and did not find anything. So perhaps that is coming from a contrib module? Otherwise it would have shown up in my search. Regardless, you can see the pattern I used to locate the code responsible for that query:

Select a unique string from the query (I tried using an individual word).
Search your whole codebase for that string.
See if the matches returned from your search could possibly relate to the slow query.

Once you locate the source of the query then you will (most likely) be able to determine if the slow query was caused by:

An error.
A view (in which case all you have to do to solve the problem is set the caching for that View).
Legit custom code (without errors) that just needs optimization, in this case you could implement Drupal's Cache API (the cache_get() and cache_set() functions) and maybe static caching as well. The nice thing about the Cache API is that you can benefit from implementing it even when you don't have external persistent cache stores such as Memcached and APC installed. Lullabot's now classic Caching guide for beginners might well help you out as well.
Legit contrib code (without errors) that just needs optimization. In this case you would probably be better off consulting the module mantainer.

As you see, the corrective actions are too many to list, and which one you will take will depend on the source of the query.


How do I manage collaborative development on a Drupal site? I work with another developer on a Drupal site. We have struggled to find a good way to work on different parts of the site at the same time without getting in each others way. We've tried working on the same development instance of the site, but we often step on each others toes, or bring down the site with some bad code making it impossible for the other to continue working until it's resolved. So we've moved to separate development instances. But now it's a big pain to merge our work into a single instance of the site. We basically end up redoing everything on a shared copy.

The biggest problem we have now is how do we merge database changes, and how do we include the database in our source control system? The files are easy, just track them all (we use git) and merge our work, resolving conflicts where needed. But this doesn't really work with the database. We can take a SQL dump and include that in our git repository, but we can't really merge the databases. The Features module helps a little, letting us export some of our database work into code which can then be versioned and merged. However, not even close to everything supports Features. So...

What steps can we take to easily merge our database changes?
How should we version the database (is putting a dump file in git a good way to do it)?
Are there any modules available that help with some of these problems?
Or, are we stuck with working on the same copy of the site? (please so no)

Edit: In the comments we discussed what things can't be exported with Features and one of them was Taxonomies. There's another question that deals with that.

It is a workflow change but you should get used to working on a fresh dump of the live DB. There are three ways to get changes into the DB.

Features. This won't work for everything but will for a lot of things you need.
update hooks. When features won't work you can hard code things into an update hook of a module you own.
Manual changes. Use sparingly. Some things don't come naturally to features or update hooks and are just much easier to do manually. This is a last resort but sometimes is the only piratical way.

If you can. Several times a day get a fresh dump and test your build, you should have less integration problems.


Email notification via private message module I am using private message module to send an e-mail to all users. When I send mail, users can able to see the message in site only after logging in.

There is an email notification settings in private message module. What is the settings to send mail to user using private message?

Below screen shot shows the settings of email notification.

Part 1:

The answer to the question "What is the settings to send mail to user using private message?" is like so: these settings can be used to finetune the eMail to the user who received a "Private message", whereas such eMails are like a "notification" that there is a new Private message waiting on the site (and for which that user must head over to the site to actually read/see the private message).

Compare it so the various eMails a newly registered user may receive after a registration request got approved, which also requires such new user to go visit the site to actually start using the user id (to set a new password, etc).

Part 2:

Below is a suggestion to address the 2nd part of your question, which you wrote in these 2 comments:

But when i am creating message "To" I have specified their user name to send mail,instead of that i want to give "ROLE OF USERS" it is possible to send mail by using user role ? ...
I have posted in above pic in place "To" i want to specify my user roles ...in under one role i have 10 users i want sent a mail for all of that users.

The Privatemsg Bulkmail module (for D6) would possibly address your question ... Provided "sending a private message" (instead of "sending an eMail") would be OK for your case. If that's not what you want, then you should not be using the Private message module (that's not what it is for). The rest of my answer below assumes that "sending a private message" would be OK.

There are currently no plans for a D7 version of that module. However, I'd use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the VBO module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted (in this case a list of users that corresponds to your ROLE OF USERS).
use Rules action "Send a message" (provided by Privatemsg module).

PS: yet another great usage of the Rules module, in this case in combination with the Privatemsg module.


"Page Not Found" error when a google search form is submitted I am using Google Site Search on a web site, and the search form submits to a page containing the appropriate code. I can access this page directly just fine, but whenever I test out the search form, I get a "page not found" error.

I believe this is because both Drupal and Google search use the parameter 'q', has anyone run into this problem and found a workaround?

Instead of using q, you can use as_q. The description given from the page I linked is the following:

  The as_q parameter provides search terms to check for in a document. This parameter is also commonly used to allow users to specify additional terms to search for within a set of search results.


How to disable/enable cache of all views programmatically? Case: I have over 50 views in my site and for performance improvement all were enabled to cache data during their implementation.

Now I want to disable cache for all views at once for some reason (make it more realtime).

Please help.

You could switch them all off with features and a bit of hacking. Also, as this involves changing lots of things in mass, make sure you back up your work before doing it and make sure you test it out on a dev server first.

With features, you can create a feature containing just your views. You can then download this feature, which will give you something that looks a lot like a module file.

One of the files in this module will be a file called your_feature.views_default.inc, which will contain a bunch of code that will look ALOT like a view export script (because that's exactly what it is.)

If you look at the lines of code, they each represent a configuration in your views, you should be have a bunch of lines that looks like:

  $handler->display->display_options['cache']['type'] = 'time';
  $handler->display->display_options['cache']['results_lifespan'] = '3600';
  $handler->display->display_options['cache']['results_lifespan_custom'] = '0';
  $handler->display->display_options['cache']['output_lifespan'] = '3600';
  $handler->display->display_options['cache']['output_lifespan_custom'] = '0';

depending how you set your caching. Regardless, if you want to shut off caching on all your views, all of those lines need to become:

$handler->display->display_options['cache']['type'] = 'none';

One your edits are done, save the file and upload the feature module back up to your site in your sites/all/modules folder.

Once it's uploaded, head back to your site, and head to the features admin at admin/structure/features, you should see your feature hanging out there, and it's state should be "Overridden." Click on "Overridden," and you see the overview of your feature, along with a handy-dandy button on the lower right hand of the screen that says "revert components." Click the checkbox next to the views list (to tell features what you want reverted), and then click on the revert components to revert the views to what is stored in code.

Now, there is a down side to using this method. The way features works is it actually takes your view and stores it in code, not the DB. So removing your feature would actually remove you views as well. This will be true until you edit your view, in which case it would go back in the database (just that one view though, not all of them).


Add custom field in exposed form in view I have a view with exposed form. I want to add some custom select field in this exposed form. I have tried with hook_form_alter() but the field is rendered in form submit button wrapper which is strange. How can I add a custom field to another one filters ?

You can define the field as a widget by messing with the #info part of the form in hook_form_alter - it's not very elegant but hey.

$form['text_search'] = array(
  '#type' => 'textfield',
  '#description' => t('Or start typing here to find your competition.'),
  '#default_value' => '',
);
// Create widget from new form item.
$new_form_info = array(
  'filter-text_search' => array('value' => 'text_search'),
);
// Put new widget definition at top, so widget will appear
// first (change order to change to desired position).
$form['#info'] = $new_form_info += $form['#info'];


Building Social Network with retweet like functionality I'm designing a social network that I'd like to build on Drupal 7. I'd like people to have a Twitter-like feed that they can follow people/orgs and see their own posts and "re-tweets".

I'm currently starting to look at Organic groups, I invision the owner(s) of the group posting content to a group and anyone visiting that group page would see the group's "feed"(a view). However, I'm not sure how to implement the "retweet" feature that allows a piece content to be viewed by a retweeter's set of followers.

Any hints would be appreciated.

You can use the statuses module for this. See this post for discussion of retweet functionality with statuses.


What's the easiest way to add a contact form for all nodes of a certain content type? I need to add a contact form to all nodes of a certain content type, so when a user submits the form it's delivered to the e-mail address of the author of the node. I tried using Webforms as a block with Contexts but Tokens doesn't work.

I ended using Webforms, passing the node author's e-mail using the token [current-page:node:author:mail] for passing the e-mail via a hidden field. I enabled the option to use the webform as a block and Context module for showing that block only in the desired content type.

With the lastest stable versions of Webforms and Token, I had to patch Token module as it's explained in this forum because the token wasn't working with Webforms.

http://doublemthemes.com/comment/3307#comment-3307


openssl key for drush My server does not allow passwords and requires me to setup an openssl key for access. Drush however requires the server to be more open and I wonder how to setup an openssl key or some other option for using drush update features.

By default, Drush runs ssh with the option -o PasswordAuthentication=no, which prohibits username/password access and requires that you use a public/private key pair to access your server.  This is exactly what you want, and in fact, by default, ssh will use the private key that it finds at $HOME/.ssh/id_rsa to authenticate you with remote servers.

If you need to use some other private key, though, you can put this line in your drushrc.php file:

$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/YOURUSERNAME/.ssh/other_id_rsa';

Note that Drush will not automatically evaluate bash shortcuts such as $HOME or ~.  If you do not want to hardcode the path to your home folder, you may look it up with $HOME = drush_server_home();.


What's the purpose of subfolders inside a theme's templates folder? What is the purpose of folders inside the templates folder in a theme? Where is specified that when rendering a page the template should be taken from layout/page.html.twig? Or a single node template from content/node.html.twig?

I could see content, block, field, form etc. in the /templates folder. I am referring to the Zymphonies theme. When I check Twig Template naming conventions I could see there are naming conventions for Twig templates. But what is the difference in giving Twig plain twig templates inside the templates folder and by giving specific twig templates in specific folders inside templates folder?

These folders are arbitrary. As long as the template is in the [THEME ROOT]/templates folder, it will be picked up. Using folders is simply the developer being well organized.


How to Reduce/Increase module's weight on the module install process? I'm developing one custom module and I want to increase my module weight when the module is installed.

How can I achieve this? Otherwise, does anyone know in which table the module's weight is stored?

Use hook_module_implements_alter() rather than changing the module weight.

Sample implementation from content_translation.module:

function content_translation_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {

    // Move our hook_entity_type_alter() implementation to the end of the list.
    case 'entity_type_alter':
      $group = $implementations['content_translation'];
      unset($implementations['content_translation']);
      $implementations['content_translation'] = $group;
      break;

    // Move our hook_entity_bundle_info_alter() implementation to the top of the
    // list, so that any other hook implementation can rely on bundles being
    // correctly marked as translatable.
    case 'entity_bundle_info_alter':
      $group = $implementations['content_translation'];
      $implementations = [
        'content_translation' => $group,
      ] + $implementations;
      break;
  }
}


modified value in form_state but it is not being saved in the validation of my form i pass the form_state by reference and I modified the form state value of one of the fields with $form_state['values']['field_total_payment']['und'][0]['value'] = $total_payment;

I also tried  form_set_value($form['field_total_payment'], array('und' => array(0 => array('value' => $total_payment))), $form_state);

and I add a second submit to check if the value is there and I can see that with both pieces of code it is in the form_state['value'] , but it is not getting saved to the node.

What is missing for this information to be stored into the database?

Use

$form_state->setValue($key, $value);

In your case, that should be

$form_state->setValue(['field_total_payment'], $total_payment);


Filter for previous time periods in views I'm trying to set up Grouped filters for Content revision: Changed in a view. I want the filter to work for Today, Yesterday, Last week, Last month, and Last year. The grouped filters makes that simple enough, and it looks like this:

But all the filters are not filtering correctly.
For the Today filter, this will work.

But When I try to use an Is between operator for any previous dates, I get an error like this

How do I filter for previous time periods in views?

The Today filter works with Is greater than or equal to today midnight. It's the Is between parameters that the view won't accept.
The existing Today filter query adds
 AND ((node_field_revision.changed >= 1597759242-68400))

to the query, which converts to
GMT: Tuesday, August 18, 2020 2:00:42 PM - 19 hours.

Setting the Yesterday filter with Is less than or equal to yesterday adds
AND ((node_field_revision.changed <= 1597759395-154800))

to the query, which converts to
GMT: Tuesday, August 18, 2020 2:03:15 PM - 43 hours

which means the filter will show values from yesterday and today. That's not a yesterday filter.
So Is between is the way to go, but any values I try, including yours @Yuseferi, aren't accepted in the UI and so can't adjust to the query accordingly. If the view would accept an Is between operator, the query would add something like this:
AND ((node_field_revision.changed <= 1597759956-(1597723200-1597636800))

Where
Now: 1597759956
Today: 1597723200
Yesterday: 1597636800

That would be a yesterday query, which Drupal could then adjust for GMT.

I would suggest
data between today 1 sec ago and yesterday


added to Views header (global unfiltered text) disappears with inspect element I'm trying to wrap a  tag around some content in my View header but it's not working as intended.

I'm using the Global: Unfiltered text as the type of header content. I'm inserting the div like so:

header

It saves it alright and when I go back and view it it's still in there...but for some reason it doesn't show up in the HTML when I inspect element. The h2 tag shows up but not the div wrapped around it.

Thoughts on how to fix this?

Add your header (for quick testing purposes, so you don't need to add it to a css file)

<style>
 .some-class { border: solid red; }
</style>

To double check that indeed it's not there.

If it's not there (you don't see anything red), then try using Global: Text area instead and use Full HTML as your text format.


Save multi value in multi value field programmatically apologize every one , my code was correct , I had a mistake in content type .2 similar content type with 2 similar image field :P

but I let it and don't delete this because maybe be useful in futures

I want to save multi image in multi image field programmatically(I set number of value to 5)

Part of my code

        $node = new stdClass(); // Create a new node object
        $node->type = "prodcut_gift_display"; // Or page, or whatever content type you like
        $node->uid = $user->uid;
        $uri = file_build_uri($geturipath);
        $file = new stdClass;
        $file->uid = $user->uid;
        $file->filename = basename($uri);
        $file->uri = $uri;
        $file->filemime = file_get_mimetype($uri);
        $file->filesize = filesize($mainimg_url);
        $file->status = 1;
        file_save($file);
        $node->field_gift_image['und'][0] =(array) $file;
        /***************************************/
        foreach ($upimg_uri_path as $inx=>$upimgtemp){
        unset($file);
        $uri = file_build_uri($upimgtemp);
        $file = new stdClass;
        $file->uid = $user->uid;
        $file->filename = basename($uri);
        $file->uri = $uri;
        $file->filemime = file_get_mimetype($uri);
//        $file->filesize = filesize($mainimg_url);
        $file->status = 1;
        file_save($file);
        $node->field_gift_image['und'][$inx+1]=(array) $file;
        }

        /***************************************/

Then I try to get drupal_json_output , it seems node and image field with 2 value is  ok but only one value saved in field.where is the problem?(I check and sure that my image field is set multi and can get 5 value )

update
Also I try

$uri = file_build_uri($geturipath);

        $imgs_paths[]=file_create_url($uri);
        /***************************************/
        foreach ($upimg_uri_path as $inx=>$upimgtemp){
        unset($file);
        $uri = file_build_uri($upimgtemp);
        $imgs_paths[]=file_create_url($uri);
        }

   foreach ($imgs_paths as $i=>$img) {
    $file_info = system_retrieve_file($img, 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      $node->field_gift_image['und'][$i]['fid'] = $file_info->fid; //assign image
    }
  }
        /***************************************/
        $node->field_product['und'][0]['product_id'] = $my_prodcut->product_id;
        $node->title = arg(1) . '-' . rand(1, 999999);
        $node->language = 'fa';
        $node = node_submit($node);
        node_save($node);

Also my field settings

As per my understanding you are trying to create a new article content type with multiple images. Assuming that you have the path of the images. In Drupal 7 you can use the below code

  $node = new stdClass(); // We create a new node object
  $node->type = "article"; // Or any other content type you want
  $node->title = "Article title";
  $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
  //$node->path = array('alias' => 'your node path'); // Setting a node path
  node_object_prepare($node); // Set some default values.
  $node->uid = 1; // admin id
  // Let's add standard body field
  $node->body[$node->language][0]['value'] = 'This is a body text';
  $node->body[$node->language][0]['summary'] = 'Here goes a summary';
  $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field
  // Add images
  $image_limit = 5;
  $images = array(//images to attach to node
    '0' => 'http://cf.juggle-images.com/matte/white/280x280/drupal-logo-primary.jpg',
    '1' => 'http://cdn.flaticon.com/png/256/37187.png',
    '2' => 'https://www.drupal.org/files/project-images/logo-128x128.jpg',
    '3' => 'http://guillermocerezo.com/sites/default/files/field/image/drupal-logo_0.jpg',
    '4' => 'http://drupalcrafters.org/sites/default/files/DrupalCraft-logo_0.png'
  );
  for ($i = 0; $i < $image_limit; $i++) {
    $file_info = system_retrieve_file($images[$i], 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      $node->field_multiple_images[LANGUAGE_NONE][$i]['fid'] = $file_info->fid; //assign image
    }
  }
  $node = node_submit($node); // Prepare node for a submit
  node_save($node); // After this call we'll get a nid
  drupal_set_message('article  saved !!!');
  watchdog('info', 'Article node created');


How can get path of image (src) in twig template of a module? How can I get access to image path (source/url) in twig template of a module?
I try to render an image that's located in my module folder in module template, this image is a static image that's not assigned to a field.
I try several methods to achieve this demands for eg:

and below method:

MyModule.module

function MyModule_preprocess(&$variables, $hook) {
    $variables['base_path'] = base_path();
}

and then in template:

And i try solution that's written in this article too: Using images in custom module
But both of them refer to my theme directory instead of module directory and seems none of them work in module template.
Thanks for any solution.

You need to use file_create_url much like Drupal 7 to transform a file path to file url. To get the path to the module, you should use drupal_get_path, combined it could look like this:

function my_module_preprocess(&$variables, $hook) {
  $variables['img_path'] = file_create_url(drupal_get_path('module', 'my_module') . '/image/icons/my-image.svg');
}


Why does my Rules Action about booking a time slot appear to not be executed? I recently installed the Booking time slot module and got it to work as expected.

The issue I have is that its "Rules event" does not trigger a Rules Action. Here is my rule (for now it only includes a Rules Action to show a Drupal message):

{ "rules_booking" : {
"LABEL" : "Booking",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entity" ],
"ON" : { "booking_insert" : [] },
"DO" : [ { "drupal_message" : { "message" : "Success!" } } ] } }

I have tried using various events (After saving a new booking, After updating an existing booking) but none appears to work.

I wondering if anyone has had this kind of experience or knows what could be wrong.

Update

Here is a screenshot of the Rules Events I can select:

I'm about sure that the answer to your question can be found here.
And to be 100%, I recommend you do some Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".

Update

Your (1st) comment confirms what I wrote in my answer even more. Have a look at the source code and let me know where I can find more details about any of those "Various events" that you try to use are actually coded. I trust they are somewhere (since your question says you use them), but with my limited knowledge of Rules (hm, hm) I cannot find them ... in the typical ".inc* file where the Rules module expect them to be located. But since "I" cannot find them, it may well be that that also explains why the Rules module cannot find them ...


Additional form validation only after passing default validation In Drupal 6.25.

I am building a custom user registration form that needs to run some actions on an external service after properly passing default form validation but before creating a new user record in Drupal. So far I am doing the following:

function mbrusers_form_alter(&$form, &$form_state, $form_id){
   if($form_id == "user_register"){
       if($default_form_validation_passed){
           $form['#validate'][] = 'mbrusers_infusionConnect_validate';
       }
   }
}

function mbrusers_infusionConnect_validate($form, &$form_state){
    // Run actions on external service
    if($error){
        form_set_error("", "SET ERROR");
    }
}

I feel like I'm overlooking something, but I haven't been able to figure out what to do. Maybe using validate is the wrong idea? Any help that sets me in the right direction is appreciated.

I'm pretty sure you have to re-arrange the order of the validators, and inject yours basically in the middle instead of just adding it at the end.

From user.module, $form['#validate'] = user_login_default_validators(); or:

/**
 * Set up a series for validators which check for blocked/denied users,
 * then authenticate against local database, then return an error if
 * authentication fails. Distributed authentication modules are welcome
 * to use hook_form_alter() to change this series in order to
 * authenticate against their user database instead of the local users
 * table.
 *
 * We use three validators instead of one since external authentication
 * modules usually only need to alter the second validator.
 *
 * @see user_login_name_validate()
 * @see user_login_authenticate_validate()
 * @see user_login_final_validate()
 * @return array
 *   A simple list of validate functions.
 */
function user_login_default_validators() {
  return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
}

and

/**
 * A validate handler on the login form. Check supplied username/password
 * against local users table. If successful, sets the global $user object.
 */
function user_login_authenticate_validate($form, &$form_state) {
  user_authenticate($form_state['values']);
}

so I'd do something like:

$form['#validate'] = array('user_login_name_validate', 'mbrusers_infusionConnect_validate', 'user_login_authenticate_validate', 'user_login_final_validate');

instead of if <Default form validation passed> so that your validation function is called before the normal/usual second validator.


database access to databases I have a drupal with many external databases. I do the same things in all databases but I want to limit the access to the database basing on the role the logged-in user has.

I mean:

The administration user has access to all databases
Employee has access to db1 and db2
Worker has access to db1

How can I control database access per role?

If you mean controlling which database Drupal uses for its own database tables (e.g. the table containing all the registered users, the active sessions, the nodes created), then it is not possible. There is no way to tell Drupal which database use basing on the user's roles.

If you are asking about your own module, then it is possible, but your module needs to handle this on its own because Drupal doesn't have my specific functions to handle your use case, except the following ones:

user_has_role() checks the user account passed as argument (or the currently logged-in user) has the role passed as argument
db_set_active() set the database used from the successive database API calls using one of the keys set in the settings.php file

Rather than using db_set_active(), I would use $options['target'] which can be used from any Drupal function necessary to query the database.


How do I create a file download URL? The function file_entity_download_uri() seems to no longer exist in Drupal 8.4, and I need to build a download URL for a file. I would not like to directly expose the file location.

If you used a Media field, I built a module for this purpose: http://drupal.org/project/media_entity_download - it will take file(s) in a media object and give them an instant download uri. It will not show the actual file path to the user.

If you just have a file field, you're basically looking at what private files option does.

In the end, you'd need a solution that ensures a BinaryFileResponse from a controller, you can see an example in my module.


drupal_mail() sends two emails, second email is empty I'm using the following code for sending out an email with drupal_mail()

$module = 'example_module';
$key = 'key';
$language = language_default();
$params = array();
$from = 'email@email.com';
$send = TRUE;
$message = drupal_mail($module, $key, $order->mail, $language, $params, $from, $send);
$message['subject'] = 'Subject';
$message['body'] = $message_body;

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);

I get two emails after the function that contains this runs, one email is perfect, the other email is completely empty.

The function that contains the code above only runs once, I tested by printing out some text with dsm().

How can I fix this?

Thank you!

The drupal_mail() function you call will send an email.

Then when you call $system->mail($message); that will send a second email.

Here is an example of how to use drupal_mail (taken from here):

/**
* Implements hook_entity_insert().
*
*/
function dummy_module_node_insert($node) {
  $module = 'dummy_module';
  $key = 'dummy_key';
  $language = language_default();
  $params = array(
    '@url' => url('node/' . $node->nid, array('absolute' => TRUE)),
    '@title' => $node->title,
  );

  drupal_mail($module, $key, $mail, $language, $params);
}

/**
* Implements hook_mail().
*/
function dummy_module_mail($key, &$message, $params) {
  $message['subject'] = t("@title event registration confirmation", $params);
  $message['body'] = array();
  $message['body'][] = t("Hello", $params);
  $message['body'][] = t("Node has been created @title (@url).", $params);
}

The user who posted this code originally labeled it as "The propper way to use this:" and I've had success using this code before.


How to get each field value in views-views-unformatted--view-machine-name.html.twig? I have an twig file: views-view-unformatted--view-machine-name.html.twig

{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

I want to have Title and body field to be in 1 line separated by comma like:

title, body

How can I get value of 'title' or 'body' or any other field in this view while debugging?

I used kint(title) and kint(body) but it's not working. I also made debug = TRUE; in services file.

But can't figure out the way of having fields value in unformatted html twig.

I have found a Way using Kint, You can get field values in views-view--unformatted.html.twig

if you want a specific field

To get text fields value

{{row.content['#row']._entity.field machine name[0].value}}

To get image fields src

{{file_url(row.content['#row']._entity.field machine name.entity.uri.value)}}

To get image alt,title,width,height

{{row.content['#row']._entity.field machine name[0].alt/title/width/height}}

  Note :  replace field machine name with your fields machine name

If you Want to loop through multiple field

{% for i in range(0, 10) %}
  {{ row.content['#row']._entity.body[i].value }}
{% endfor %}

If you Want raw value

{% for i in range(0, 10) %}
  {{ row.content['#row']._entity.body[i].value|raw }}
{% endfor %}


AJAX auto on views (without clicking submit button) I'm working on a view with exposed filters ; I want it to be reloaded when a select list (based on a taxonomy) has its value changed by an user. However, by default, AJAX in Views needs a click on the submit button : "Options such as paging, table sorting, and exposed filters will not initiate a page refresh."

How can we improve that ? Why does Views not offer an option for that, it's not just about perfs considerations ?

thanks !

If you enable AJAX in Views, you can also edit "Exposed Form Style" settings. There is a checkbox in there that says "Autosubmit" which will react whenever a user changes an exposed filter.

Edit: sorry, that is for Drupal 7. I see you have listed Drupal 8. For Drupal 8, this was removed and is now being added in an effort in the CTools module. You can see the updates here: https://www.drupal.org/node/2475595

According to this comment, you can apply the latest patch in that thread to CTools 8.x beta1 release, enable "CTools Views" module to add the functionality back in.


Empty value "- Select -" does not appear for select fields with states requirement When I create a standard select box using the Drupal 7 form API, the first value (also the one selected on a fresh 'blank form') is <option selected="selected" value="">- Select -</option>. This value is not specified in the form definition and I am doing no form altering. (This is fine)

However, when I create a second select box that depends on the first using #states, it does not have any such default value. For complex forms with multiple dependencies this inconsistency is a problem.

An example form definition is as follows:

function sb_quickquote_test_form($form, &$form_state, $post=array()) {

  $fields['first_select'] = array(
    '#type'             => 'select',
    '#title'            => 'First select box',
    '#options'          => Array('First', 'Second', 'Third'),
    '#required'         => TRUE,
  );

  $fields['dependent_delect'] = array(
    '#type'             => 'select',
    '#title'            => 'Dependent select box',
    '#options'          => Array('Something', 'Another thing', 'Something else', 'Final thing'),
    '#states'           => Array(
      'visible' => Array('select[name=first_select]' => array('value' => '2')),
      'required' => Array('select[name=first_select]' => array('value' => '2')),
    ),
  );

  $fields['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $fields;
}

In this simple example, we have 2 select boxes and a submit button. The two select boxes are displayed as:

 ______________      ________________
| - Select - |v|    | Something    |v|
`--------------'    `----------------'
| - Select -   |    | Something      | <- no empty option
| First        |    | Another thing  |
| Second       |    | Something else |
| Third        |    | Final thing    |
 --------------      ----------------

(Because of the #states setting, the second select box only appears when the first select box has "Third" selected)

This inconsistency is causing problems in a situation where we are generating complex dynamic forms with inter-dependant fields.

Does anyone have any idea why the fields are being given inconsistent options and what the best approach is to work around the problem?

To force the "empty option", assign it with something like:

"#empty_option"=>t('- Select -'),


Primary and secondary zone's links in drupal 7 This is my website in drupal 7. The page at http://150.254.36.80/wige/kandydaci/aktualnosci shows the following header.

I would like that "kandydaci" in this white menu will be active (black lighted) in every page in this zone, for example on http://150.254.36.80/wige/kandydaci/o-wydziale.

We are in the "kandydaci" zone, but the white menu doesn't show it.

You can use the Menu Position module to accomplish this.

After installing:

Visit /admin/structure/menu-position
Click "Add menu position rule"
Select the parent menu item "kandydaci"
Add a page restriction for "kandydaci/*"

This should keep the "kandydaci" menu link active on the correct pages.


Breadcrumb trail not displaying correctly in custom module I'm working on developing a custom module for Drupal 7.  Part of the module that I'm creating is a form editing component (with an entirely different aim from something like cck, which is why I am re-inventing the wheel here). I've got one page registered to display a list of all the forms, and another registered for viewing and editing a specific form.  I would like the breadcrumb on the viewing page to include a link to the listing page, however it does not appear.  I am getting "Home » Administration » Jarrow ETD System", while I would like to have a "Form Editor" component on the end.  The relevant hook_menu code looks like this:

$items['admin/settings/jarrow'] = array(
  'title' => t('Jarrow ETD System'),
  'description' => t('Configure the core settings for the Jarrow ETD system'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('jarrow_configure'),
  'access arguments' => array('administer etd'),
  'type' => MENU_NORMAL_ITEM,
);

$items['admin/settings/jarrow/forms'] = array(
  'title' => t('Form Editor'),
  'description' => t('View All Forms'),
  'page callback' => 'jarrow_list_forms',
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_LOCAL_TASK,
  'weight' => 40,
);

$items['admin/settings/jarrow/forms/%/view'] = array(
  'title' => t('Form View'),
  'description' => t('View a Form'),
  'page callback' => 'jarrow_view_form',
  'page arguments' => array(4),
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_NORMAL_ITEM,
);

There are a significant number of other pages registered, which I have omitted.  Aside from the fact that I probably shouldn't be using 'admin/settings' as my base url, I can't see anything wrong with the menu structure.  Oddly enough, if I add in the following code to hook_menu, I get the right result:

$items['admin/settings/jarrow/stuff'] = array(
  'title' => t('Stuff Editor'),
  'description' => t('View All Forms'),
  'page callback' => 'jarrow_list_forms',
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_LOCAL_TASK,
  'weight' => 40,
);

  $items['admin/settings/jarrow/stuff/%/view'] = array(
  'title' => t('Stuff View'),
  'description' => t('View a Form'),
  'page callback' => 'jarrow_view_form',
  'page arguments' => array(4),
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_NORMAL_ITEM,
);

This is exactly the same entry into hook_menu, down to the function it's calling, except for the url having "stuff" in it instead of "forms".  However, the breadcrumb trail displays properly: "Home » Administration » Jarrow ETD System » Stuff Editor".

I took a look at the inner workings of menu.inc, and traced the execution.  It appears that when Drupal assembles the menu tree for the form, it is including the child /view, whereas for "stuff" it does not.  I can't for the life of me figure out why, and I am hoping someone with experience dealing with drupal's menu system can provide some explanation as to why the menu would be constructed as such.

After making a completely unrelated change to my hook_menu, the breadcrumb fixed itself.  I don't know why though.


Create an autopath or a token using entity reference of entity reference I have created a new node type "station". This node type has an entity reference to another node type "location", which in turn has an entity reference to a node type "prefecture".

I would be interested to have an autopath for the station, which would be of the form
http://www.website.com/[prefecture:name]/[station:name]

The problem is that prefecture:name does not appear in the tokens for node 'station'. Any idea how to go further with this?

Ok, that was easy. One has to enable the Entity Token module, which creates automatically nested tokens for all depths of entity references.


How to avoid calling FieldCollectionItemEntity::deleteRevision Sorry about the confusing name. I have the following problem. I have a migration for a content type that has a multivalue field-collection-item (~50 items there in average per content). The migration is fairly quick, 150 items/min. However the migration-update is very slow, 10 items/min. I've checked with xhprof and 95% of the time it spends inside FieldCollectionItemEntity::deleteRevision - basically deleting the old field collection items when re-populating the node with the new ones.

The content type has the revisions turned off, so the number of related revisions should be 1 all the time, not more. Is there any smart way to avoid this massive time that it takes?

I'm wondering if the Entity API has a queue system to save these delete operations for later. Or somehow removing revisions completely?

Thanks you

Copy and Paste your own version of the FieldCollectionItemEntity class file and call it like FieldCollectionItemEntity2. Then simply like have FieldCollectionItemEntity::deleteRevision return or do a NO-OP. Use the new class in your migration instead of the default one you're using now.

For when the migration completes; implement like a PostImport() function to delete all but the most recent revision.

To my knowledge there is no Queue of revision items. A node/entity Save (and revisioning) I thought is done in a sql transaction statement.


Error installing CiviCRM Following the amazing work @david-snopek posted:

Blog post - CiviCRM & D8,
David's StackExchange Post.

I spent the better part of last evening trying to get CiviCRM up and running on a Drupal 8.4 BLT project.

After trying a few different approaches, unfortunately I'm now seeing the following error when trying to enable the CiviCRM Core Module

  CiviCRM must be downloaded into the libraries folder.

No matter what I try, I can't seem to get the module to recognize that civicrm is installed.

Other things I've tried:

manually copying the [project_root]/vendor/civicrm-core into [project_root]/docroot/libraries/civicrm-core
Renaming libraries/civicrm-coreto libraries/civicrm
Modifying composer.json to try and install CiviCRM into the libraries folder:
Creating symbolic links to the folder (my least favorite attempt)

Here is the composer.json update for number 3 above:

    "require": {
    "acquia/blt": "^8.3",
    "phpoffice/PHPWord": "dev-zend-version as 0.13.0",
    "civicrm/civicrm-core": "4.7.25"
},

...

"repositories": {
    "phpword": {
        "type": "vcs",
        "url": "https://github.com/dsnopek/PHPWord.git"
    },
    "zetacomponents-mail": {
        "type": "vcs",
        "url": "https://github.com/civicrm/zetacomponents-mail.git"
    },
    "civicrm": {
        "type": "package",
        "package": {
            "name": "civicrm/civicrm-core",
            "version": "4.7.25",
            "type": "drupal-library",
            "source": {
                "url": "https://github.com/civicrm/civicrm-core.git",
                "type": "git",
                "reference": "origin/master"
           }
        }
    }
}

source: https://gist.github.com/mortenson/a5390d99013b5b8c0254081e89bb4d47

I think this has to do with an autoloader issue perhaps seeing that BLT does not use the Drupal composer.json file and the instructions @david-snopek posted were for the traditional Drupal installation method.

I was able to trace the error to modules/custom/civicrm-drupal/civicrm.install:125.

/**
 * Returns the path to where CiviCRM is installed.
 *
 * @return string|void
 *
 * Recommended location for civicrm is in /libraries/civicrm [citation needed].
 * We also allow /modules/civicrm, which seems to work fine.
 */
function _civicrm_find_civicrm() {
  if ($path = drupal_get_path('module', 'civicrm')) {
    if (file_exists($path . '/CRM/Core/ClassLoader.php')) {
      return \Drupal::service('file_system')->realpath($path);
    }
  }

  $path = 'vendor/civicrm/civicrm-core';
  if (file_exists($path . '/CRM/Core/ClassLoader.php')) {
    return \Drupal::service('file_system')->realpath($path);
  }

  return NULL;
}

Notes on my process:

I ran into a couple snags with the Gist David posted.

When running $ composer require 'phpoffice/PHPWord:dev-zend-version as 0.13.0', I noticed that Composer was trying to add the dependency as:

"require": {
    "phpoffice/PHPWord": "dev-zend-version",
    "as 0.13.0"
},

This failed but I was able to get past the issue by manually adding the dependency to the composer.json file as:

    "require": {
        "acquia/blt": "^8.3",
        "phpoffice/PHPWord": "dev-zend-version as 0.13.0",
    },

Unfortunately, I then got stuck on the next step requiring civicrm-core until I read the comment a bit closer. I believe this step is now incorrect as civicrm-core 4.7.25 has been released.

#Require civicrm-core at the requested version.
#TODO: Need to keep using my fork until 4.7.25 is released!
#composer require civicrm/civicrm-core:$CIVICRM_VERSION
composer require "civicrm/civicrm-core:dev-roundearth-$CIVICRM_VERSION as $CIVICRM_VERSION"

I was able to get past that issue by updating the additional repository via:
composer config repositories.civicrm-core vcs https://github.com/civicrm/civicrm-core.git

Reference:
https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm

Following literally the instructions for manual installation as given by David Snopek (https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm) I succeeded in installing civicrm 4.7.27 under Drupal 8.4.2.

One caveat: I installed Drupal with composer (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies), using option B on that page "drupal/drupal" as using this option put vendor under the document root, something that is necessary according to David's blog post. In the Drupal documentation it is indicated that with option B one must manually add some lines to the composer.json file but, at least with 8.4.2, it is all there. But the error code about the libraries folder may indicate that these lines are not available in your composer.json file.

I cannot provide additional help but at least, the instructions from David seem to work still with the latest versions of both Drupal and Civicrm.


How to resist anonymous user to access module internal files? eg. path starts from \Drupal\module\mymodule\files I have one file placed in my module. I want that only authenticated users or admin can access the content of this file. For anonymous users, it should be shown 'You don't have permission to access...'

Link is like Sample File'

Right now issue is, even if i logged out, I am able to see the content of this link.

I tried this:

if(isset($user->roles[1])) {
        global $base_url;
        return $mylink;
      }

but above code is not working for me.

What is the best possible way to achieve this?

If I've understood your requirement correctly, you've some files other than normal Drupal files, like csv, txt which should not be accessible to Anonymous user.

This should be done at .htaccess level or you can give a try to private file system in Drupal Core. Check the ans given to "how to restrict file access to specific user roles" for more details on Private File system. The question is related to Drupal 7 because of which contributed modules will not be available for Drupal 8. But you can check configuration options mentioned for Drupal 8 Core.


Use datefield year as condition in Entity Query I'm performing an entity query that searches for nodes of my custom content type called 'news'.
The content type has a date field called 'field_date'. I want to be able to perform the query in a way that only produces the 'news' nodes that have a 'field_date' that fits within a specified year. Here is an attempt I made below.

$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', [date('Y','field_date'), $year], '=')
  ->range(0, 10);

In the code above I'm attempting to only grab the year from the 'field_date' datefield and compare that to $year, 2015 in this case. However I receive SQL errors like:

  Invalid parameter number: number of bound variables does not match
  number of tokens

I'm guessing part of it is date('Y','field_date') doesn't know what 'field_date' is but I'm not sure how to go about it.

How do I make a year comparison on a datefield in a entityquery condition?

Assuming the data in the database looks like this: "2015-10-12T21:30:00", you can use a like query

->condition('field_date', $year . '%', 'like')

Your code revised with the change:

$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', $year . '%', 'like')
  ->range(0, 10);


Why doesn't drush respond to commands after install Setup

I just followed the directions on the drush website for installing drush.

I performed the command php -r "readfile('http://files.drush.org/drush.phar');" > drush

Then attempted the next command php drush core-status which resulted in lots of text basically saying "Permission Denied".

So I went ahead and performed the next direction which makes the scripts executable. chmod +x drush

The Problem

I then attempted php drush core-status again.

Now the console just sits there when I type the command. It displays nothing and never released back to prompt. I had to ctrl+c to free up the console.

The Question

What am I doing wrong here? Are their dependencies on drush that are not listed in the install document? Is their some way to see errors that are not printed to the console?

I was using php 5.4 originally but updated to 5.5 and that did not solve the problem. CentOS 6.7.

At the time of my comment the phar for drush wasn't working correctly. That very well may be fixed by now, however, I've still found installing drush via composer to be the easiest solution.


Adding an input filter to automatically replace text with HTML via a script I am using Drupal 8 on Pantheon.

This is a website for an ebook.  The ebook HTML was generated using a Perl script that automatically replaces text like this:

APPLE -> HTML including an apple image
ORANGE -> HTML including an orange image

The list of these replacements is kept in a plain text file (there are about 200 replacements), and then there is a relatively short Perl script that does the actual replacing (for the ebook).

Now, I want to use these replacements in my Drupal site.

Following this lullabot tutorial, I created a custom input filter in a custom module.

But now I am wondering about how I should proceed.

In the future, the replacements for the ebook will be changed every month, so I need to make sure that it isn't too painful to keep the ebook replacements and Drupal replacements in sync (ideally, I would use the same files).

So,

Should I try to find a way to call the Perl script from within Drupal, and share the exact same code between Drupal and the ebook?
Or should I rewrite the Perl script in PHP and incorporate it into the custom input filter?
Or should I do something else entirely?

I would rewrite the relatively short script. This shouldn't be a problem because you can re-use the Perl Regex in PHP, see http://php.net/manual/en/book.pcre.php

More Drupal specific would be caching. Add a cache tag to the filter result

  public function process($text, $langcode) {
    ...
    $result = new FilterProcessResult($text);
    $result->addCacheTags(['mymodule:filter']);
    return $result;
  }

so that you can invalidate the cached entities when the replacement text file gets updated:

\Drupal::service('cache_tags.invalidator')->invalidateTags(['mymodule:filter']);


How can I update text_format value in Ajax callback? I have a Drupal 8 form that includes the following fields:

// Comtainer for message fields and preview.
$form['email'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
);

// Template selection drop-down.
$form['template']['template_select'] = array(
  '#type' => 'select',
  '#title' => $this->t('Select template to use (overwrites message)'),
  '#options' => $options,
  '#default_value' => 1,
  '#ajax' => array(
    'wrapper' => 'email',
    'callback' => array($this, 'updateEmailTemplate'),
    'event' => 'change',
  ),
);

$form['email']['message']['subject'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Message subject'),
  '#default_value' => $params['subject'],
  '#ajax' => array(
    'wrapper' => 'preview',
    'callback' => array($this, 'updateEmailPreview'),
    'event' => 'change',
  ),
);

$form['email']['message']['body'] = array(
  //'#type' => 'textarea',
  '#type' => 'text_format',
  '#title' => $this->t('Message body'),
  '#description' => $this->t('Text for the email body. you may use the following tokens: @tokens.', ['@tokens' => SimpleConregTokens::tokenHelp()]),
  '#default_value' => $params['body'],
  //'#value' => $params['body'],
  '#format' => $params['format'],
);

My Ajax callback function is:

  // Callback function for Template drop down - load message fields with template.
  public function updateEmailTemplate(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $templates = $form_state->get('templates');

    if (!empty($template = $form_values['template']['template_select'])) {
      //Code here to determine new form values.

      $form['email']['message']['subject']['#value'] = $params['subject'];
      //$form['email']['message']['body']['#type'] = "textarea";
      $form['email']['message']['body']['#value'] = $form['email']['message']['body']['#default_value'];
      $form['email']['message']['body']['#format'] = $params['format'];
    }
    return $form['email'];
  }

So what's happening?

When the user chosen selects a template from the dropdown, the text_format doesn't update.

If I change the #type of the field from text_format to textarea, it will update without any problems, which suggests the callback should work.

I though there might be something in the text editor JavaScript preserving the text_format field from being updated, but if I explicitly set the #value in the form building function, it starts updating in the callbacks. The problem with this is that it also overrides the value when the form is submitted.

Finally, I've tried adding a line to the callback to set the #type to a textarea, and this is also getting ignored. The callback is still getting called, however, because the supbect textbox does update.

Any ideas where I'm going wrong? I'm particularly confused as to why the textarea version works perfectly but changing to text_format doesn't.

James

Don't change $form in an ajax callback. See this documentation for D7:

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7

  Details and Warnings

  Changes to the form must only be made in the form builder function, or
  validation will fail. The callback function must not alter the form or
  any other state.

For D8 there is in the moment only documentation for the new syntax, but not for the basics. Use the D7 doc's instead.


How to make custom fieldset collapsed by default in Drupal 8 In Drupal 7 there was option to have fieldset collapsible or not, and to restrict default state of this form element (collapsed, or uncollapsed). Example:

$form['contact_data'] = array(
        '#title' => t("Contact data"),
        '#type' => 'fieldset',
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
);

Now, in Drupal 8 I cannot find attributtes #collapsible and #collapsed in Drupal\Core\Render\Element\Fieldset. In official documentation of Fieldset element is not mentioned any new element, which should substitute the Fieldset element.

Also there is not Form API elements overview for Drupal 8, such as for Drupal 7. You have to manually search for all Render Elements definition in code, which is more time consuming (especially when you would like to see elements overview and compare them).

All collapsible fieldsets have been replaced with HTML5 details
  elements.

Fieldset and legand are very hard to style and its not recommended to use with Drupal 8 any more. Instead its replaced with more cross browser way, which is the HTML5 Details & Summary tags.

'#type' => 'details'

https://www.drupal.org/node/1852020

Drupal 7

$form['advanced'] = array(
  '#type' => 'fieldset',
  '#title' => t('Advanced settings'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#description' => t('Lorem ipsum.'),
);

Drupal 8

$form['advanced'] = array(
  '#type' => 'details',
  '#title' => t('Advanced settings'),
  '#description' => t('Lorem ipsum.'),
  '#open' => TRUE, // Controls the HTML5 'open' attribute. Defaults to FALSE.
);


Error entries in Watchdog duplicated dozen and hundreds of times I have seen that the table watchdog in my MySQL database is growing enormously, and after TRUNCATE, I see that for each visit to a single page, it generates hundreds of inserts, and when seeing them, they appear to repeat dozen and dozen of times. How can I trace where the error is, because I would bet this is a misconfiguration or something. I am worry that Drupal is making thousand of redirections, I have no other explanation, the pages load fast but the machine has a lot of RAM and hardware, so maybe I am loosing performance somewhere.

The best is to check what these entries are and try to fix them, e.g.:

when the warning/error comes from contrib module, consider searching for this specific error and find out what's the solution (sometimes it may be misconfigured module),
when warnings comes from your custom modules or themes, consider fixing it manually.

If you think you cannot fix the source of the issues, you should introduce caching mechanism to your site such as:

Redis/Memcached which will limit enormous number of inserts into cache tables.
Varnish to cache the front end pages.

or limit the entries by:

limiting watchdog entries to warnings only (ignoring PHP notices) or silence all of them.
disabling dblog (database logging) module completely and switch to syslog logging instead.

See also: How do you improve Drupal performance?


Can I pass variables from more specific template/preprocess function up to less specific? I need to display a node as a block, so I went with the most obvious way and created a view with a display block and this very node in it. But now I need to style it and I can't pick up the proper template. block-views.tpl.php looked great, but being in this template I do not seem to have access to view's variables anymore, have I? Basically I need a place where I could have access to view's variables and control over the look of the block. If I could just pass variables up the chain, that would be great...

Nodes In Block or Node Block can help to place nodes in blocks.

The other part, to theme that particular node can achieved by different scope of templates from general to specific node templates. e.g.

node.tpl.php
node-[type].tpl.php
node-[nid].tpl.php


How to grant edit access for specific nodes to 1 or more selected users? I am building a school site on Drupal 8.  Among others, I have two content types, one for teachers, one for courses.  Teachers also have user accounts and belong to a role, say 'teacher'.

I want teachers (authenticated site users who belong to the 'teacher' role) to be able to edit the pages of the courses they teach.  The problem is, there are courses which are being taught by more than one teacher, hence I can't solve this simply by enabling 'edit own content' and have them as owners.

So all in all, I want to give 'edit access' for specific nodes, to specific, sometimes multiple, users.

I researched before asking this fairly simple question.

There is a very similar question here - however its four years old, and the node access module which is suggested as a solution is not usable for Drupal 8 yet.

There is a mention of another module, flexi access, but that is only available for Drupal 7.

There is also a link to ACL, "an API for other modules to create lists of users and give them access to nodes", but that in itself is only in pre-release for Drupal 8, and a module which seems to be using it, Content Access has open security issues (and also is in pre-release status).

Searching around, I also found Permissions by Term module, seems stable and very well documented, however I didn't find it very intuitive to be honest, and also it seems to cater basically for restricting view access to nodes (as suggested here, but also from its video tutorial).

I want something simpler.  And I obviously want all nodes to still be publicly viewable by anyone (even anonymous users, of course).  So although Permissions by Term seemed a possible choice, I don't know if I can/should use it.

There is also the Group module which is frequently referenced, but that also seems an overkill and way too complicated for the simple task I want to accomplish.

I 'm a bit lost on this one .. It seems quite simple, yet I can't find a way to do it.  Any help would be greatly appreciated ...

The Group module is what you should be looking at ... It's not °overkill° (as in your question), instead it's the only stable contributed D8 module available today that will also address your needs.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Note:

Let me address (part of) your additional comment below this answer also, which is like so:

  I will need to have quite a few Groups in my case - one for each course taught by more than 1 teacher.

If I was to configure the Group module for your case, I would use an approach like so:

Create a Group type = Courses.
Create Group roles =  Teacher and Student.
Create exactly 1 Group for each possible Course, labeled (say) C1, C2, C3, ....
Only grant the Group Permission to "edit" a node of content type "Course" to users who have been granted the "Group role" Teacher. And as per your "I want all nodes to still be publicly viewable by anyone (even anonymous users)", you want to grant "View" access to "Outsiders" and "Anonymous", and probably also to "Students".
If only teacher (user) T1 is teaching Course C1, then only T1 is granted the Group role "Teacher" for (group) C1.
If teachers (users) T2 and T3 are teaching Course C2, then only T2 and T3 are granted the Group role "Teacher" for (group) C2.
When creating nodes of type "Course", assign them to 1 (and only one) Group (so either C1, C2, or C3, or ...). And decide about which teacher(s) (user(s)) Tx the newly created Course will be granted the Group role "Teacher".

Done ...

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to preallocate form I'm using the Follow module and I'd like to modify the form, where I can preallocate the beginning of the form, like in the picture shown below:

May I know how can this be done?

You need to make a custom drupal module then implement a form alter to add a #field_prefix to the form element.

In this case specifically, it would be like this:

/**
 * Implements hook_form_alter().
 */
function MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
    $form['FIELD_NAME']['#field_prefix'] = t('PREFIX_TEXT');
  }
}

You will need to change the following in that code sample to suit your form:
MODULE_NAME: The name of your custom drupal module.
FORM_ID: The form id of the form you want to alter. In this case the forward form.
FIELD_NAME: The machine name of the field you want to add a prefix to.
PREFIX_TEXT: The text you want to put in front of the field.

To work out the form id of the form you want to alter, install the devel module, and just inside your form alter function add the following line:

dpm($form_id);

Now whenever you load a page you will see the form ids for all the forms on the current page, so go to the page with the forward form and you will see the form id.

To get the field machine name of the field you want to add the prefix to you use the same method.

So after you have added the form id to the code sample, then just inside that if statement add:

dpm($form);

Then when you go to the page with the form on it you will get a display of the form, which you can click to expand.
Expand it and you will see a list of the form elements in the form, the keys are the machine names of the elements.

When you are done you can remove the dpm() calls and uninstall the devel module.


Is it possible to add translation to smiley alt and title in CKEditor? I'm using Drupal 7 with CKEditor module which permit to insert smiley from editor. I've found that the source code of CKEditor fix the smiley description in JS :

config.smiley_descriptions = [
    'smiley', 'sad', 'wink', 'laugh', 'frown', 'cheeky', 'blush', 'surprise',
    'indecision', 'angry', 'angel', 'cool', 'devil', 'crying', 'enlightened', 'no',
    'yes', 'heart', 'broken heart', 'kiss', 'mail'
];

So when I insert a smiley, the code will be

<img alt="laugh" height="23" src="//cdn.ckeditor.com/4.4.3/full-all/plugins/smiley/images/teeth_smile.png" title="laugh" width="23">

But I want to modify the language of alt and title attributs according to the language  used in my site.  Is it possible to do that?
Thanks in advance.

Never tried but I'm pretty sure that's possible.

If you use the ckeditor module, you can alter JS settings through PHP with hook_ckeditor_settings_alter.

Knowing that, it becomes pretty easy to wrap all strings with the t() function:

function yourmodule_ckeditor_settings_alter(&$settings, $conf) {
  foreach ($settings['smiley_descriptions'] as $key => $smiley) {
    $settings['smiley_descriptions'][$key] = t($settings['smiley_descriptions'][$key]);
  }
}

If you use the wysiwyg_ckeditor module, you can use hook_wysiwyg_plugin. That's pretty much the same thing, you can find a pretty good example on how to use this hook here.

Again, the code hasn't been tested, but it should be a good starting point ;).


Can I create a drush make file and installation profile from existing site? I have an existing Drupal site, that I would really like to be able to put entirely (or as much as possible) into code and use drush, a git repo, and installation profiles to be able to properly track my code and do rebuilds on my site. Is it possible to create this from an existing Drupal site. If so what are the steps to achieve this?

Profiler and Profile Builder, while useful, are for building a new profile using tools and libraries.  If you would like to convert an existing site into an installation profile, please see:

http://drupal.org/node/1368242

This issue contains a Drush command to build a Drupal 7 installation profile from an existing site.  The issue is marked as "needs work" because the code templates for Drupal 6 are not in place yet, but if you're working on a D7 site, it should do the trick for you.


On quantity change, create individual line items of the same item in Drupal Commerce cart Here is a more detailed explanation:

In Drupal Commerce cart, when a customer sets the quantity of a product from 1 to 5 for example, on 'Update Cart', we'll need 5 individual line items of the same product with quantity 1 each.

I've gotten this far on solving the problem but I'm not sure how to continue:

<?php
/**
 * Implements hook_entity_update
 */
function mymodule_entity_update($entity, $type){
  if ($type == 'commerce_line_item'){
    $original = intval($entity->original->quantity);
    $updated = intval($entity->quantity);

    if ($original != $updated){
        $new_product = $entity;
        // Create as many individual line items of the same product as needed, save them and add them to the order
    }
  }
}

I've tried to use commerce_line_item_save() to save $new_product, which is in this code snippet should be a clone of the line item. I've tried it with increasing the line item id and save it that way but I just got DB errors.

How can I make this happen in a nice way? Thank you!

It would be possible to create a new views handler based on commerce_line_item_handler_field_edit_quantity that worked the way you want, but IMHO it would be weird from a UX POV to enter 5 into the quantity textfield of 1 line item, submit, and then see 5 distinct line items with quantity 1.

A simple alternative would be to modify the cart view to have something like an Add 1 more button:

Remove the quantity field;
Add a relationship to the product;
Add the product's add to cart form as a field;
Configure the field to not combine products (and you can also modify the text here, eg Add 1 more).

I haven't tested this, but I think it should work.


Executing PHP code only once, when the node is created I am using Drupal 7 with  the Token module.
I wrote PHP code using the token field that can satisfy loading a specific node, updating some field values, and saving the node (using node functions).

When editing this node the code run again; I just want to run this code when creating this node. How can I do that?

You should use hook_node_insert in a custom module to run your code when the node is created.

function hook_node_insert($node) {
  // To include @marcvangend's comment.
  if ($node->type == 'type') {
    // Run code here only for node of type 'type'.
  }
  // Run code here for all nodes...
}


Upload multiple files and directories Is there a way to upload files and directories, and make Drupal keep the structure in the destination folder?

If you are willing to upload zip files, then maybe Pack & Upload could work for you.

Although I haven't used this before, I would assume that folder structure would remain.


Replace \Drupal::service with Dependency injection in FieldWidget class I have created an ajax callback inside a custom Field Widget plugin. In the Ajax callback I have called a custom service using

$service = \Drupal::service('service.name')

I am using phpmd to clean up the code and it suggested that the service should be called using dependency injection.

This means I should create a constructor for the Fieldwidget class and then get it as argument. I am not sure how to pass the argument when the Field widget is called. Not even sure what interface should be set for the Drupal service caller.

Any ideas on how to do that.

This requires three steps:

Declare a property to hold the service.
Implement a __construct() method to populate the property from step 1.
Implement a create() method, to generate the service that is passed to __construct().

1) Declare a property to hold the service

In your class, declare the property that will hold the service.

/**
 * The example service.
 *
 * @var \Drupal\example\Service\ExampleService
 */
protected $exampleService;

With this, you can now refer to $this->exampleService within your class. However, at this point it is still NULL, so it needs to be populated.

2) Implement a __construct() method to populate the property from step 1

This is done by overriding WidgetBase::__construct(), and adding the service to it.

public function __construct(
  $plugin_id,
  $plugin_definition,
  FieldDefinitionInterface $field_definition,
  array $settings,
  array $third_party_settings,
  ExampleServiceInterface $exampleService
) {
  // Initialize the parent class:
  parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

  $this->exampleService = $exampleService;
}

Now the property from step one can be populated when the class instantiated. However, the service itself needs to be generated, and passed to the __construct() method.

3) Implement a create() method, to generate the service that is passed to __construct().

The service is generated in the create() method. This is done by copying the code from WidgetBase::create(), and adding the service to it. WidgetBase::create() looks like this:

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['third_party_settings']
  );
}

Notice that the values returned are the same values passed to the __construct() method, but without the example.service service. The example service needs to be retrieved from $container and added to the above, by implemented create() in your class as follows:

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['third_party_settings'],
    $container->get('example.service')
  );
}

This function call generates the example service, which passes it to __construct(), which in turn populates $this->exampleService, so it can be used in your class in place of \Drupal::service('example.service').


What is the alternative to drupal_realpath()? I use drupal_realpath() to do includes for some code samples I have:

 require_once(drupal_realpath('public://php_includes/functions.php'));

This gives the real path C:\www\sites\mysite\files\php_includes\functions.php.
What is the command to get the HTTP path http://mysite.com/sites/files/php_includes/functions.php?

The api documentation says "RealPath is deprecated"... if it's deprecated, what is supposed to replace it to get the same path (either C:\... or http://...)?

To get the HTTP path of a file, you need to use file_create_url($uri).

file_create_url('public://php_includes/functions.php');

This will output http://mysite.com/sites/files/php_includes/functions.php.

Regarding the fact that drupal_realpath() is deprecated, I think it's to warn developers to avoid relying on file system path and instead use wrappers.


InvalidArgumentException: Invalid translation language (fr) specified I'm currently trying to translate my twig template to the current language and at this moment I'm getting the following error

  InvalidArgumentException: Invalid translation language (fr) specified.
  in Drupal\Core\Entity\ContentEntityBase->getTranslation() (line 872 of
  /Applications/XAMPP/xamppfiles/htdocs/iom/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Here is a snippet of code that I'm currently working on

// Page-level pre-processing
function iom_preprocess_page(&$variables) {

    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

{% if (language.getId() == 'fr')  %}

{{ tab_label.entity.field_tab_title.entity.translation('fr').label }}

{% else %}

{{ tab_label.entity.field_tab_title.entity.label }}

{% endif %}

Somehow this part right here is what seems to be causing the error even though the language is currently correct

{{ tab_label.entity.field_tab_title.entity.translation('fr').label }}

Should check on lang_code the variable you already passed from preprocess, not language.getId() try something like that:

{% if lang_code == 'fr' and tab_label.entity.hastranslation(lang_code) %}

{{ tab_label.entity.translation(lang_code).field_tab_title.entity.label }}

{% else %}

{{ tab_label.entity.field_tab_title.entity.label }}

{% endif %}


Remove pager from frontpage On the frontpage of my drupal site I have set up multiple blocks that display content from different views however, in the Content block region my news block is showing a pager that I am unable to remove.

In the news block I have configured the Pager settings to display a specified number of items
and to use a more link that says view all. But the settings will not work in the content block region.

I have also tried to configure the frontpage with similar Pager settings and still no luck.

System Information:

Theme: Bartik 7.12

I figured out what I was doing wrong. It had to do with the defaults of the page view path.

In the Front Page View I changed the page settings path to /home and went into
Configuration >> Site information and scrolled down to the Front Page settings.

I set the default front page url to home and the pager was removed as per my configuration of the frontpage Page pager settings.