Trouble adding JavaScript inside a custom module

It looks like it's due to the second implementation of drupal_get_path().

You're passing through mymodule2 as the argument, where it should just be mymodule.

e.g.

function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule.js');
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule2.js');
}

On another note, if the JavaScript needs to be added on every page (as I'm guessing it does with the implementation of hook_init) then you might be better off adding your scripts in using scripts[] in the module's .info file

  scripts (Optional)

  You can now add Javascript in the module's .info
  file if it should be added on every page. This allows Javascript to be
  aggregated in an optimal way, and is the preferred method of adding
  Javascript that most visitors will need on a typical site visit

Source:  Writing module .info files

References:

drupal_get_path(); API Docs

Managing JavaScript in Drupal 7

Writing module .info files


Commerce order mail is empty for anonymous users

You have anonymous orders so your code doing the loading of the user account obviously wont work as they dont have a user account:

 // load user
$user = user_load($order->uid);
//$user->name;
$to = $user->mail;

The above won't work for anonymous users as they don't have an account so the uid is always 0. I think the $order object has $order->mail to get the actual email address used on the order regardless if it was a full user or anonymous


How can I NOT show the Request new password tab within the /user (login) page for one particular user

If you just wish to hide the tab, you can do that by using the Tab Tamer module. However, the user would still be able to access the form through the URL http://<yoursite>/user/password.

If you wish to disable (along with hiding) the password tab, you can implement the hook_menu_alter().

function MODULE_menu_alter(&$items) {
  //condition to check the user
  global $user;
  if($user->id == '<USER_ID_OF_THE_USER>') { //can use $user->name as well
    $items['user/password']['access callback'] = FALSE;
  }
}


Adding variable to user profile page in drupal 6

Use the hook_menu in your custom module and use MENU_LOCAL_TASK as the type, and the path in your custom module needs to start with user/

function HOOK_menu() {
      $items['user/%user/yourpage'] = array(
        'title' => t('My Tab'),
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'yourmodule_page', //your module page should be a function
        //'page arguments'
      );
      return $items;
    }

function yourmodule_page()
{
   $uid = arg(1);
   $user = user_load($uid);
   //use user to get particular content belonging to them
   //return content
}


Mandatory Group / Autosubscribe in Drupal 7

You can use rules to do this (As OG7 uses rules for everything else).

Create new Rule
Add New Action
React on event: After saving new content
Add condition
Data Selector node:author
Choose whatever role is admin
Add Action
Send email to all users of role
Select whatever roles
Fill in your message with applicable tokens

You can also check out the notifications and Messaging framework or the new Newsletter module for D7. These are better for allowing users to control which notifications they receive and can subscribe and unsubscribe themselves.


Drupal Commerce Stock Availability or Out of Stock

On Drupal 7.61 & Commerce Stock 7.x-2.3 I've solved it with hook_commerce_product_reference_default_delta_alter:

/**
 * Implements hook_commerce_product_reference_default_delta_alter().
*/
function test_module_commerce_product_reference_default_delta_alter(&$delta, $products) {

foreach ($products as $product) {
  if ($product->commerce_stock['und'][0]['value'] > 0){
    $product->commerce_stock['und'][0]['value'] = "On stock";
  }else {
    $product->commerce_stock['und'][0]['value'] = "Out of stock";
  }
 }
}


drupal 7 lack of understandig location of bartik's color.css

The Bartik theme has support for the Color module, which is a module that allows themes to change the color used in their images, or in their CSS style files basing on a schema defined in the theme settings page.

When the selected color set is not the default one, color_scheme_form_submit() generates the files that will be used for the theme. The files you have seen inside the sites/default/files/color directory are the ones generated from the Color module, and that will be used for the theme. The files in the theme directory are the ones used when the color set is the default one.

As side note, if you are editing the files used by a theme that supports the Color module, you need to disable, and then re-enable it, or the files used for the theme could still be the old ones.


How to find which module is causing PHP warning

Best way is probably to use a debugguer like xdebug and watch the callstack in your IDE before your warning.

If you cannot, use debug_print_backtrace() or debug_backtrace(), locate your warning and you will see all the calls before it happens.

Here is an exemple you have to adapt (or not) : set_error_handler()


How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?

Assuming your question is about D7, there are basically 2 ways (options) to answer your question, as further detailed below.
Option 1: Use Rules and Views Bulk Operations
You could create a view (using the Views module) of those users that you want to send an eMail to.
After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, using a rule that looks like so:

Rules Event: After saving a new comment.
Rules Actions:

Load the VBO list of the users in your View.
Add a loop to perform a Rules Action "Send an eMail", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
Option 2: Use Rules and Views Rules
a) About this module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

b) Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

c) Create a rule using the view of display type 'Rules'
Create a rule that looks like so:

Rules Event: After saving a new comment.
Rules Actions:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.


How to edit how Commerce outputs the Billing and Shipping information in the checkout review table?

At time of writing, this isn't a viable solution, but I'm posting it because it might become one, one day.

Commerce Responsive UI module

There's a massive long 5-year-old issue matching my problems theming Commerce checkout in the Commerce issues queue. The "fix" was the creation of a module, Commerce Responsive UI, that aims to modernise the markup of the checkout (and other) pages and make them themable. It sounds like exactly what I'm looking for.

Problem is, there's no stable release, no release at all since November 2015, and it appears to have some serious unresolved issues, like breaking normal cart/checkout page paths. This might become a good answer to the question, but right now it's an unfinished work in progress.


Showing 2nd Depth term name and image along with it's associated node's title

When you say 'Popular', do you mean the view must showing only the most popular/used term?  a bit more info please.

Ok, then I think I can help you get there, if I've understood everything correctly.

I've created a taxonomy that looks like this:
Vocab: Electronics
Terms:

Notebooks

Asus
Apple

Television

Panasonic
Sony

Then set up a view of Taxonomy Terms, using Filter Criteria to limit to your Electronics vocabulary (all straight forward so far).  What will help you is adding Advanced > Relationship > Taxonomy term: Content with term .  This will allow you to output the node fields that reference each term, per result.

Then enable Advanced > other > aggregation. This will allow you to group your results together by term.

To get closer to your required output, you can GROUP the fields using the FORMAT > settings.  Let me know if this takes you in the right direction, or even gets you close.  Or if you've tried this all before and I can remove the answer.

NOTE: the node will reference a specific TERM.  You can get access to that term's parent(s) tree etc, but bare in mind the relationships begin with the node->referenced TERM.


integration Webform and registration module

There are two contributed modules that may provide what is needed (quotes included are from their project pages):

Webform register:

  ... adds a Webform component that collects user registration details and creates a new account. This is useful when you only want authenticated users to submit webforms, but you do not want to create an extra hurdle for people before they fill out your webform.

  Webform Register can help you keep the flexibility of Webform, while reducing duplicate entry for your visitors. Because the user registration page can be extended through Drupal's built-in user profile fields or with the help of Content Profile, the Webform Registration can help you collect user-specific, oft-repeated information such as Name, Address and Organization information and store it in a profile entry for each visitor. Meanwhile, information that's only pertinent to the individual webform, such as survey data or preferences for a single event, are collected by standard Webform behavior.

Webform Registration:

  ... born from the need to allow visitors that came to the site to fill out a sweepstakes from which needed to not only submit values to Eloqua, using the eloqua module, but also create a new user.

  At the time the Webform register module did not provide enough flexibility for what we needed to do. Which was have many different field names (used for eloqua mapping) and still keep track of which ones held the values for email, username and password.

  How is this module different from Webform register:

  Maximum webform integration and flexibility
  You can add and fully customize every field that will be used for registration.
  If you are in a hurry, just add en email field and this module will handle the rest via a very user friendly and intuitive interface.
  Only the email field (webform component) is required, all the other components can be either generated by this module or omitted depending on your needs.
  Optionally you can specify all the labels and descriptions for all five fields (components): email, username, password, password confirmation and email confirmation


Multilingual "Posted on: ... - By: ..." labels

The Nexus 7.x-1.3 theme didn't considered internationalization for some of its  templates:
To enable it to translate "Posted on: ... - By: ...", edit the node.tpl.php on line 90.

Posted on: <?php print $date; ?>

By: <?php print $name; ?>

you will need to use the t() function to change the lines to:

<?php print t('Posted on:'); ?> <?php print $date; ?>

<?php print t('By:'); ?> <?php print $name; ?>

I'm not sure about which calendar you mean, in case that you are using the one bundled with Date module (Date popup), I believe those buttons can be translated using the Translate interface (admin/config/regional/translate/translate).


How to alter the search api views exposed form field value?

I have found an answer. I am sharing it here so that it can help someone.

Instead of form_alter hook, we can use hook_views_pre_view.

Here is the code

/**
 * Implements hook_views_pre_view().
 */
function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view_name') {
    $address = 'some address';
    $latlong = somefunction($address);
    $view->get_exposed_input();
    $view->exposed_input['latlon'] = $latlon;
    $view->execute().
  }
}


Display different time from one field value

Well you are better off writing a custom module or using a function that can swap out a timezone variable instead of manually calculating by adding 8 hours...
But if that's what you want here is one way of achieving this..

Create a node template for that content type or specific node (whichever suits your scenario).

In the template file you can use:

 <?php
    // Your date field. note the appended 'field_' at the start of the machine name.
    $date = new DateTime($content['field_YOUR_FIELD_MACHINE_NAME']['#items'][0]['value']);

    // Boston date field
    $boston_date = $date;
    $boston_date ->modify("+8 hours");
    $boston_date ->format("d.m.Y H:i");

    //Outputs your date field with 8 hours added to it.
    print 'Eventname - starttime for Boston: ' . $boston_date;
 ?>


How to implement a Rules Condition like [account:last-login] = never?

It looks that what you're trying to do implement (= do a data comparison with "never") is not an obvious thing to do. Therefor, you may want to go for a plan-b that, for sure, will implement what you're trying to achieve, i.e. "... redirect on a special page for first time after login ..." (as in your question). Read on for more details.

Create a custom rule that looks like so (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_redirect_new_users_to_special_page" : {
    "LABEL" : "Redirect new users to special page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
      { "redirect" : { "url" : "welcome\/newuser" } }
    ]
  }
}

Some details about this rule:

Rules Event: User has logged in.
Rules Condition: User does NOT (!!!) have a role with role id = "4".
Rules Action:

Grant User the role with role id = "4".
Perform a page redirect to relative path welcome/newuser.

So this rule checks if a user does not yet have some (designated) role with role id = "4" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case then the user is granted that role, followed by a page redirect to relative path welcome/newuser (adapt to whatever path that fits your case). Obviously, next time a user performs a login again, the Rules Condition will no longer be TRUE, and no more redirect will be performed.

Pretty similar to "... redirect on a special page for first time after login ..." (as in your question), no?

Variation

What is explained before in this answer, does require some extra (dedicate) role. If you rather want to keep the number of roles in your site to a minimum, you could also use the Flag module (as an alternative for such extra role). Some more details about this variation:

Define a "global" flag to flag users
Replace the Rules Condition (to check for the dedicated role), by another one like "Check if the user is NOT flagged" (by the global flag).
Replace the Rules Action (to grant the dedicated role), by another one like "Flag this user flagged" (by the global flag).

Voilà ... use the solution you prefer, either one will do ...


What conditions may cause "The content on this page has either been modified by another user..."?

Another cause might me the fact that you save a form, then hit the back button and try to save it again


How can I prevent a form from being displayed in the privatemsg module?

The following code does it for me:

function MYMODULE_form_pm_block_user_list_alter(&$form, &$form_state, $form_id) {
  unset($form['new']);
}

This should help if you didn't know about it.

hook_form_FORM_ID_alter();

Also there's the more generic hook_form_alter().


Does hook_node_access_records() and hook_node_grants() change permissions for existing nodes?

You can implement hook_enable() and call node_access_needs_rebuild(TRUE), see user_relationship_node_access_enable() for an example.

That doesn't actually do much on its own, but Drupal will then automatically print a message to administrators and inform them that the permissions need to be rebuild and also includes a link to the place where this can be done.


Is it possible with one of the template suggestion hooks to also specify a new template location?

You can specify a new template location in hook_theme():

  path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the
  default path, include it here. This path should be relative to the
  Drupal root directory.

  Like let's say inside my custom module's /templates folder?

This means when using hook_theme() instead of hook__theme_suggestions_* the module's template folder is already default and you don't need to specify path.

So you can use this answer  hook_theme_suggestions_page() provide default template file inside module folder.


How to pass the query string used to access a page in a link in a views content pane?

If I understand the question, you need to tell views to pass the url path to the content pane (views > pane settings > use panel path).


How do I programmatically add a field to a Transaction in Drupal Commerce?

The payment transaction entity type isn't field-able (see commerce_payment_entity_info()).

But you can change that with hook_entity_info_alter():

function MYMODULE_entity_info_alter(&$info) {
  $info['commerce_payment_transaction']['fieldable'] = TRUE;
}


Images break with wrong href; clearing caches fixes!

More than likely, your server is responding to multiple domain names, either by being the default or matching/wildcards for ServerName and ServerAlias (using Apache terminology here; nginx and IIS have similar concepts).

So, the problem is that you get a request to www.example.com, and Drupal serves that page up and uses that URL as the base.  It will also respond to www.subdomain.example.com and use that as the URL base.  The problem you see is that the subdomain request is the one being cached, and the hostname isn't part of the cache ID.

The general solution to this is to set up a canonical redirect in either the Apache config or the .htaccess file for your site (I prefer in server config).  The rule would look something like this

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
  RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
</IfModule>

When you do that, Apache will redirect everything to https://www.example.com.  Over time, Google will fix its indexes because of the 301 redirect, or you can try to submit manual delists.


Thank you very much!
I really didn't need routing!

Well, finally I found the solution to my problem - I created the module with 2 files only - mymodule.info.yml and mymodule.module.
In .module file I only added these lines of code and everything worked! (Almost)

function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
if ($entity_form['#entity_type'] == 'node' && $entity_form['#bundle'] == 'my_custom_content_type_machine_name') {
  unset($entity_form['field_I_need_to_hide']);
}}


how can i attach a taxonomy to the users profile?

Users in Drupal 7 are proper entities and fieldable.

Goto Administration » Configuration » People » Account settings » Manage Fields (admin/config/people/accounts/fields)

Add a new Field.  Choose a label, and choose Term Reference as the field type.  Configure as needed.  This should identical for how you do it for a Content Type (ie, a node).

The click on the Manage Fields tab.  Set up the display for how you need it.

Edit you users, and add in some field data.  It will be in the full loaded $user object, and you can use it in Views over Users.


A solution would be to install the Display Suite module.

Once both Display Suite and Display Suite UI modules are enabled you must go to the presentation, choose a layout at the bottom and save, then you will have a lot of fields that weren't available before. One of those fields is the node title.


The Spambot module is a great solution for protecting the registration form:

  Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.

I'd definitely recommend it


How do you position a custom search box in the main menu?

Menu Inject Block module was built exactly for the same purpose.

  This module allows you to inject blocks as menu items. It facilitates easier use of JavaScript based dropdowns and panel like navigation. Most users employ this module to create dropdown panels using other modules to handle the dropdowns and this module to inject the blocks as needed.

To use this module:

Enable the module
Create or Edit your menu item (/admin/build/menu)
Enter in  for the Path
Give your menu item a Title
Select a Block from the "BLOCK TO INJECT:" drop down (in your case the search block).
Save your menu item

You don't need to create a separate search block in case you use the module. You can place the default search block that Drupal provides, into step 5 mentioned above.


That's the message you get for the standard front page (located at /node), so it looks like your attempt to update which page is the front page hasn't taken for some reason.

In case you've done it another way, the usual way to set this front page is to go to admin/config/system/site-information and set the "Default Front Page" to the path of the new node that you've created.

You'll also need to clear Drupal's caches once you've added the new template file in case you haven't done that already.


How to make link unchangeable when using Pathauto?

This is an option in the pathauto settings (Configuration » Search and metadata » URL aliases » Settings) under Update action. Set it to Do nothing. Leave the old alias intact. and pathauto will not update the path alias after its initial creation.


Execute a custom shell script before the aegir verify

You could implement a drush_hook_pre_COMMAND() hook in drush to run any code you'd like.

See the docs page for more details: https://docs.aegirproject.org/extend/altering-behaviours/#running-extra-code-after-a-task


How to get Drupal 7 installed in a sub-folder / sub-directory properly?

When I do this, provided I have a clean install, I do not modify anything. Take the domain http://diw.ifi.uio.no/, where Drupal is installed in both /www/, and /www/gruppe01/, etc. (I just create the number of subdomains I need for various experiments). My DocumentRoot is set to be /www/. I just direct my browser to http://diw.ifi.uio.no/ for the main site, and  http://diw.ifi.uio.no/gruppe01/ for the first subfolder site, etc. and it works - just like that.

Have you tried starting with a clean install and just install Drupal in the subfolder using the standard install procedure without changing .htaccess? (While not always necessary, I recommend that you have $base_url set correctly in the site's  settings.php.)

In my experience, Drupal works fine out of the box when installed in a subdirectory of a vhost. The fact that there is another Drupal in the DocumentRoot does not make this any different, as long as each Drupal site has its own .htaccess, it will not try to read the .htaccess in any superior directory.

Examples:

http://diw.ifi.uio.no/
http://diw.ifi.uio.no/gruppe01/


Why do I get the "could not find the controller" error?

A 301 is a redirect, so it sounds like you have the Global Redirect module enabled. See this issue for details: https://www.drupal.org/node/1927336

The patch allows you to declare paths that should be ignored by the Global Redirect module so it doesn't hijack Service calls to your Drupal site. You'll input something like this into the configuration text area once the patch has been applied:

drupalgap/*


How to Determine a View Row's Content Type

Create a new display mode and use this display mode on the view. then each of this display mode can be altered in admin or custom template can be made.


All instances of block are not getting removed

As mentioned in the other question, what you need to do is query for the blocks that no longer exist and delete them.

BlockContent::delete()/getInstances() is an example for that. You can do a similar query, either by using entity_load_by_properties() for the plugin ID that those blocks would have. Or you can run an entity query, which has more options.

You don't have an entity, so in your submit, you need to build a list of all unchecked options and then query for those. The advantage of doing an entity query is that you can do an IN condition, so you probably want to use that.

A more complicated example, that looks at settings and either updates or deletes the affected blocks can be found in simplenews.module's Newsletter::postDelete():

if (\Drupal::moduleHandler()->moduleExists('block')) {
  // Make sure there are no active blocks for these newsletters.
  $ids = \Drupal::entityQuery('block')
    ->condition('plugin', 'simplenews_subscription_block')
    ->condition('settings.newsletters.*', array_keys($entities), 'IN')
    ->execute();
  if ($ids) {
    $blocks = Block::loadMultiple($ids);
    foreach ($blocks as $block) {
      $settings = $block->get('settings');
      foreach ($entities as $newsletter) {
        if (in_array($newsletter->id(), $settings['newsletters'])) {
          unset($settings['newsletters'][array_search($newsletter->id(), $settings['newsletters'])]);
        }
      }
      // If there are no enabled newsletters left, delete the block.
      if (empty($settings['newsletters'])) {
        $block->delete();
      }
      else {
        // otherwise, update the settings and save.
        $block->set('settings', $settings);
        $block->save();
      }
    }
  }
}


How to hide certain taxonomy views from user?

Out of the box Views only has 2 different types of access management:

Via role
Via permission

However, it's an all-or-nothing control; you can't do it on a per contextual argument basis (for a taxonomy in your /taxonomy/term/% view).

What you can do, is create your own Views access plugin (or perhaps one already exists, look through drupal.org for 8.x Views projects). Take a look at the access plugin code docs or this tutorial as primer on how this is done.


Redirect user page to user/edit and user/login

You can do it without hook_menu_alter, achieve it in hook_init, try something like  (don't forget changes in hook_init need clear the cache to getting applied)

function yourmodule_init(){
   if(current_path()=="user"){
   global $user;
     if (user_is_logged_in()) {
      drupal_goto('user/'.$user->uid.'/edit');
    }
   else {
      drupal_goto('user/login');
   }
}
}


Can I access public:// from inside a module?

You're looking for the file_create_url() function:

  Creates a web-accessible URL for a stream to an external or local file.

e.g.

$data['avatar'] = file_create_url($profile->field_picture['und'][0]['uri']);


stark.css doesn't contain any background colour,  so you can set one yourself.  you don't need to remove anything first.


Have a look at my answer to the question about "How to add up all items of a field collection field using Rules?". Your question is, IMO, a minor variation of it. Just replace article-details-item:field-price by line_item_quantity (as in your pseudocode) and it is close to identical.

The custom rule to do the calculation, looks like so:

{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

Enough to get you going and get it to work (or should I say "How good are you in reading/digesting the Rules-export-language)?


Standard way of getting a form inside block

You can get the fully qualified class name by using ClassName::class:

use Drupal\mymodule\Form\Myformclass;

  public function build() {

    $form = $this->formBuilder->getForm(Myformclass::class);
    return $form;
  }

If you want to avoid the full classname in code.


Drupal views support sorting with timestamps by default. You need to install the Date module to add support for date sorting in views. I also recommend that you import the data from your source with the feeds module and use another date field for your date NOT the property "updated" which is a timestamp.

Another solution is to convert the date from your source to timestamp as you import it. The tamper add on module for feeds may help you do this.


Store all images uploaded to website in specific directory

Is there also a way (maybe a script) to delete the file from anywhere
  in the directory when the node that holds the images is deleted?

They get auto deleted when cron runs.


No need to hardcode a query. The voting api module provides some helper function for this.

The function you need is votingapi_select_votes($criteria = array(), $limit = 0)

The $criteria parameter takes a decent amount of options.

Here are the options:

$criteria['vote_id']  (If this is set, all other keys are skipped)
$criteria['entity_id']
$criteria['entity_type']
$criteria['value_type']
$criteria['tag']
$criteria['uid']
$criteria['vote_source']
$criteria['timestamp']   (If this is set, records with timestamps
                          GREATER THAN the set value will be selected.)

In your case you really want to pass in the 'entity_id', 'entity_type' and 'uid' to check if the user has voted in that particular content item before awarding him points.

This is the same way we prevent a user from voting multiple times in the same item with Fivestar.

Hope this helps.


Relation: add button to create node related to current node

The Node Reference URL module works with the References module to accomplish this feature. When you add a node reference field, you can specify Reference From URL widget which will auto fill the field from a value in the URL. You can also specify (in the field settings) to display a link on the referenceable node.

In your case, you would create a node reference field on School News that references Shools. Just select the Reference From URL widget and configure as necessary.

There's an older lullabot video about creating image galleries in Drupal 6 that demonstrates how it works. The Drupal 7 version has the same features and works the same way.


I know I'm late, because this answer has been answered long time ago, but I don't think this is the right way to do it, especially with the java script interval function – it might work but in many cases may cause a problem.

For those who need the same result I suggest to use this java script code which is based on action when the ajaxStop event is triggered.

First you nedd to create a java script file in your module directory, for exapmle: YOUR_MODULE_NAME/js/custom_shs_behaviors.js with the following code:

/**
 * @file
 * Custom behaviors for Simple hierarchical select:
 *   Change the first option text from "- None -" to whatever you want (default: "- Any -").
 *   Create labels for each level.
 */
 (function($) {
  Drupal.behaviors.customShsBehaviors = {
    attach: function (context, settings) {

      // Helper function for an option text replacement.
      // use: optionObj.replaceOptionText(); for default replacement from '- None -' to '- Any -'.
      // or optionObj.replaceOptionText('Foo'); to replace the '- None -' with 'Foo'.
      $.fn.replaceOptionText = function(replacement) {
        var replacement = replacement ? replacement : '- Any -';
        if ($(this).text() == Drupal.t('- None -')) {
          $(this).text(Drupal.t(replacement));
        }
      };

      // Function that helps to get the select element width including its padding and margin.
      $.fn.getSelectWidth = function() {
        var width = Math.round($(this).wrap('').outerWidth(true));
        $(this).unwrap();
        return width;
      }

      // Define labels.
      var labels = ['Label-1', 'Label-2', 'Label-3'];

      // act when the ajaxStop event is triggered (there are no more Ajax requests being processed.)
      // see: @link http://api.jquery.com/Ajax_Events/ @endlink
      $('.shs-wrapper-processed').ajaxStop(function(event, xhr, settings) {

        $("select.shs-select").each(function(level) {

          // fix the SHS bug - new level that is being created has the same ID as the previous one.
          // make sure that each select has an ID and the class corresponding to the level.
          // YOU CAN USE THESE TWO LINES ONLY IF YOU ARE USING SHS WITH THE ABILITY TO ADD NEW LEVELS.
          $(this).attr('id', $(this).attr('id').replace(/(.*)select-(\d+)/, "$1select-" + (level+1)));
          $(this).attr('class', $(this).attr('class').replace(/(.*)level-(\d+)/, "$1level-" + (level+1)));

          // Replace the first option text using the helper function for an option text replacement.
          $("option", this).first().replaceOptionText();

          // Get label width.
          var labelWidth = $(this).getSelectWidth();

          // Create label.
          if ($("label[for='" + $(this).attr('id') + "']").length == 0) {
            $(this).parent().before(
              "" + labels[level] + ""
            );
          }

          // Remove the label if the select element has just been removed by clicking any option on lower level.
          // There might be several Ajax requests bound with this action,
          // so we have to make sure that our "removing process" will be executed at most once.
          // See: @link http://api.jquery.com/one/ @endlink
          $("option:not(:selected)", this).one("click", function() {
            $(".shs-wrapper-processed").parent().find("label").each(function() {
              if ($(this).attr('for').slice(-1) > level+1) {
                $(this).remove();
              }
            });
          });
        });
      });
    }
  };
})(jQuery);

And attach the java script file to your form. You can do it by using the hook_form_alter() in your theme or module file:

/**
 * Implements hook_form_alter.
 */
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

  switch($form['#id']) {
    case 'YOUR-FORM-ID' :
      $form['#attached']['js'][] = drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/custom_shs_behaviors.js';
    break;
  }
}

You're done! With this code you can set the label for each level of your shs and even change the default option text, for example: from - none -  to - any -.


Menu setting not visibile for other roles on Node Form

Go to /admin/people/permissions and make sure the 'administer menu settings' are set for the Editor role.
But I think it is better to install the Menu Admin per Menu module. With this module you make sure the Editor only gets access to certain menu's.

Menu Admin per Menu allows to give roles per menu admin permissions without giving them full admin permission.

For instance, you may let certain users manage the items of the Main or Navigation menus but not those of the Management menu.


Build taxonomy categories with views, only children

Can you set up your Taxonomy view to accept the argument Parent term and pass it the current term? I don't know how complex your view is, but I got it to work in this basic example:

View type: Term
Add arguments: Taxonomy: Parent term
Action to take if argument is not present: Hide view / Page not found (404)
Validator: Taxonomy term
Argument type: Term ID
Add fields: Taxonomy: Term Term

That will display only the current term's children, i.e. those that have the current term as a parent.


How to display an add to cart button for each product displayed in my views grid?

Surely your issue was solved a long time ago, but this could be useful for other people, so in short :

in advanced settings of the view, add a relationship Commerce Product: Referencing Node (Relate a product to the Node referencing it through field_product) with your product type
then add a Contextual filter
(Node referencing products from field_product) Content: Nid

then you're be able to pick up Add to cart form from Add fields menu

Enjoy ;)


Set

'#checked' => !empty($default_value)?1:0,

in your form checkbox field.


Change a multiple value field to use divs instead of a table in node/add?

You can override theme_field_multiple_value_form(), e.g.

function MYTHEME_field_multiple_value_form($vars) {
  // Copy code from theme_field_multiple_value_form() and change as appropriate
}

It's not a short function, and you'll probably be reproducing a bunch of code, but it uses theme_table() directly so it can't be solved with a preprocess function.


How does Drupal Commerce use the commerce_line_items field?

This answer refers to the Drupal 7 version, but I assume it's similar for D8.

The commerce_line_items field is a field of type commerce_line_item_reference (basically a reference field) that is defined and instantiated inside the function commerce_order_configure_order_type, in the file commerce_order.module.

This field of unlimited cardinality stores references to each of the line items in an order. Think of the line items as basically each of the "lines" in an order or invoice that reference a specific product, its quantity, price, and total price etc.

The values of the commerce_line_items field are initially set in the commerce_cart.module file, inside the commerce_cart_product_add function (basically when you add a product to the cart), in line 1377.

All of this information can be glanced by studying these files.

[EDIT]

I'm not sure I'm understanding where you are going with this question, but given your recent edition, yes, you can access the values of the line items by using, for example, an entity_metadata_wrapper, which will allow you to navigate the relationship to each line item and all its fields and properties. See this tutorial for entity_metadata_wrapper


This post actually gives insight on how multilanguage fields work using internationalization:
http://dominiquedecooman.com/blog/drupal-7-tip-get-field-values-entity-objects-nodes-users-taxonomy

As well as Gabor's Very authoritative one: http://hojtsy.hu/multilingual-drupal7


Body field of some nodes not displayed in teaser view

This problem might be related to the WYSIWYG editor you're using. Some of them output a lot of redundant code, so you don't get anything or a bunch of white space before content on teasers. Try using the 'Edit summary feature' that comes with Drupal corer to fine-tune teasers (or you could always have a new teaser text field). Most of the WYSIWYG editors come with a Teaser button, so you should use that.


Why do Drupal Form Builder properties have hash marks (#) in the key?

If you don't add a hashmark you're not setting that property, but are instead defining another level of a render array element. Consider this example:

$form['your_name'] = array(
  '#type' => 'textfield',
  '#title' => 'Your Name',
  'title' => array( // I am an entirely new element, whose key is "title".
    '#type' => 'textfield',
    '#title' => 'Your Title',
    '#description' => 'Example: Sir, Mr, Bossman, Chieftan',
  ),
);

This example is silly, but it should describe why a hashmark is used to set a property. If your question is really "why use a hashmark instead of an exclamation point, an ampersand, or some other random character?", well, I don't know. I've seen the hash symbol used to define properties in other languages and APIs.


Replacing field result with hook_views_pre_execute when replacing SQL query

From your description, you are trying to display the aliased path of the current page using a view.If you are trying to encourage users to deep-link to your site, a PHP code snippet might be a better approach. (Drupal often encourages complex answers to simple requirements.)

Using aliased links means that the links may be broken if the alias changes (as with a change in the page title) unless the old aliases are retained. In that case, multiple aliases will exist for each page. Deep links should use the un-aliased url.


I'm assuming you are using the "Taxonomy term" view that comes with drupal.

Edit that view and:

Edit the contextual filter for "Content: Has taxonomy term ID (with depth)"

Set the depth option as high as you need to cover the number of levels in your vocabulary.


You cannot alter a form from a theme's template.php file. You need to create a custom module for that. In this module, you can alter the login form in an implementation of the hook_form_alter() or hook_form_FORM_ID_alter() hooks.

Without some JavaScript, you will not be able to submit the form to a separated URL. What you can do, in your module, is to provide an dedicated validation or submit handler for you button. In this handler, you can redirect to your external URL using drupal_goto().

Something like:

MODULE_form_user_login_alter(&$form, &$form_state) {
  $form['foo'] = array(
    '#type' => 'button',
    '#value' => t('Foo'),
    '#submit' => array('MODULE_user_login_foo_submit'),
    '#limit_validation_errors' => array(),
  );
}

MODULE_user_login_foo_submit($form, &$form_state) {
  drupal_goto('/path/to/request.php', array('external' => TRUE));
}


How to set kint() to be closed by default?

I know this is an old question, but I just figured this out and this question comes up first on google.

The option is already there. What you need to do is click next to the plus sign (the text next to it) not the actual plus sign itself. Clicking the plus sign will expand everything, clicking the title, path or array key will just expand the immediate node below it.

I went through almost a whole project thinking Kint() unusable when it's really just a confusing UI choice.


This is not part of Drupal core. There's a module which provides this capability for D7,  Taxonomy Term Author Info but it's not been officially ported to D8 although there is an unofficial port at https://github.com/worthingtonlibraries/term_authoring_info


For each role you can grant access control with permissions, so each user with specific role can manage any content or users you want to.

Managing access control with permissions and user roles
User: access and management settings


Add a Radio-button with other option in comment type

I think you need to do this in a hook_form_alter.

I have written some example code that you can use. The code is probably not 100% correct, but it's intended to help you, to get an idea of how to solve the problem.

function MY_MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface  $form_state, $form_id) {
  $form['radios_field']['#ajax'] = [
    'callback' => 'MY_MODULE_radios_field_callback',
    'event' => 'change',
    'wrapper' => 'radio-field-wrapper',
  ];

  if ($form_state->getValue('radiois_field') == 'other') {
    // Field to show when options is "Other".
    $form['textfield'] = [
      '#type' => 'textfield',
      '#attributes' => [
        'id' => 'radio-field-wrapper',
      ],
    ];
  }
}

function MY_MODULE_radios_field_callback(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setRebuild();
  return $form['radios_field'];
}


Display date field labels within selectors

Ok I've just quickly whipped up a sandbox module to modify date options array. And here's the code, hope this helps:

/**
 * Implementation of hook_form_alter()
 * @param array $form
 * @param array $form_state
 * @param string $form_id
 */
function sandbox_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'article_node_form') {
    // Only call after builder if we're using date_combo type which is 3 select fields
    if($form['field_date'][$form['field_date']['#language']][0]['#type'] == 'date_combo') {
      // Add our after build function
      $form['field_date'][$form['field_date']['#language']]['#after_build'][] = 'sandbox_field_date_after_build';
    }
  }
}

/**
 * After build callback
 * @param array $element
 * @param array $form_state
 * @return array
 */
function sandbox_field_date_after_build($element, &$form_state) {
  // Loop through each delta if more than 1 value
  foreach(element_children($element) as $delta) {
    // Loop through each granularity e.g. month, day, year, hour, minute, second
    foreach(element_children($element[$delta]['value']) as $key) {
      // #options not set means this type of granularity isn't set, so we skip
      if(isset($element[$delta]['value'][$key]['#options'])) {
        // If there's an empty value, change the option label to be '- [#title] -'
        if(isset($element[$delta]['value'][$key]['#options'][''])) {
          $element[$delta]['value'][$key]['#options'][''] = '- ' . $element[$delta]['value'][$key]['#title'] . ' -';
        }
        // Otherwise insert an empty value at beginning with label '- [#title] -'
        else {
          array_unshift($element[$delta]['value'][$key]['#options'], array('' => '- '. $element[$delta]['value'][$key]['#title'] . ' -'));
        }
        // Make the title invisible
        $element[$delta]['value'][$key]['#title_display'] = 'invisible';
      }
    }
  }

  return $element;
}

Which produces this result provided you have set "No default value" in the field instance setting:

Or you can always do it in the Advanced Settings of any date field.


Changing value of a field before rendering in Drupal 7

I suppose you're not actually trying to change the value of a field – but instead change one of its attributes? It would probably be useful to see how you're trying to rewrite the classes inside those theme functions so far. Basically that should already be the right location to do this.

I recently just had a very similar problem, wanting to rewrite classes of a node. I know it's not exactly what you're asking – but the approach should be very similar. Inside your preprocess funtion first you should extract the already existing classes for later use:

$variables['classes_array'][] = drupal_html_class('node-' . $node->type);

Then you could add classes to the classes_array according to your conditions:

if ($variables['promote']) {
    $variables['classes_array'][] = 'node-promoted';
}

Find full example code and further details on this page or also over here.


IP-numbers not found in database table ip2country

The comment from AyeshK led me to the right answer. I found this in the php manual:

  As pointed out by others, this function's return value is not
  consistent on 32 and 64-bit platforms.

  Your best bet for consistent behavior across 32/64-bit platforms (and
  Windows) is the lowest common denominator: force the return value of
  ip2long() into a signed 32-bit integer, e.g.:

var_dump(unpack('l', pack('l', ip2long('255.255.255.0'))));

And so I changed this row $ipl = ip2long($ip_address); into this $ipl = unpack('l', pack('l', ip2long($ip_address))); and now it works!

But if there is a better solution, please let me know.


Share fields between commerce variation types?

Assuming you are asking about Drupal 7, the answer is yes. You can share base field types across product bundles. Each bundle will have it's own instance of the field, but the data will be stored in the same underlying storage system.

You can add them by choosing from the list of fields under "Add existing field" on the field editing screen:


How to automatically assign child taxonomy terms?

The best way to achieve this job is using JQUERY,load all terms in the page  ,hide all of  children  terms and when the parent term checked show the children terms of it( also when unchecked hide all children of it).


Can I write [the external data] to the database directly without creating any inconsistenties?

Hypothetically, yes. On a practical level, I'd avoid this approach like the plague. For example, in your next question, you ask…

What tables do I have to write this to? only the node table and the field_data tables? Or do I also have to add it to field_revision tables etc? Am I forgetting any others?

Thanks for the segue. Why not use Drupal's Feeds module to consume your data and let Drupal and Feeds manage the consumption process? This will ensure all the data modeling, processing, security and coding best practices inherited by the larger community. Why would you bypass all the work that's gone into this development?

Is there a module that's doing this? I tried the Feeds & the Migrate modules, but I can't seem to find anything to set up XML or SQL Data import on those. Either of the 2 is fine, whether it goes directly from the XML, or if I have to import it from SQL, cause then I can just add them to a temp table first.

As ar7Max indicates, you can use the Feeds and Feeds XPath Parser. It's stable, mature and has a large user base. We rely on this combination heavily (50+ sites, 100's of specific feeds imports) mostly without a hitch. The hitch tends to be poorly formed XML output which can break an import — again, this is rare and addressable at the source OR using Feeds Tamper. where you can rewrite the XML data as needed. If you wish, ask your XPath Parser specific questions here — once you understand it, it's trivial to manage.


Under /admin/structure/types/manage you can select the content type, and adjust the submission form settings to require preview before submitting.


Load existing form and use hook_form_alter to create a custom submit handler?

You can use the 'Available as block ' for webform settings. This option can find at 'form settings'->Advanced settings of your webform. Once it enabled you can render this webform block, instead of your static form as follows.

You can define custom submit handler for the webform, ex: $
form['#submit'][] = 'my_custom_submit_handler';  in form alter,
in that function you can write the necessary code to save and redirect etc;

hope this may help you.


Why does Panels output  for some panes and  for others?

To the best of my knowledge, Panels contains no instances of <section>. This comes entirely from your theme.

Specifically, I believe it's from at_core/templates/panels-pane.tpl.php which contains the following:

 * Adaptivetheme variables:
 * - $is_mobile: Bool, requires the Browscap module to return TRUE for mobile
 *   devices. Use to test for a mobile context.
 * - $tag: top level wrapper element, section or div.

followed by

 <<?php print $tag . $attributes . $id; ?>>

The relevant logic appears to be

/**
 * Preprocess variables for panels_pane.tpl.php
 */
function adaptivetheme_preprocess_panels_pane(&$vars) {
  // Top level wrapper
  $vars['tag'] = $vars['title'] ? 'section' : 'div';


Change page.tpl template inside a hook_menu callback

You cannot directly change the page template from a page callback. You can either bypass the full page rendering by printing your page content from your page callback. Or you can use a global variable to trigger addition of template suggestion in hook_preprocess_HOOK implementation.

function _no_template_page_callback() {
  // ... processing ...
  // Print the result, and bypass the page template (so no blocks, no CSS, no JavaScript, etc.).
  print $html;
}

function _template_suggestions_callback() {
  global $MODULE_page_template_suggestions;
  // ... processing ...
  // Set flag to trigger usage of our custom page template.
  $MODULE_suggest_page_template = $suggestions;
  return $html;
}

function MODULE_preprocess_page(&$variables) {
  global $MODULE_page_template_suggestions;
  if (!empty($MODULE_page_template_suggestions)) {
    // Use template suggestions set from _template_suggestions_callback the module.
    foreach ($MODULE_page_template_suggestions as $suggestion) {
      $variables['template_files'][] = $suggestion;
    }
  }
}


There is no good answer for this, as it will vary host-to-host.

Sometimes, shared hosts use management tools that map domains to accounts to directories.  This makes it hard(er) to do the Apache ServerAlias settings.  I have worked with shared hosts that have let this happen.

Sometimes, hosts will map domains to user accounts and run Apache in FastCGI mode, which may complicate things.

You need to contact your host to see what is possible.


You need to use Drupal-to-Drupal data migration module. Project page says

"With migrate_d2d 2.1, we are introducing a wizard-based UI for defining your Drupal-to-Drupal migrations. Enabling the migrate_d2d_ui module will add an "Import from Drupal" subtab to the Migrate dashboard - visit that tab, enter the credentials for your source Drupal database (versions 5, 6, or 7), and follow the steps to define how your legacy content maps to the destination Drupal 7 site."


Views callback work only once with advanced form block

you just need to put the number of tid directly here :

ajax_command_replace('#target_div_id_of_view_to_update .view','1'),


How to prevent a rule to be triggered inside a rule?

This is a workaround solution.
You could add a boolean field to your journal entry content type. Side note, you could use the Field Permission module to hide the boolean field from the add/edit form.
Alternatively, if you're not using the sticky system, you could use that instead.
So now all you gotta do is add a condition to your Unflag Rule.

Boolean is false/unchecked OR content is unsticky.

Now in your Component Action add:

Set a data value and make your boolean True/checked OR Make content sticky
Unflag node
Set a data value and make your boolean false/unchecked OR Make content unsticky

Voilà!!! your component will not trigger your unflag rule.


You have to prepare the string yourself, manually. You can use the pathauto_cleanstring() helper function that will remove all characters you wouldn't want in the URL (e.g. spaces).

Here's an example:

// The function we need is in the pathauto.inc file.
module_load_include('inc', 'pathauto');
$clean_title = pathauto_cleanstring($string_you_want_to_clear);

Hope this is what you were asking about.


"Find Content" missing even though user has permission "Access the content overview page"

Problem: User's "Add Content" menu item is available, but "Find Content" is not.

Solution: Manually re-add the missing menu link.

How to add an item to the admin short menu...

Click Edit Shortcuts

Add a new shortcut

Enter a Title, A URL and then Save

You will now have the 'Find Content' shortcut in your admin shortcut bar as needed.

Side note:

If viewing admin/content you can also add the shortcut by simply clicking the + as noted in the graphic below:


D7 - Can't set selected value of a webform select element

You can set value by using #value

$vars['form']['submitted']['country']['#value'] = 'BARBADOS';

But make sure that the select option key should be same

Example:

<option value="BARBADOS">BARBADOS</option>
$vars['form']['submitted']['country']['#value'] = 'BARBADOS'; //will work

<option value="barbados">BARBADOS</option>
$vars['form']['submitted']['country']['#value'] = 'BARBADOS'; //will not work
$vars['form']['submitted']['country']['#value'] = 'barbados'; //will work


Views proximity search by postal code show all when empty

In the settings for the exposed search field, you should be able to change the behaviour:
On Empty input, Show None.  Show All is set by default


Drupal users getting blocked automatically

Do you happen to have the Inactive User module installed? This module can be used to block users who are inactive for some time. Otherwise, are you sure that the users are not trying to log in with the wrong password (5 times), which would also block them. It could be possible that someone else is trying to log in with these user accounts and is getting them blocked (I suppose it would be up to you to decide how likely this is based on whether or not your website is fairly high or low profile).


How can I disply the regex match in a view?

You can create your own module that adds a field formatter for the text_with_summary field type. At the bare minimum you will need to implement the following hooks:

hook_field_formatter_info() for defining the formatter
hook_field_formatter_view() for outputting the results
hook_field_formatter_settings_form() for adding a form field to input the pattern into

Here is an example that will do what you are asking for, but still requires a lot more work before you should use it in production. For example, it doesn't validate the pattern, and does not have an input field to enter the regex pattern in the Manage Display page for content types, even though it can be selected as a formatter.

/**
 * Implements hook_field_formatter_info().
 */
function my_module_field_formatter_info() {
  return array(
    'my_module_regex_formatter' => array(
      'label' => t('Regex matches'),
      'field types' => array('text', 'text_long', 'text_with_summary'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function my_module_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'my_module_regex_formatter') {
    $pattern = FALSE;
    if (isset($settings['my_module_regex_pattern'])) {
      $pattern = $settings['my_module_regex_pattern'];
    }
    if ($pattern) {
      foreach ($items as $delta => $item) {
        $matches = _my_module_get_regex_matches($pattern, $item['value']);
        $element[$delta] = array('#markup' => $matches);
      }
    }
  }

  return $element;
}

/**
 * Returns regex pattern matches.
 */
function _my_module_get_regex_matches($pattern, $subject) {
  $result = '';
  $regex_result = preg_match_all($pattern, $subject, $matches);
  if ($regex_result) {
    $result = '
';
    foreach ($matches[0] as $match) {
      $result .= '
' . check_plain($match) . '
';
    }
    $result .= '
';
  }
  return $result;
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function my_module_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $default = '';
  if (isset($settings['my_module_regex_pattern'])) {
    $default = $settings['my_module_regex_pattern'];
  }
  $element = array();
  if ($display['type'] == 'my_module_regex_formatter') {
    $element['my_module_regex_pattern'] = array(
      '#type' => 'textfield',
      '#title' => t('Regex pattern'),
      '#default_value' => $default,
    );
  }

  return $element;
}

This will add Regex matches as an option in the Formatter select box within the Views configuration form for text fields, including the Body field. When you select the Regex matches formatter, a text input field will appear with the label Regex pattern. The pattern needs to include delimiters, and be properly escaped. The pattern in your question would look like this:

/\<h[23456]\>[^\<]*[\.!?:;,][^\<]*\<\/h[23456]\>/

The pattern is surrounded by a delimiter: /
All brackets are escaped: \<h, \>
The period is escaped: \.
The forward slash is escaped: \/h

preg_match_all() is used to perform a global regular expression match. The matches are outputted as an unordered list of escaped html (i.e. you will see the header tags in the output).


I've done it using Display Suite code field like that:

<?php
$max['amount'] = 0;
$min['amount'] = 0;
$products = field_get_items('node', $entity, 'field_products');
foreach($products as $product) {
  $product = commerce_product_load($product['product_id']);
  $commerce_price = array_shift(field_get_items('commerce_product', $product, 'commerce_price'));
  if($commerce_price['amount'] > $max['amount']) {
    $max = $commerce_price;
  }
  if($commerce_price['amount'] < $min['amount'] || $min['amount'] == 0) {
    $min = $commerce_price;
  }
}
return $min['amount'] < $max['amount'] ? commerce_currency_format($min['amount'], $min['currency_code']) . ' - ' . commerce_currency_format($max['amount'], $max['currency_code']) : commerce_currency_format($min['amount'], $min['currency_code']);
?>


How to have a webpage File Save As filename different from the page URL?

Its actually chrome browser (and some others) doing this based on the page title. For example firefox will actually prefer to save as the last part of the url instead. Make sure to use http://drupal.org/project/page_title module and that should give you what you are looking for. Not sure if there is a way to force it on firefox too.


Do All Drupal themes support subtheming?

No, of course it isn't true. All themes can be subthemed. Subtheming is a part of Drupal's core and themes cannot simply turn it down. You can always create a theme, name it's parent theme and override some CSS.

Fun starts when you want to override things from template.php, or if parent theme provides advanced configuration - not all themes are built in a way that makes subtheming easy. But even if it's not easy, it's not really blocked.


Is there any way to run hook_form_alter based on a form ’s class instead of it’s ID?

No - forms are only referred to by their ID (or 'base ID'), which is essentially the name of the function that defines them, or generally speaking, closely related to it.

So if you have

function MYMODULE_some_form($form, &$form_state) {
  // ...
}

Then the ID of that form is MYMODULE_some_form. It's not related to the HTML ID attribute, in case that's what you're thinking, so there's no class equivalent.


Xdebug: What Drupal values for "Project URL" & "Index File" will NetBeans accept for a new Configuration?

The trick to target a specific page using NetBeans and xDebug is to use Arguments.

File >> Project Properties >> Run Configuration
Project URL: http://hellofrom.local/
Index File: index.php
Arguments: q=admin/structure/views/view/post_drag/edit/page_1


How to check in Twig file whether node has a field?

I'm a friend of template pre-processing, in order to keep presentation logic separated from (advanced) field processing.

Therefore, I suggest a hook_preprocess_HOOK() implementation in your theme's *.theme file and outline this approach:

/**
 * Implements hook_preprocess_HOOK() for nodes.
 */
mytheme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  $example_class = '';
  if (
    $node->hasField('field_language')
    && !$node->field_language->isEmpty()
  ) {
    $variables['example_class'] = strtolower($node->field_language->value);
  }
  $variables['example_class'] = $example_class;
}

So you could access the newly added template variable {{ example_class }} within your node template:

{% for item in items %}
  {%
    set field_classes = [
      'field',
      field_name,
      example_class,
    ]
  %}
  <div{{ attributes.addClass(field_classes) }}>
    {{ item.content }}
  </div>
{% endfor %}

If you'd like to stick to just altering your template, you can also access all fields of a node entity within its templates by using the {{ node }} variable.

Keep in mind, that unrendered/preprocessed fields of the original entity usually are FieldItemLists. So you'll access an array of field item instances keyed by their delta:

{% if node.field_language and node.field_language[0].value == 'English' %}
...
{% endif %}

The {{ dump() }} Twig function can help you to debug your available values.


The initial sorting that you have specified in views is only used on the first page view. When you click on the header to change the sort the query is altered to use the drupal table sort routines instead. Unfortunately there is no support in the built in table sort code to allow multiple column sort, nor the ability to define a default of descending instead of ascending column. An alternative if your table is displaying all results is to add some Javascript that performs table sorts on the HTML and not provide sorting on the columns in Views. A google.com search for "javascript table sort" will give many results, this one looks to be quite robust: http://tablesorter.com/docs/


Views contextual filter not working for Pathauto path

Install Global Redirect module, this module create a unique form of all of the aliases. I am not able to test this solution of your problem But I guess it may solve the problem.


How to get workflow state transition history for a node?

The Workflow module has a lot of API calls that you can use to get the relevant information you need.

Here are all the workflow functions you can access

It seems like you might be looking specifically for the workflow_get_workflow_node_history_by_nid function

Here you supply a node ID and it will return the history results as an object where you can find the information you need.  It even joins it with the users table so you have all the relevant user information.


Well after ignoring this problem for a while it was time to find an answer.

The issue was with using $form['#tree'] = TRUE;
I didn't use the full array references after that...eg:
$form_state[$i]['description'] needed to be
$form_state['values']['items_fieldset'][$i]['description'] = 'foo';
(

After that I just used a foreach to grab my values from the dynamic field values...like:
foreach ($form_state['values']['items_fieldset'] as $v){
$submission->description[] = $v['description'];
}

And last was to dump them into my DB, and life is good.


Will image styles be applied when they do not logically apply?

It is all up to the PHP toolkit used to manipulate images. The code that is executed from the image effect is the following one. (See image_scale_and_crop_effect().)

function image_scale_and_crop(stdClass $image, $width, $height) {
  $scale = max($width / $image->info['width'], $height / $image->info['height']);
  $x = ($image->info['width'] * $scale - $width) / 2;
  $y = ($image->info['height'] * $scale - $height) / 2;

  if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
    return image_crop($image, $x, $y, $width, $height);
  }
  return FALSE;
}

The IF-statement is only used because image_resize() can return FALSE if the PHP image toolkit doesn't support the operation being executed on the image. The function called from image_size() (image_toolkit_invoke()) is generic, and it doesn't make assumptions about the operations currently enabled from the selected image toolkit.


Both menu link items and custom block content are treated as content within Drupal core. That's to say, they aren't covered by the configuration management system.

In instances where it make sense to have menu link items or custom block content stored in the configuration system, there are modules out there to assist with this:

Fixed block content: Provides a way of having permanent custom content blocks without broken instances if the block does not exist.
Config menu link: A drop-in replacement for core's Custom Menu Links module.

There many other options to store menu/block data into the config system so it's worth your time to explore other options to find the one that best matches your scenario (especially since Superfish seems to be a part of it).


How do I dynamically set up different cookies for multiple domains?

You should be able to do this by altering the services container: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services.

You can put your logic in there to dynamically set/override values that would usually be set static in a .yml file.


You need to configure URL options in links.task.yml file. See Url::fromUri for details.

your_module.export:
  title: Export
  route_name: entity.node.canonical
  options:
    query: {_format: json}
  base_route: entity.node.canonical


RSS Feeds: Using Aggregator (Drupal Core) vs Feeds module - which has more features and is more reliable?

Answering my own question, I would be inclined to say Feeds module, on the basis of:

more integration with other Drupal entities allowing more possibilities for manipulation of the content
extensibility - ability to extend with extension modules that parse the XML content of the feed to re-purpose it. e.g. rather than a text list of youtube videos, the actual videos themselves embedded into the page
standard api for extensions
well supported and active in drupal 7


Cache remains stale for custom blocks after editing

hope this works ...

<?php
abstract class BlockBase extends PluginBase implements BlockPluginInterface {
  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
    return array(
      'label' => '',
      'module' => $this->pluginDefinition['module'],
      'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE,
      'cache' => array(
        'max_age' => 0,
      ),
    );
  }
}

refer to this link block cache api is removed

The following block cache constants have been replaced with the combination of the cache.max_age and ::getCacheContexts() return values (or bubbled cache contexts) on blocks:

DRUPAL_NO_CACHE (equivalent: cache.max_age = 0)
DRUPAL_CACHE_CUSTOM (equivalent: cache.max_age = 0 + Cache::keyFromQuery())
DRUPAL_CACHE_PER_ROLE (equivalent: cache.max_age >0 + user.roles)
DRUPAL_CACHE_PER_USER (equivalent: cache.max_age >0 + user)
DRUPAL_CACHE_PER_PAGE (equivalent: cache.max_age >0 + url)
DRUPAL_CACHE_GLOBAL (equivalent: cache.max_age >0, no cache contexts)


Views2 Handlers: Fatal Error Class 'views_handler_field' not found

Is your class code in the same file as your hook, aka the .module or .views.inc file? That doesn't work because views_handler_field is in a separate file and only loaded when required.

You need to move it in a separate file which as the same name as your class and the ending ".inc", inside the folder that you defined in 'path'. (in your case, your module directory, for large modules with many files, it's recommended to place them in a views directory)

Then, views will automatically include your class including the file that contains views_handler_field (because you defined the parent relationship in your hook) when required.


The only way I can think is to use a views field template file to be overridden.

Copy the template sites/all/modules/views/theme/views-view-field.tpl.php to your current enabled theme folder. Assuming that you have a block view "product-listing", you could rename it to views-view-field--product-listing--block.tpl.php.

Rescan template files in your view theming information. The file views-view-field--product-listing--block.tpl.php just created should be highlighted with bold. Now, you have an active custom field template for your block view.

Then, you can edit the template as you need. Here is a sample code:

<?php
 $alias = drupal_get_path_alias('node/'.$row->nid);
 if(drupal_valid_path($alias)){
     $url = url($alias);
?>
    <a href="<?php print $url; ?>"><?php print $row->node_title; ?>
<?php
}else{
?>
    <?php print $row->node_title; ?>
<?php
}

You can check if a page ( or path ) exists or not by using drupal_valid_path().


How to move a field to a different region using Omega sub-theme / D7?

Thank you IRC! At least two modules will help with this (quotes included are from their project pages):

CCK Blocks:

  Since version 6.x-1.1 , the module does not hide the field in the node's content area anymore. You can do that for yourself in the display settings for your content type.

  CCK blocks will define a display mode named "CCK Blocks", which you can use to configure the display of fields when they are appearing as blocks.

  This allows you show the field both in the node's content area and in the CCK block, with different display settings.

Display Suite:

  ... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

  By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.


How to set Blocks settings in a Drupal Installation Profile?

You can use hook_block_info inside your custom module to add all of your blocks programmatically. Look at this SE Post for an example to use the hook_block_info to assign it to the right region and also enable/disable it by declaring status=>true/false.


Update a field based on value of another field in node edit form

Drupal 7:

Create a custom module. This module should implement hook_node_insert and hook_node_update. Both functions will have almost identical code, and it should go something like this:

/**
 * Implements hook_node_insert()
 */
function mymodule_node_insert($node) {
  if ($node->type == 'my_node_type') {
    // Set the $value variable with value you wish
    // to insert to the referenced node.
    $field = field_get_items('node', $node, 'field_whatever_it_is');
    $value = $field[0]['value'];

    // Grab the referenced node's nid.
    $field = field_get_items('node', $node, 'field_nodereference_field_name');
    $ref_nid = $field[0]['value'];

    // Load the referenced node into a variable. Avoid cached nodes.
    $ref_node = node_load($ref_nid, NULL, FALSE);

    // Update the referenced node with $value
    $ref_node->field_to_update[0]['value'] = $value;

    // Save the referenced node
    node_save($ref_node);
  }
}

If you just want to update the referenced node's node reference field with the current node's nid then you can also just use a module called Corresponding Node References


Assuming I understand your question correctly, it is possible. This is how I would do it (not sure how much this differs from the way you mentioned). Obviously you would need to change your page callback function, which you set for the tab in hook_menu(), to return a json object rather than a rendered page.

At the end of your page callback function you should add something like this:

// Return the rendered view in a JSON object. The object will contain a property
// named “contacts”, which containes the rendered view.  This will be sent to the
// browser and is accessable to javascript.
return drupal_json_output(array('contacts' => $view));
exit;

You would then need to include some javascript on the client-side to send an ajax request to the server using the URI/path you set for the tab in hook_menu.  This same client-side javascript would then process the returned data.

  currentMenuLink.click(function() {
      var updateContacts = function(data) {
        // The data parameter is a JSON object. Do something with the returned data here.
      };

      // Send ajax request.
      $.ajax({
        type: 'POST',
        url: this.href, // Which url should be handle the ajax request. This is the url defined in the  html tag
        error: function() {
          $('#namecards-get-contacts-by-nid-row-' + currentNid).show();
          $('#namecards-get-contacts-by-nid-cell-' + currentNid).html($('
An error has occurred while retrieving the list of contacts.  Please try again.  If the problem persists, please inform your website administrator.
'));
        },
        success: updateContacts, // The js function that will be called upon success request
        dataType: 'json', //define the type of data that is going to get back from the server
        data: 'js=1' //Pass a key/value pair
      });
      // return false so the navigation stops here and not continue to the page in the link.
      return false;
    }
  });


For multilingual sites, where are translated variables for the non-default language stored?

Please refer to this I18n translation of site_name not working

You need to enable 'Variable translation', 'Variable store' modules. Then you need to specify which variables you want to translate from Configuration -> Multilingual settings -> Variables. With this you would be able to translate your Site Information variables in different languages.

Now in Features, you can export translated variables from the section 'REALM VARIABLES'.


Submission of dynamically generated input fields

The WebformSubmissionStorage service uses the list of elements associated with the webform to properly store the data.  You are going to have to create an Element and WebformElement plugin definition that defines the element type (ie multiple, composite, etc...) and then attach your JS as a library.


The standard field handler in Views returns flat rendered output. To change this or put in the feature for even/odd numbered values you would need to implement a field handler plugin. For this task that would be a bit too much work. You can improvise in theming to get the same result.

In Views you can define a separator for multiple field values. Choose a separator that is not in the content of the field. Default is ','.

In Twig you can use the filter split to get the array items. Use the separator from the multiple field settings.

views-view-field--field-fieldname.html.twig

{% set items = output|split(',') %}

Put items in a loop and display only even number items:

{% for item in items %}
  {% if loop.index is even %}
    {{ item }}
  {% endif %}
{% endfor %}


Try Drupal SEO may be what you are looking for.  http://drupal.org/project/seotools

From its project page:

  The Drupal SEO Tools module seamlessly integrates a sophisticated all-in-one suite of search engine reporting, analysis and optimization tools into your website. It provides a dashboard that integrates analytics reports with links to webmaster tools and vital Drupal SEO modules.

Hope that helps.


How do I enable aggregation in the settings?

Your view appears to be a search API view, for which "aggregation" is not supported. Which is also why the "Use aggregation" option is not visible (credits: comment to question Clive).

A possible solution (work around?) to make the aggregation option available, is to NOT use the Search API for your view, and instead use a regular content type view (credits: comment to question Alfred Armstrong).

PS: Comments may get deleted, for all sorts of reasons, which is why I included them in this answer ...


Drush 9 doesn't come with drush.launcher so something is wrong with your Drush installation / update. You should try to fix that by updating or reinstalling Drush. However, in the meantime just delete drush.launcher.

PS! It's recommended to install Drush Launcher in addition to the site-local Drush.


Change Number of Values in CCK Filefield/Upload

/**
 * Implementation of hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form') {
    $form['field']['multiple']['#options'] = array(1 => t('Unlimited'), 0 => 1) + drupal_map_assoc(range(2, 24));
  }
}


In ur html rel="gallery-all" is available which means you allow to load all the images in the galery or page, for resolving your issue (for single load) remove this rel attribute.

The rel attribute specifies the relationship between the current document and the linked document.In colorbox "gallery-all" means it will load all images to colorbox. For eg here load 4 images, perhaps select "single" load the main image


Render filename of file upload field in node template

I think you missed a key in between. Try,

$output2 = field_view_value('node', $node, 'field_file_upload', $item[0]);
foreach ($output2 as $key) {
  if(is_object($key)) {
    echo "File Name: ".$key -> filename;
  }
}


How can i put popup box captcha on managed file remove button?

I have solved it. I have hide remove button access. and then put my own remove button, and open dialog box in form to display popup box.

please see code.

drupal_add_library('system', 'ui.dialog');
drupal_add_js('jQuery(document).ready(function(){
    jQuery("#clicky").live("click", function(){
        jQuery("#dialog").dialog({ modal: true ,height: 250,width: 350, buttons: [
            {
            text: "Cancel",
            click: function() {
                jQuery(this).dialog("close");
            }},
            {
                text: "Submit",
                click: function() {
                     jQuery("#dialog-form").submit();
            }}
        ]});});});', 'inline');


As the documentation you linked says, the structure for the fivestar field is the following.

{
  "field_fivestar":[{
    "rating":"100",
    "target":"0"
  }]
}

Probably you are missing "target"

Also, if you are using auto complete for taxonomy you should use the term id, tid, 3 times:

{
  "field_termins":[{
    "tid":{
      "tid":"[tid:26686]"
    }
   }]
}

Auto complete is the tricky part.


Multiple url aliasses per node in multi language website

I'm not sure if this article helps, but here it is: https://www.drupal.org/node/1516444

For something more complex, I've actually implemented a hook_url_inbound_alter() to control the redirection of pages and it's worked pretty well for me, but it involves creating the logic yourself. On the other hand, the benefit is that you can completely control when and where you redirect page visits.


Intercept 404s for pages in certain path

Use the Match Redirect module to redirect specific pages that matches urls.

Summary of drupal project page :

This module provides redirecting based on path patterns with wildcards. This functions much like how block page visibility works. You specify a pattern like "old-blog/*" and a target like "new-blog" and all pages under old-blog will be redirected to the page new-blog.

Features
Pattern matching allowing wildcard redirects
Redirect code choice (301, 302, etc)
Filters out existing pages so they won't be redirected (unless overridden)
Loop protection (no chaining redirects allowed)


What is causing the "username_link not found" error in the LDAP integration module?

According to comment nr 2 in issue nr 2751219 this is not a bug, but it's just a configuration issue. Here is a quote from it:

  Incorrect admin password for LDAP server.

So double check the password is correct, and try again ...


List all Ubercart product fields found in uc_product_field_extra_fields()

It turns out that in uc_product_field_extra_fields(), the extra fields are defined for 'display' and not for 'form'. The correct call is field_info_extra_fields('node', 'product', 'display');


Allowed memory size exhausted after importing PO file

Generating/exporting Feature modules takes a lot of memory, depending on amount of components which you're trying to export. The Features module is constantly improving, so please check the recent stable version if that makes the difference.

Otherwise you've to increase your PHP memory limit either in your php.ini or before the import, temporary add this line into your settings.php file:

ini_set('memory_limit','1G');

If you would like to debug what takes so much memory, then you need to use PHP profiler such as XDebug (xdebug.profiler_enable=1) or use XHProf.


Watchdog reports many spammy looking page not found warnings

Pretty much every site online is being scanned by bots looking for security holes. The more popular the site, the more common this is. They don't necessarily follow links from the site itself, and even on Drupal sites you'll see requests for paths like "/wp-admin".

And you can exit via Ctrl-C.


How to send a message notification based on a flagged node being linked via entity reference?

It works, after days and days it finaly works! I used this as a base line for my research: Sending a message to users of a flagged node when it is referenced

Instead of sending an e-mail within the loop, i create a new entity(action), in this case the message notification. After that i fill(set data) in the entity-created:field-mnc-recipients field with the flagging users. This is how it works :)


Navigate to page with content displays page not found error

You need to have some sort of content assigned to the URL url1. The simplest way would be to create a new Basic page node and set its URL alias field to url1.

By the way, what you are seeing now is the "page that is displayed when no other content matches the requested document" (Administration >> Configuration >> System >> Site Information >> Default 404 (not found) page). You can have a specific page assigned as your Page not found page, or Drupal will build the content for it on the fly, and show it using the most appropriate template in your theme (most likely page.tpl.php).


Adding custom module pages to the Solr index

Apache Solr Search Integration is a replacement for the core content search.
This means that the output of your custom modules will appear in the Solr index, if the modules create nodes.

If the content returned by the custom modules is dynamic, then they need to create dummy nodes that they will be updated with hook_nodeapi(). When ApacheSolr rebuilds its index, it loads the node with node_load(), which then invokes any implementation of hook_nodeapi(), passing "load" as operation parameter.


How can I display the block title when rendering a block using Twig Tweak?

You'll have to manually type it on your twig, as per https://www.drupal.org/project/twig_tweak/issues/2738781

If you don't want to type it on twig, a work around would be to add a "Text area" to your view's Header and use replacement patterns,
[view:title]
.

Alternatively, you could ditch Twig Tweak and do it yourself by creating a variable:

function MY_THEME_preprocess_HOOK(&$variables) {
    // replace HOOK with the template file you're trying to add it to. Ex: node, page, block etc..
    $view  = views_embed_view('view_name', 'block_1');
    $variables["my_view"] = \Drupal::service('renderer')->render($view);
}

Then in the template file you just do {{ my_view }}


That's typical in Drupal. In this very moment, This is the CSS styling I use in scenario similar to yours:

.some-div-class label,  .some-div-class input[type="text"] {
  display:inline;
  width:auto;
  font-size:0.8em;
}

This will work fine on mobile devices as well.

Please do note your own CSS may need a bit more work.


Multi-language menu's / menu-items setup

At the moment it is not possible to translate the menu items in the node form:

  Unfortunately the node form's menu widget was not made ready for menu
  item translations (yet), so if you provide the French menu item title
  there, it will be updated in the original item and not going to create
  a translation. Until that is fixed, use the menu item translation
  process as with the contact menu item.

Drupal 8 multilingual tidbits 20: combination use cases with content and menus

The solution presented by Gábor Hojtsy in the link is to translate the menu in the menu management or use different menus for every language.


Is there any way to check user activation link has been sent

Use Mail Logger  module. It simply logs all outgoing emails into a database table.
You can view the logged emails by going to the Reports -> Outgoing Mail log entries page.


How to flip order of Privatemsg thread from ASC to DESC?

Any other ways I can get it to work, outside of hacking the module?

There is no way to alter a module from another php file / module unless it provides a hook, luckily here they did.

I must be blind, right above it (line 1098), it says in the comments: * @see hook_query_privatemsg_messages_alter()

I found the doc hook_query_privatemsg_messages_alter. Hooks go inside modules, more specifically inside the .module file and you replace the word hook with the actual name of your module.

So create a custom module, inside of mymodule.module (Here we assume your module is called/named mymodule)

/**
 * Implements hook_query_privatemsg_messages_alter().
 */
function mymodule_query_privatemsg_messages_alter($query) {
   $query
     ->orderBy('pm.timestamp', 'DESC')
     ->orderBy('pmi.mid', 'DESC');
}

Side note:

Don't confuse hooks with templates_something_something() those go inside your template.php file. Ex: template_preprocess_node and you replace the word template with the actual name of your theme.

  No Sssweat, can I bother you for one other thing? I'd like to move the
  reply box above the message thread. I found where this is handled in
  the module (privatemsg.pages.inc, lines 892 and 926). How would I
  override those two lines (adjusting the "weight" values so that the
  reply box is a lower weight than the message thread) without hacking
  the inc file? Would it be done somehow in a custom module?

You're suppose to use hook_privatemsg_view_alter

Sadly, it does not work for reply or message; even though, when I dump dpm($content) using Devel the array it has changed the weight. Works for pager only. Looks like this is a bug.

/**
 * Implements hook_privatemsg_view_alter().
 */
function mymodule_privatemsg_view_alter($content) {

    $content['pager']['#weight'] = -3; // does not work
    $content['reply']['#weight'] = -5; // does not work
    // nor it does not work when doing $content['message']['#weight'] = -5;

}

If I comment out the $content['pager']['#weight'] = 3 and $content['reply']['#weight'] = -5; from the module, the hook works.


You can use a title callback function along with title arguments:

$items['path/path/%'] = array(
  'title callback' => 'MYMODULE_page_title',
  'title arguments' => array(2),
  'page callback'    => 'pagecallback',
  'page arguments' => array(2),
  'type'             => MENU_CALLBACK,
  'access arguments' => array('access content'),
);

function MYMODULE_page_title($arg) {
  return t('Arg is: @arg', array('@arg' => $arg));
}

The default title callback is t(), so if you just need the argument to be passed straight through as the title you can get away with just using title arguments.

See hook_menu() for more details.


Change file path of aggregated CSS file path

Not the answer you're looking for but it does solve the problem you're having (old css); try the Advanced CSS/JS Aggregation module.


How to send a webform email to all users of a specific role?

From the exported rule in your question, it seems you already have the Webform Rules module enabled (a prereq for what follows ...).

You may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

Some more details about the VBO-view you'd have to create for this:

Create a list users, using the Views module.
It should include an appropriate filter for the role to be processed.
It should have exactly 1 result (row) for each user to be eMailed.
One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Core patching and version controlling across multiple versions of the same site

Drupal has a good guide for this. A general summary for updating would be:

Delete everything except sites
Unpack the latest Drupal in the same place
Run the updater via update.php.
Check for breakage.
Update modules if necessary. They'll most likely be outdated too.

When all is good, commit all the updated code. Ideally you'd have separate commits for the core update, and for each module you updated. Then push up your code to your remote repo.

Now over to your environments, you simply do a git pull. If your remote repo is the filesystem of the remote environment (i.e. Acquia, Pantheon), then pulling isn't required. Set the site to maintenance mode, and run the updater. Ideally, you'll have this automated. If you use Drush, then it's just the following commands:

drush vset maintenance_mode 1 # enable maintenance mode
git pull                      # pull in the latest code
drush updb                    # perform updates
drush vset maintenance_mode 0 # disable maintenance mode


How to send to redirect to a user after creating a node and display a message?

The rules module can act on a "A new node has been created" event and has both "Page redirect" and "Display a message to a user" actions.


Providing a vocabulary in a custom module

You should make use of the taxonomy module's functions such as taxonomy_save_vocabulary() and taxonomy_save_term() (Drupal 6), or taxonomy_vocabulary_save() and taxonomy_term_save() (Drupal 7) to populate your custom vocabulary. Creating fields should be accomplished via the Field API. There really should be no need to directly interact with the database.

Term translation is not supported out of the box in Drupal 7, but I do believe that the internationalization module provides a module that has cobbles together support for it.


Is Drupal suitable for that kind of ecommerce?

Yes it is possible, most of which using Rules, Fields, Date and Views. I'd say that, due to the specificity around some features, Commerce would be best as it fully taps into the Entity API which makes developing a breeze.