Drupal doesn't have the concept of sub-modules. It just happens that it looks for modules in the directories where it expects to find modules, recursively. For example, if you install the CAPTCHA module, Drupal will find also the Image CAPTCHA module, and allow you to install it.

Drupal will not install it automatically, nor will it handle it differently from any other module. This means, for example, that the module still needs to declare its dependency from the CAPTCHA module, if it requires it, which is what the Image CAPTCHA module does in its image_captcha.info.yml file.

name: Image CAPTCHA
type: module
description: Provides an image based CAPTCHA.
package: Spam control
core: 8.x
dependencies:
  - captcha
configure: admin/config/people/captcha/image_captcha

Usually, developers put any "sub-module" in the modules directory, but this is not required from Drupal, nor is it followed by every developer.


How can I create a Install New Module-style "add button"?

Figured it out. You create a sub-item in your hook_menu(), then set its type to MENU_LOCAL_ACTION.

  $items['menu/url'] = array(
    // --snip--
    'type' => MENU_LOCAL_ACTION,
    // --snip--
  );


Panels template files: Inheriting a tpl file in a sub theme

Here's the weird news, just having a panels-pane.tpl.php in a parent theme should work. It's working for me in a highly used parent theme. So I'm guessing any theme suggestions or other steps aren't going to cut it...

I would check for typos, in this case I would look at the file name (sounds like that's fine), then I would check the sub-theme info file to make sure that's set correctly (although it sounds like that may also be right)

base theme = base_theme_name

Then I would check file permissions on tpl/theme folder. 664 tends to work for me, and apache needs access to it and the folder it's in.

If that seems fine my two steps before I panic with drupal are:

drush rr

restart apache

Hope that helps.


Updated to Drupal 7.51 and website is now stuck in maintenance mode

I am compiling here some points which I found. Following list I have ordered them from common to complex solution.

1. Clear cache:

First thing you can do is clear the cache. If you read the forum discussion on the Drupal forum page titled: Site stuck in maintenance mode!, you'll find various people solved this issue just by clearing the cache.

Through Admin UI: As per this comment just clear the cache by going at Administration/configuration/performance.
Using Drush: If you are using drush, you can do this by command drush cc all.
Other methods: If above both methods are not accessible for you, you can try other methods witch are listed in this article: [Drupal]Methods to clear Drupal caches

2. Login to site:

You can try some methods to login into site while still site in maintenance mode.

Login to site using /user/login: On this question of DA: How can get my site out of maintenance mode? @Dmitry has stated in his answer,

  Just go to /user/login, it works even in maintenance mode, and then
  sign in as an admin.

On other Drupal forum QA also if you see the comment on this Link, it talks about using /user/login. I have pasted here,

  I just had a similar issue with a D7 site I was performing maintenance
  on. Logging in via http://example.com/user and
  http://example.com/?q=user wasn't working. What did, though, was
  http://example.com/user/login.

3. Changing Maintenance Mode setting:

@mixerowsky has very well explained various ways of changing the maintenance mode in his answer at this DA question: How can get my site out of maintenance mode?


According to  Drupal db_like doc page

Get a database connection injected into your service from the
container and call escapeLike() on it.

For example,
$injected_database->escapeLike($string);

Try something like:
$database = \Drupal::database();
$result = $database->select('table_name', 't')
    ->fields('t', ['field_1', 'field_2'])
    ->condition('field_1', "%" . $database->escapeLike($string) . "%", 'LIKE')
    ->execute()
    ->fetchAll();

Read Database api in Drupal 8 for a better understanding of database query in drupal 8.


Why does Behat throw an error on "ucan "?

While debugging with xdebug in PhpStorm I figured out that user_load_by_mail($mail) loads cached users. user_load_by_mail() uses this function:

/**
 * Load multiple users based on certain conditions.
 *
 * This function should be used whenever you need to load more than one user
 * from the database. Users are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * @param $uids
 *   An array of user IDs.
 * @param $conditions
 *   (deprecated) An associative array of conditions on the {users}
 *   table, where the keys are the database fields and the values are the
 *   values those fields must have. Instead, it is preferable to use
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
 *   this function.
 * @param $reset
 *   A boolean indicating that the internal cache should be reset. Use this if
 *   loading a user object which has been altered during the page request.
 *
 * @return
 *   An array of user objects, indexed by uid.
 *
 * @see entity_load()
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
 * @see EntityFieldQuery
 *
 * @todo Remove $conditions in Drupal 8.
 */
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
  return entity_load('user', $uids, $conditions, $reset);
}

But it calls this function without $reset == true. That's why it uses cached user objects and tries to delete an already deleted user.

I fixed this lines with:

// Delete Testuser before the Scenario.
    if (in_array($title, $scenarios)) {
      foreach ($users_to_clean as $mail) {
        $users = user_load_multiple(array(), array('mail' => $mail), true);
        $user = reset($users);
        if ($user) {
          shell_exec('drush ucan ' . $user->name . ' -y');
        }
      }
    }


Why is 'Confirm Order' pane being skipped?

This checkout pane / page is added by the PayPal Express Checkout module. PayPal EC has a step where you return from PayPal after authorizing payment to finalize the order, including taxes, shipping selection, coupon entering, etc. For other payment methods, this page is skipped.


Contact form to notify the author of the node

You may try the Privatemsg module.

  Privatemsg allows your site's visitors to send private messages to each other. Perfect for community oriented sites, such as forums and social networking sites. Many additional features are available as separate modules.

  Current features

  send and receive private messages on a site (between multiple recipients)
  threaded conversations (make it easier to keep track of messages and replies)
  search private messages
  tagging and filtering (helps organise conversations)
  user blocking
  e-mail notifications of new messages


Drupal 7 Change User Login block link text

You could use a template, probably named something like 'user-login.tpl.php'

For more information on 'working with template suggestions' have a look at http://drupal.org/node/223440


How to allow users to choose different theme?

I didn't look this up, but if I'm not mistaken, you should enable the themes users can choose from, and give the appropriate user role(s) the "select different theme" permission.


redirect user to page where they clicked an "add node" link

You can use Token Filter module and the following code should work:

Add Contact

Make sure that the token filter is available in the text format you are using.


How to hide Default values using Drupal Behaviour

To start with, as you're namespacing jQuery you can use the $ instead of jQuery inside the (function (jQuery) { ... });

Secondly, you're not pointing to classes or ID's in your jQuery.  I'm pretty sure that edit-submitted-phone should be #edit-submitted-phone in every instance in your code.

If this doesn't work, then let me know and I'll see what else I can come up with.


In OG 7.2 you need to enable Rules module then enable the two rules for "Pending" and "Active" memberships


Using Migrate in Drupal 6, setup and parsing XML

Yes, look at the Beer examples that come in the migrate module itself. If you want some example code and usage with some explanation I find the BTMash blog posts useful. While the BTMash blog is D7 based -- the hooks and usage of Migrate is widely similiar between D6 and D7.


Add Location CCK field and instance programmatically to content type in Drupal 7

Never mind I figured it out. The following params work (note that the entity type and bundle params are also needed, but for my own usage I add these later).

For field_create_field:

'field_property_location' => [
    'field_name' => 'field_property_location',
    'label' => $t('Location'),
    'type' => 'location',
    'module' => 'location_cck',
    'settings' => [
        'location_settings' => [
            'form' => [
                'fields' => [
                    'name' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 1,
                    ],
                    'street' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 2,
                    ],
                    'additional' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 3,
                    ],
                    'city' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 4,
                    ],
                    'province' => [
                        'collect' => 1,
                        'widget' => 'autocomplete',
                        'default' => '',
                        'weight' => 5,
                    ],
                    'postal_code' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 6,
                    ],
                    'country' => [
                        'collect' => 1,
                        'default' => 'gb',
                        'weight' => 7,
                    ],
                    'locpick' => [
                        'collect' => 0,
                        'weight' => 20,
                    ],
                ]
            ],
        ]
    ],
],

For field_create_instance:

'field_property_location' => [
    'field_name' => 'field_property_location',
    'label' => $t('Location'),
    'required' => true,
    'widget' => [
        'weight' => '0',
        'type' => 'location',
        'module' => 'location_cck',
        'active' => 1,
    ],
     display' => [
        'default' => [
            'label' => 'above',
            'type' => 'location_default',
            'weight' => 0,
        ],
    ],
],

There are more params you can fiddle with but these are the ones that suited my needs. To figure the params (and to figure out params for other fields like this in future), first add the fields manually to the content type with the desired settings in the Drupal backend. Then in the command line go to the projects root directory and used drush eval "print_r(field_info_fields())" to see all the fields added and drush eval "print_r(field_info_instances())" to see all the field instances added.

Mirror the data and structure from the print out to use in the field_create_field and field_create_instance functions as I've done above.


`drush uli` generates correct link but results in 'Access Denied'

This can happen when the user is blocked. Setting the status to 1 in the Users table may resolve it.


You can open your theme's .info file and add regions[my_region] = My region. Now open your page.tpl.php and do print $my_region (the name of the variable corresponds to the regions array index - see the first sentence) where the region should be rendered. After this make sure to clear your Drupal's cache so that it picks up the new region and the modified page.tpl.php.

Views can generate block displays. After you created the block display, you can use the Drupal's default blocks interface to put the Views block into the region you created, or better yet use a module like: Context which gives you more control over when to show which blocks in what region and when not to...


Show parent items in hierarchical facet display

Enable the "Index hierarchy" option under your index filters. After enabling you can choose the field(s) for which you want to index the hierarchy. Save. Re-index.

Parent terms will now show in your facet.


Access denied when enabling or setting by default a theme (on Nginx)

I've got a solution after several hours working on it.

I am using Nginx instead of Apache and I did not configure it to add the query string in the rewriting to index.php. So neither the token nor the theme parameters were reaching the script and system_theme_enable()/system_theme_default() (located in /modules/system/system.admin.inc) always returned MENU_ACCESS_DENIED, which I consider to be a very confusing behavior by the way.

This is how the server config looks like now and makes it work:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}


How can I convert a node title to a lowercase string with hyphens?

If you're just looking for a way to convert the title into a URL friendly machine name, then the following regex will do what you need:

$machine_name = preg_replace('@[^a-z0-9-]+@','-', strtolower($title));


How to add an extra form action on the user login page?

Use hook_form_FORM_ID_alter() in order to modify the specific form.
You can add the action or the link there.
The link can be added using the #prefix,#suffix attributes of either the form or of a specific element.

Prefix example:

$form['#prefix'] = l(t('Link text'), 'my link');

Action example:

$form['actions']['add'] = array(
  '#type' => 'submit',
  '#value' => t('Add'),
  '#submit' => array('_my_callback_function'),
);


Assign a class to an element dependent on multisite domain?

Well i decided to use different .css files with this code:

// Allow a site-specific user defined CSS file (useful for multisite installations):
// If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"),
// it will be loaded after "local.css". SITE is the site's host name, without leading "www".
// For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css"
global $base_url;
$site = preg_replace("/^[^\/]+[\/]+/", '', $base_url);
$site = preg_replace("/[\/].+/", '', $site);
$site = preg_replace("/^www[^.]*[.]/", '', $site);
drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all');


Migrate error: Call to a member function count() on a non-object

It seems the problem was the files not saving properly after I updated them, The code I posed above seems to be working ok now.


Is there a way to have a language neutral link that automatically redirects to the user's active language?

I'm not familiar with the "slider" module. But from the example URLs you added, it seems to me that at least you should check your configuration at Configuration -> Languages -> detection and selection: the order specified there should be 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ...

Curious to hear what the result of checking this will be ...


Call User Profile Field in Node Template

global $user is that of the currently logged in user, not specifically the owner of any specific content.

So what your code was doing was just looping through printing your byline, eg, admin, eg uid 1.  What you need to do is grab the uid from the specific user's content, user_load(THAT-UID) into a variable, and then use that to get the byline into vars[] in hook_preprocess_node() so it goes to the specific node in question, not the page it is printed on.

(in D6 at least, still learning D7 but I am sure it's pretty similar)

Addition/Edit:  In D6, you can get the uid of the node author like this:

function hook_preprocess_node(&$vars) {

  $node=$vars['node'];
  $uid=$node->uid;

  $byline= "whatever you need to do to get it with $uid"

  $vars['byline']=$byline;

}

just change hook to your theme or module name and you should be on your way.  You can now use the byline variable in your node.tpl.php (barring any typos or brainfades of mine above :)


How to programmatically import a block to existing view?

The indicated "block" you point out in the UI, is internally called a "display". Displays are stored inside the view object in the display property (e.g. $view->display).
If you look at the views export code you should see the pattern of exported blocks (e.g. /* Display: Block 1 */, /* Display: Block 2 */, etc.) that's rendered by the views::export() method.
For each block (i.e. display) you should see the $handler = $view->new_display(...) followed by many $handler->display... lines that add the relevant fields/filters for that display.
To programmatically import a single display you would do something like the following:
$view = views_get_view('my_existing_view');
// @TODO: Add my new display handler code
$view->save();


How do I get third party jQuery plugins to work with Drupal?

Read Managing Javascript in Drupal 7 for the full details, but basically you're looking for something like this:

(function($, Drupal) {
  Drupal.behaviors.sliderRevolution = {
    attach: function(context, settings) {
      $('.tp-banner', context).once('sliderRevolution', function() {
        $(this).revolution({
          delay:9000,
          startwidth:1170,
          startheight:500,
          hideThumbs:10
        });
      });
    }
  }
})(jQuery, Drupal);


Create Taxonomy term with added text and date fields, then display them in "add content"

Am not familiar with any contributed module which will server your requirement.
But i can help you to achieve this functionality.

Add the Date and Notes field to the specific content type using the 'Add Existing field' option. Since you have already created the fields for taxonomy term, its not necessary to create a new fields.

While adding a new content of that particular content type, mention the category , date and notes in the respective fields.

Now what we need to do is to hack-into the node submit flow and update the specific taxonomy term with the newly entered date and notes values.

Easily do this by using a single hook : hook_node_presave($node)

You can using this hook in any of the custom module. The '$node' variable will contain the date and notes values. We can easily load the selected taxonomy and update the date and notes of the taxonomy via DB queries

Thanks,
Vineeth


How to use subgroups in drupal_add_tabledrag()

If you want ajaxed example perhaps you can study the Display Suite UI.

In my opinion the easiest way to do this if you need similar functionality is just to use the block module tpl's and change the data presented inside it (from block region to your custom module regions)

to remove the weights, I think if you remove :

drupal_add_tabledrag('blocks', 'order', 'sibling', 'block-weight', 'block-weight-' . $region);

it will remove the ability to drag and sort the weight.

some rough examples for "Drupal compliant" way :

note: this is VERY rough code, you will need to adjust it heavily

function theme_example(&$variables) {
  // build the header
  $header = array(
    '', // this will be hidden when table drag run
    '', // this will be hidden when table drag run
    t('Block Region'),
    t('Region Area'),
  );
  // enabled region
  //$regions = region_area_grab_region('enabled');
  // substitute this to what ever your module provides
  // this should be in $form array
  $regions = array('example_one', 'example_two', 'example_three');

  $region = array('example_block_one', 'example_block_two', 'example_block_three');

  // Add table javascript.
  drupal_add_js('misc/tableheader.js');
  drupal_add_js(drupal_get_path('module', 'block') . '/block.js');

  // take notice of the key that will be related to real options
  // in the select box, this should be in $form array
  $options = array();
  foreach ($regions as $key => $region) {
    $options[$region] = $region;
  }

  // add additional class here
  $attributes = array(
    'class' => array('draggable'),
  );

  // building the table rows
  $rows = array();

  // looping for each regions
  foreach ($regions as $region) {

    // this is the heart of the draggable
    // take good notice for the region-manager (the table id), region-area-weight (group of rows class)
    // and regionarea-weight- $region (unique row class), you will need to add this to the form array
    // element NOT in the table row

    // if you want to emulate the block page table drag, comment out the drupal_add_tabledrag
    drupal_add_tabledrag('region-manager', 'order', 'group', 'regionarea-weight', 'regionarea-weight-' . $region , $hidden = FALSE);
    // build the region row

    // replace this with your form element array eg $variables['form']['whatever']
    $elements = regionarea_build_admin_region_form($region, $form, $form_state);

    $row = array();
    $row[] = '';
    $row[] = drupal_render($elements[$region['name']]['weight']); // replace this to actual form array for the weight
    $row[] = $elements[$region['name']]['name']['#value']; // replace this to actual form array for the value / title
    $row[] = drupal_render($elements[$region['name']]['enabled']); // optional
    $row = array_merge(array('data' => $row), $attributes); // merge the array, add draggable class
    $rows[] = $row; // build the row

    // ----------------------------------------------------------------------------------------------------------------- //
    // Usually up to this point is enough for just normal draggable, only continue if you have a sub child to drag
    // ----------------------------------------------------------------------------------------------------------------- //

    // build the block regions
    // now we looping for the sub child AKA regions as in the block region page
    foreach($region['regions'] as $regionkey => $blockregion) {
      // add two table drag, one for weight the other for 'region'
      drupal_add_tabledrag('region-manager', 'match', 'sibling', 'region-select', 'region-' . $blockregion, NULL, FALSE);
      drupal_add_tabledrag('region-manager', 'order', 'sibling', 'region-weight', 'weight-' . $blockregion);

      // replace this with your form element array eg $variables['form']['whatever']['children']
      $elements = regionarea_build_admin_blockregion_form($blockregion, $regionkey, $options, $form, $form_state);

      // build the current row
      $row = array();
      $row[] = '';
      $row[] = drupal_render($elements[$blockregion]['weight']);
      $row[] = $elements[$blockregion]['name']['#value'];
      $row[] = drupal_render($elements[$blockregion]['regions']);

      $row = array_merge(array('data' => $row), $attributes);
      $rows[] = $row;
    }

  }

  // some options to pass to the theme_table
  $element = array(
    '#empty' => t('There are no region area available'),
    '#attributes' => array(
      'id' => 'region-manager',
    )
  );

  // build the theme
  return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes'])),
}


Get() on array in settings from custom Form controller

You can handle the config like an array:

$form['infoblock_text'] = [
    '#type'          => 'text_format',
    '#title'         => t('Infoblock text'),
    '#description'   => t('The body text for the infoblock on the front page'),
    '#format'        => isset($config->get('infoblock_text')['format']) ? $config->get('infoblock_text')['format'] : 'full_html',
    '#default_value' => isset($config->get('infoblock_text')['value']) ? $config->get('infoblock_text')['value'] : '',
];

When accessing the array like this, it's always a good idea to check if the key is set. This avoids warnings in your log.


Apply comments votes to parent node (with Rate module)

No, it is not possible.

And also unlike Fivestar module, where the rating field can be made visible in node/comment form and node/comment display, the Rate module allows you to add the field only on node/comment display, not on form.


You might want to do something like this in your template.php file.

function MYTHEME_preprocess_node($vars) {
  switch (arg(0)) {
    case 'red-car':
      drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/red-car.css");
      break;
    case 'blue-house':
      drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/blue-house.css");
      break;
  }
}


Upgrading Drush 6 to Drush 9 on Centos 5 server

drush dl drush downloads the obsolete version of Drush from drupal.org. Drush was never intended to be used to download Drush via the pm-download command, even when it was hosted on drupal.org; the fact that this works is more of an anomaly or coincidence than design.

To update to a newer Drush, follow the usual instructions in the Drush documentation.  Since you already have Drush in usr/bin/drush, use this location instead of the location stipulated in the docs (usr/local/bin/drush).

wget http://files.drush.org/drush.phar
chmod +x drush.phar
sudo mv drush.phar /usr/bin/drush

The Drush at files.drush.org/drush.phar is always the most recent stable version of Drush. To download a specific version, visit https://github.com/drush-ops/drush/releases. There is a phar available with every release of Drush from version 8 and later.  You can, of course, replace your /usr/bin/drush at any time that you need to upgrade.


How to get the taxonomy translated in URLs?

I've been able to do that, using Entity Translation instead of Taxonomy translation (part of i18n) for translating taxonomy terms, and using the Title module to replace the name field of the taxonomy term and making it translatable.

It works so far.


"Deprecated function: implode()" on GMap Drupal module

This answer draws upon the comments above by leymannx. The essential problem is an incompatibility between the GMap module and PHP 7.4, for which a patch is available. In this answer the patch is applied to the code repository itself, prior to any Docker builds, this is possibly the cleanest method.
The first step is to download the patch into the right folder in the repository:
cd sites/all/modules/gmap
wget https://www.drupal.org/files/issues/2020-03-06/gmap-php7.4.patch

The patch file is encoded for MSDOS, therefore it must be converted before the patch can be applied. Here all the target files are converted too, as a precaution:
dos2unix ./gmap-php7.4.patch
dos2unix gmap_test/gmap_test.features.inc
dos2unix lib/Drupal/gmap/GmapDefaults.php
dos2unix tests/inc/gmap_defaults.inc

The patch can now be applied. Since this is a git repository, the git command itself can not be used.
patch -p1 -i ./gmap-php7.4.patch

Finally remove all the extra files the process may have created. They are not needed in the container.
rm *.patch gmap_test/gmap_test.features.inc.orig lib/Drupal/gmap/GmapDefaults.php.orig tests/inc/gmap_defaults.inc.orig


Get a list of revision IDs for any given entity?

Figured it out. I'll leave it here because it might be useful to someone down the road.

You can use this function to get a list of all revisions ids for any given entity.

/**
 * Get a revision id list for a particular entity.
 */
function get_entity_revision_list($type, $entity) {
  $info = entity_get_info($type);
  if (!isset($info['revision table'])) {
    // If this entity does not track revisions then return FALSE.
    return FALSE;
  }
  if (!isset($info['entity keys']['revision'])) {
    // If for whatever reason a revision table was defined, but no revision key
    // then also return FALSE.
    return FALSE;
  }
  $revisions = db_select($info['revision table'], 'r')
    ->fields('r', array($info['entity keys']['revision']))
    ->condition($info['entity keys']['id'], $entity->{$info['entity keys']['id']})
    ->execute()
    ->fetchAllAssoc($info['entity keys']['revision']);
  return array_keys($revisions);
}


Bulk change radio button setting in admin/content using database

Have you tried bulk operations? You can select a bunch of nodes from the content overview page, and use bulk operations to change values on all of them. https://www.drupal.org/project/views_bulk_operations


I can't post all the code you would need, but essentially you will want to do a form alter, and add an #ajax item on the submit button and point it at a callback. This callback will perform validation and submission - at the end of it you can issue a ReplaceCommand. Here's an example:

function mymodule_form_submit($form, FormStateInterface $form_state) {
  // code here to handle the submission aspect
  // you'll need to manually submit form value data to Webform using webform api

  // if successful, this is the response
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('selector', 'data'));
  return $response;
}

Where selector is an HTML element, and data is what you want to replace it with.

Sounds like you would want the selector to be the id of the container wrapping the form, and the replacement should be the confirmation message from Webform (you'd have to get it from fetching the config of that form). This will cause a non page refresh and instead, the form will be replaced with the confirmation message.


Use multifield values to create new nodes

I managed to solve this by swapping the Multifield for a Double Field which does play nicely with Rules.

I was then able to use Rules Action: generate a list from an integer to loop through the quantity for each category and create a new node for each, populating the required fields.

The only downside is that Double Field does not allow to populate a select list from a taxonomy vocabulary, and I could not get the Field Remove Item or Multiple Fields Remove Button modules to work with it.


How to add custom node field into page title?

A hook_preprocess_page function in your template.php file would certainly be one way to do it:

function MYTHEME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'article') {
    $data = $node->field_custom_field[$node->language][0]['value'];

    $vars['title'] = $vars['title'] . ' ' . $data;
  }
}

In page.tpl.php your $title variable should contain your new string based on the field.

You'll probably want to do a couple of extra checks in there as well, for example making sure the node is of the right type, etc.

EDIT

To address your comments I guess you'd want to do something like this:

$area_size = $node->field_area_size[$node->language][0]['value'];
$location = $node->field_location[$node->language][0]['value'];

$vars['title'] = "$vars[title] $area_size sq ft ($location)";


What function should I use in instead of mimemail()?

The reason the mimemail() function does not exist for Drupal 7 is because it is not needed.

See, for instance, issue: API function for quick send html mail without uneccessary operations (mimemail analog from 6.x) in the project's issue queue;

  On Drupal 7 calling drupal_mail() is enough. See the README.txt and drupal_mail_system() for more information.

The general idea is that you set up the Drupal to use MimeMailSystem for some or all mail messages sent by your module:

mailsystem_set(array(
  '{$module}_{$key}' => 'MimeMailSystem', // Just messages with $key sent by $module.
  '{$module}' => 'MimeMailSystem', // All messages sent by $module.
));

and then calling drupal_mail() is enough.


How do I reset Drupal Commerce orders, profiles, carts etc?

I don't recommend truncating database tables, because you also have to consider field data / revision tables - that can get nice and tricky if you've used the same field on entities that you want to delete and on those you want to keep. There also may be other contributed modules on the site that have stored data related to these entities. Without using the API to delete these entities properly, you'll end up with this stale data laying around that may or may not cause problems later.

If I had to do this I'd either do as the other answer recommended - go through each list and use the delete links - or in the case of large data sets, I'd add Views Bulk Operations to the Views so I could delete them en masse. VBO is one of Drupal's best kept secrets - great for automating routine tasks like this.

When deleting Commerce entities, I'd start with payment transactions then orders then products and customer profiles. You need to delete both complete orders and shopping cart orders, otherwise referenced products / customer profiles will not be deletable.


Preprocess title field in all contexts (sitewide)

I'm sure hook_node_view can do it for you, but you might need to call drupal_set_title on some situations.


Validate function not working in ajax form

You can try the following code.

$form['submit']['#validate'] = array('YOUR_VALIDATE_FUNCTION_NAME');


How to exclude nodes with matching field values using EntityFieldQuery

I believe you do need a subquery here. Apparently, you can actually do that with EntityFieldQuery. So first create your subquery, something like this:

$subquery = db_select('your_field_data_table', 't');
$subquery->addField('t', 'nid');
$subquery->condition('field_period_notifications', $period);

That gives you all nodes that have a matching value. Then add this to your EntityFieldQuery to exclude those:

->fieldCondition('field_period', 'nid', $subquery, 'NOT IN')

Or maybe you can do:

->entityCondition('entity_id', $subquery, 'NOT IN')


There is a core module namely 'Book' . Use that module to get desired structure of pages.

For more information visit here


Anonymous users getting same product items in cart

I would guess it has to do with:

$order = commerce_cart_order_load($uid);

Since all anonymous users are assigned uid:0, it could be drawing from all products currently associated with that uid (which would be all anonymous users), rather then the products from the current user's session


How to add a dynamic cart link to the user menu?

You can create a new menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module.

For example

function mymodule_menu() {
     $items['cart/new_menu_item'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'mymodule_new_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'mymodule_new_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}


View page as default page for content type

There are a couple of ways to do this.

One is to edit your node template file and field order so that the default node view is how you want it to look.

Another, if you prefer to create a view, is to do so and use a module like Internal Nodes or Page Manager (part of ctools) to redirect to the view.


A few things to check:

make sure there is no .htaccess rule that is preventing the download
(it may be inherited).
If using file entity check: /admin/config/media/file-settings and make sure .xls is allowed.
Could be blocked by server security like modsecurity rules, check the apache logs...


User can change `Moderation State` on content without having permissions to do so - Workbench

in order to display the moderation states i wanted for a specific role I had to make sure
Administer Workbench Moderation and Bypass Moderation restrictions were turned off.


The purpose of $page in node.tpl.php and when does it become FALSE?

That variable becomes false in:

template_preprocess_node

with

$variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);

See also:

node_view

For the view_mode parameter used there.

The output of the node $title is controlled by page.tpl.php for the full page node view.


/admin/* pages "The website encountered an unexpected error"

Just to get this marked off as answered (with thanks to Clive).

First of all was understanding how to make use of the database watchdog table to find the errors. You have to download and view the variables column... the error's in there. In my case it was that cURL was not installed.

It was as simple as installing cURL and restarting the Apache service.

apt-get install php5-curl

Thanks again to Clive!


Add VBO checkbox to send Bulk emails in Admin

This is how you do it:

Go to Structure > Views and locate the Test Event view.
Click the Edit button.
Find the Fields display and click the Add button.

Filter the available fields by Bulk Operations and select a field you need, e.g. Bulk Operations: User.

Now the settings for this field show up. Scroll down to Selected Bulk Operations and select Send Email.

Click Apply.
Don't forget to save your view.
Now you should have a checkbox and you can select Send Email from a drop down menu.

I'd personaly would not use the VBO field but the Views Send module which is a bit easier to use. If you have the Views Send module, add the field Global: Send Email instead of the VBO field and proceed as described above.


Rules to Flag a node referenced by Commerce Order Line Item

I believe you'll either need to access the node ID from the line item entity using a loop within the Rules UI or what I think a simpler way would be to create a custom Rule that accomplishes the same task.

Something like:
Event:  order is completed. I guess you could use order paid in full.
Conditions:  Here is where a custom condition would come into play.  You'd need to dig through the order line items to the user-selected node, and then pass that node_id to the Rules action as a parameter.  Note:  you could also do this entire check within the action and then programmatically set the flag to avoid passing the node_id as a parameter.
Actions:  Set a flag on a node.  (The node parameter).


You should never change code in Drupal core, change back to the original code in contact.module first.

When you have the Locale module enabled and have added your language (Configuration -> Regional and language -> Languages) you can translate strings. You will find the translate interface under Configuration -> Regional and language -> Translate interface.

Search for the English phrase first to find the string you want to translate (use exact spelling, it's case sensitive) and add your translation.


What theme function outputs the administrative overlay in D7?

To output the overlay, Drupal uses a template file, overlay.tpl.php. To use that template file, the Overlay module implements hook_page_alter(), which contains the following code:

  $mode = overlay_get_mode();
  if ($mode == 'child') {
    // Add the overlay wrapper before the html wrapper.
    array_unshift($page['#theme_wrappers'], 'overlay');
  }

The Overlay module has also a preprocess function for that template file: template_preprocess_overlay().


How to filter a view based on tags applied to

So, shortly after posting this question I worked out how to do it.

When I built this site I included the facility to create a Views relationship that points at the "referred to" user (the "patient" in the above example). So, I created this relationship in the view that I built. I then created another relationship that was itself based on the first relationship but pointing at the node created by the Content Profile module.

Then, I created a filter based on the second relationship, that filtered based on the taxonomy term I'd created (i.e., the "diabetic", "pregnant" stuff above). That did the trick.


Migrating specific nodes from Drupal 6 to Drupal 7

The easiest way I know is export your nodes from Drupal 6 by using Node Export . Then you can import your node to Drupal 7 by Feeds module. This has update and replace exsisting nodes options. Just make sure you set one of the source as an "Unique" on Mapping setting, like "uid" or "title" of the node. Hope this help


Checklist(s) for simplifying upgrades from Drupal 6 to 7 or higher in the future?

I have used the Upgrade status module on the past to better understand how much work will be involved in upgrading a site from a mayor version to the next.

Also, depending on how many modifications, or modules you have, it will also make the process easier.

One more tip: Check the Drupal documentation, and remember Youtube is your friend.


Custom Drupal field widget causing check_plain() error

According to the hook description, $items is an "Array of default values for this field."  You are trying to look in an array of arrays in your default value.

You need to change this line:

    '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',

to look in the $items array, rather than the $items[$delta] array (which doesn't exist) by removing ['value'], like this:

    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',


Can I rewrite a view's query SQL directly?

try hook_query_alter. Views queries should pass though this hook allowing you to alter them. https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_query_alter/7


Get view output without rendering (with substitutions)

There were several changes between these versions. If you check out Releases for Views you can see a list of changes for each version, and you can download each intervening version. I would suggest you peruse the list, and maybe roll back your current version, until you discover the specific change which broke your site. Then open an issue on the Views project page.


Conditionally run a view if another view has no results

When editing the view, under Advanced > No results behavior select Global: View area. Select the view you wish to show if the first has no result, and check if you want the replacement view to inherit the contextual filters of the first.


You may want to check if using the Views Date Format SQL module could be a solution. Here are some quotes about it (from its project page):

  ... allows to format date fields using SQL.

  The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

  The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.


Drupal pulls the number of comments per page from variable_get('comment_default_per_page' . $node->type).   Its default is 50.  To change this go to content type X -> edit, then save.

To change the 50 to something else, you can create you own custom module and have this code

function example_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'node_type_form' && isset($form['comment'])) {
        $form['comment']['comment_default_per_page']['#default_value'] = 70;
    }
}

If you want to change it somewhere else,  then I recommend calling variable_set('comment_default_per_page' . $node->type,  'MYVALUE').  See below where it is hard-coded
inside comment.module & comment_form:

$form['comment']['comment_default_per_page'] = array(
  '#type' => 'select',
  '#title' => t('Default comments per page'),
  '#default_value' => variable_get('comment_default_per_page_'. $form['#node_type']->type, 50),
  '#options' => _comment_per_page(),
  '#description' => t('Default number of comments for each page: more comments are distributed in several pages.'),
);

function _comment_get_display_setting($setting, $node) {
  global $user;

  if (isset($_GET[$setting])) {
    $value = $_GET[$setting];
  }
  else {
    // get the setting's site default
    switch ($setting) {
      case 'mode':
        $default = variable_get('comment_default_mode_'. $node->type, COMMENT_MODE_THREADED_EXPANDED);
        break;
      case 'sort':
        $default = variable_get('comment_default_order_'. $node->type, COMMENT_ORDER_NEWEST_FIRST);
        break;
      case 'comments_per_page':
        $default = variable_get('comment_default_per_page_'. $node->type, 50);
    }
...

and inside comment_render($node, $cid = 0) {

$comments_per_page = _comment_get_display_setting('comments_per_page', $node);


I wouldn't approach it this way. Hardcoding list items, with content, in a tpl.php is generally frowned upon and will ultimately require more work than this should entail.

Instead use Views and the Colorbox module. Create a view with the list of nodes you want to display, pop it in a block on the page in the region you'd like it to display, and use the Colorbox plugin to Views show the popover on click. Use CSS to style the colorbox however you please. This can be handled strictly with configuration and a touch of CSS. This way, when the theme changes someday, the functionality is maintained.

See http://drupal.org/project/views and http://drupal.org/project/colorbox for more details.


how to get the size and last modified date of file with fid

This is the code to get the size:

 $tid=$fileupload[0]['target_id'];
 $file = File::load($tid);
 $size = $file->getSize();


How to change the database drupal forms send to

I would try reading through How to connect to multiple databases within Drupal (notably, the Drupal 6 section towards the end.

Basically, in your settings.php file, convert the $db_url to an array, and add the secondary database:

e.g.

$db_url = 'mysql://drupal:drupal@localhost/drupal';

becomes

$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';
$db_url['db2'] = 'mysql://user:pass@localhost/db2';

Then create a submit handler that either compliments or overrides an existing form submit handler and use db_set_active to connect to the secondary database, save the data, and then switch back.

e.g.

function MYMODULE_MY_EXTRA_SUBMIT_HANDLER($form, &$form_state){
  // Switch to db2
  db_set_active('db2');

  // Do all your form processing and database transactions

  // Connect back to default Drupal database
  // *Note* If your primary db is keyed with "default", then you don't need to
  // pass an argument to db_set_active().
  db_set_active('default');
}


This is easily done with a little bit of theming. Based on the page being displayed, you can unset the $breadcrumb template variable to suppress output of the breadcrumbs on that particular page.

Pop a function like this simple example into YOUR_MODULE's template.php:

function YOUR_MODULE_preprocess_page(&$vars) {
  if ($_GET['q'] == 'general-chat') {
    unset($vars['breadcrumb']);
  }
}


Token does not return full dynamic path to Media Image URL

Would you believe:
node -> media field -> media entity -> image field -> image style -> url
Makes sense, right? (I mean, it makes sense if you understand core Media and Entity References.)
As a Token, it looks like this:
[node:field_hero_image:entity:field_media_image:large:url]
Not exactly intuitive, but it makes sense in hindsight. The Media field is an entity reference to a Media entity containing an Image field that can be rendered in a variety of Image styles, so the token chain goes all the way down that rabbit hole.
This approach generates a valid image URL in the header meta tags.
Of course, AddToAny is still not picking up the metadata when I share a Twitter card ... but that's a different issue!
Just pointing out to nobody in particular that this Token does not show up in the Node section of the "View available tokens" box. ¯\_(ツ)_/¯


Drupal 7 - Giving correct path to callback function in #autocomplete_path

You've just forgotten to define the path for the autocomplete itself:

function tdyards_searchbox_menu(){

  $items['tdyards/tdyards_searchbox'] = array(
    'title' => 'Autocomplete (simple)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('autocomplete_form'),
    'access arguments' => array('access user profiles'),
    );

  $items['tdyards/tdyards_searchbox/autocomplete'] = array(
    'title' => 'Autocomplete',
    'page callback' => 'tdyards_searchbox_autocomplete_callback',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}

Add that, clear the caches, and it should work.


Defined variables losing value after using drupal_bootstrap

When "register_globals" is enabled, Drupal unsets all global variables before boostrap.

Disable the "register_globals" option in your live server.


How do you build a query to get a series of nodes and their field values filtered by field values?

I second Jeremy's suggestion of trying harder with views. However, if you absolutely must write your query directly in code, you'll want to use EntityFieldQuery.

For example, to get a count of all nodes with a text field value of 'foo':

// Get field information
$field = field_info_field('field_name');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'NODE TYPE')
  ->fieldCondition($field, 'value', 'foo')
  ->count();

$count = $query->execute();

If you don't want a count, but results instead, you would leave off the count part, and fetch results:

foreach ($query->execute() as $entity_type => $entities) {
  foreach ($entities as $entity_id => $entity) {
  ...
  }
}

The Commerce Guys also have a good blog post detailing a simple use case.


Why is the 'values' array not set on an unsaved entity? Is there a way to make it get populated?

The code comments in ContentEntityBase say that $values always hold the original, unchanged values of the entity:

/**
 * The plain data values of the contained fields.
 *
 * This always holds the original, unchanged values of the entity. The values
 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
 * is used for values in default language.
 *
 * @todo: Add methods for getting original fields and for determining
 * changes.
 * @todo: Provide a better way for defining default values.
 *
 * @var array
 */
protected $values = [];

Quick glance through the code suggests that the public method updateOriginalValues() would do the trick:

/**
 * Updates the original values with the interim changes.
 */
public function updateOriginalValues() {
  if (!$this->fields) {
    return;
  }
  foreach ($this->getFieldDefinitions() as $name => $definition) {
    if (!$definition->isComputed() && !empty($this->fields[$name])) {
      foreach ($this->fields[$name] as $langcode => $item) {
        $item->filterEmptyItems();
        $this->values[$name][$langcode] = $item->getValue();
      }
    }
  }
}


You should not change the core function. What core does, if $rel is not set, it uses 'canonical'. If you want to use 'delete-form' instead, put this as an argument when using the link function:

$row['config_name'] = $entity->link(NULL, 'delete-form');

BTW, link() is deprecated, so use toLink() instead.


How to set the default theme programmatically

The current advice is to set this via config:

\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', $theme)
  ->save();

The previous method using ThemeHandlerInterface::setDefault() is now deprecated.

You might need to install it first too, I'm not sure. In case you do:

\Drupal::service('theme_installer')->install(['test_theme']);


Does anyone know solution for adding pure javascript filter for View?

I'ld suggest you choose views format Table and then add your JS from hook_page_build().


What is the order of return value for field_info_instances?

This is the query run by field_read_instances():

$query = db_select('field_config_instance', 'fci', array('fetch' => PDO::FETCH_ASSOC));

$query->join('field_config', 'fc', 'fc.id = fci.field_id');
$query->fields('fci');

// Turn the conditions into a query.
foreach ($params as $key => $value) {
  $query->condition('fci.' . $key, $value);
}
if (!$include_inactive) {
  $query->condition('fc.active', 1)->condition('fc.storage_active', 1);
}
if (!$include_deleted) {
  $query->condition('fc.deleted', 0);
  $query->condition('fci.deleted', 0);
}

$instances = array();
$results = $query->execute();

So it's safe to say there's no default order for field instances; they'll be in whatever order they went into the database, or perhaps different depending on your DBMS and settings.


How to run entity field query in cron without getting undefined stdClass::$roles notice?

As you can see in the cron doc, cron runs as anonymous user so you have to run the query as admin user.

In the EntityFieldQuery DO doc you can see examples, but essentially you just need to add the addMetaData code to the end  of your query:

 $q = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $content_types, 'IN')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $uid)
    ->propertyCondition('type', $content_types, 'IN')
    ->fieldCondition('field_something', 'value', $code, '=')
    // Run the query as user 1.
    ->addMetaData('account', user_load(1));


This is just a suggestion, its not well designed solution.

Considering that you already added your field to a Node type and you need update its value...

You can create a function that loads all nodes with specific type:

$articles = \Drupal::entityManager()->getStorage('node')->loadByProperties(array('type' => 'article'));;

And use a foreach to update your field content:

foreach ($articles as $nid => $article) {
  //Change what you need
  //Save your changes
}

Now, just run this once, on a new module install function or whatever you want.


You may want to use hook_views_pre_execute (see example) or hook_views_post_render() where you can add arbitrarily content (new rows or html code) into the view to fake the nodes.

Please check the following code example to give you some idea.

You may also compare how other Views-based modules doing non-database query results, such as Search API Views or YQL Views Query Backend.


How can I override the autocomplete.js file while developing a module?

As long as all you want to do is achievable by using form_alter() and #autocomplete_path, you should avoid modifying core's JavaScript files. To address specific field widget, use hook_field_widget_alter().

If you need to alter what JavaScript is doing, use corresponding behaviours, as described on StackOverflow.


What about using entity references. You mention the field-collection approach, which has the same overhead as using entity references.

Basically you create a few node types that each conform to a different block element that you require. Then you create a master node with an entity reference field and select all of your block element node types as candidates, and set the filed count to unlimited. Then also use the inline entity form.

This will work but has a heavy server load.


How to change the output of a theme function?

To override the output of a theme function in a theme, you simply take the name of your theme, and the name of the theme function, and join them together with an underscore.

So for your example, the function would be called:

function MYTHEME_links__system_main_menu($variables) {
  $html = '<ul>';

  // Loop over links

  $html .= '</ul>';

  return $html;
}

Your function should return the HTML string that you want to be rendered when this theme is used, any variables that have been passed to the theme() function will be available to you in $variables.

Usually it's enough to look at the original theme function to find out what's available to build your HTML, but sometimes you'll need to get the Devel module installed and inspect vars with dpm to properly see what's going on.


How to provide ubercart discount coupons only for specific users

What you are looking for is a custom hook_uc_validate_coupon function. Ubercart coupon module allows for custom hooks here:

// Invoke validation hook.
  foreach (module_implements('uc_coupon_validate') as $module) {
    $callback = $module . '_uc_coupon_validate';
    $result = $callback($coupon, $order, $account);

So in your site module you would need to define a new hook function that validates whether the order (or possibly the user object?) is using a billing address from Texas. Roughly, clone the existing validation function and add logic to check the order for your conditions.

function YOURMODULE_uc_coupon_validate($code, $order = NULL, $account = NULL) {

if ($order->billing_state != 'Texas') { // or however you want to handle this
   $coupon = new stdClass();
   $coupon->valid = FALSE;
   $coupon->message = t('This coupon code is only valid in Texas.');
   $coupon->title = t('Unknown');
   return $coupon;
}

.. rest of validation function

}


Adding missing Input Formats after Minimal Install

If you want to set them up exactly as they were in the default installation profile, you can just copy the code from /profiles/standard/standard.install and run it somewhere (e.g. at /devel/php with the Devel module installed):

// Add text formats.
$filtered_html_format = array(
  'format' => 'filtered_html',
  'name' => 'Filtered HTML',
  'weight' => 0,
  'filters' => array(
    // URL filter.
    'filter_url' => array(
      'weight' => 0,
      'status' => 1,
    ),
    // HTML filter.
    'filter_html' => array(
      'weight' => 1,
      'status' => 1,
    ),
    // Line break filter.
    'filter_autop' => array(
      'weight' => 2,
      'status' => 1,
    ),
    // HTML corrector filter.
    'filter_htmlcorrector' => array(
      'weight' => 10,
      'status' => 1,
    ),
  ),
);
$filtered_html_format = (object) $filtered_html_format;
filter_format_save($filtered_html_format);

$full_html_format = array(
  'format' => 'full_html',
  'name' => 'Full HTML',
  'weight' => 1,
  'filters' => array(
    // URL filter.
    'filter_url' => array(
      'weight' => 0,
      'status' => 1,
    ),
    // Line break filter.
    'filter_autop' => array(
      'weight' => 1,
      'status' => 1,
    ),
    // HTML corrector filter.
    'filter_htmlcorrector' => array(
      'weight' => 10,
      'status' => 1,
    ),
  ),
);
$full_html_format = (object) $full_html_format;
filter_format_save($full_html_format);


Remove inline JS from specific page type?

Put this inside tlito_theme_js_alter().

foreach ($js as $key => $value) {
  // Skip if data is not a string or is not inline.
  if (!is_string($value['data']) || $value['type'] !== 'inline') {
    continue;
  }
  // Remove SyntaxHighlighter.defaults.toolbar inline js.
  if (strpos($value['data'], 'SyntaxHighlighter.defaults.toolbar') !== FALSE) {
    // Remove from the js array & exit loop.
    unset($js[$key]);
    break;
  }
}


What is the best way to theme page--front with twitter bootstrap?

You might want to switch the theme entirely. You could simply use something like: https://www.drupal.org/project/themekey

Regarding the regcognition of page--front.tpl.php,
rename your existing page.tlp.php to page--default.tpl.php


Create a custom module, for example:

MODULENAME.install file with hook_schema() implementation:

<?php

/**
 * Implements hook_schema()
 */
function MODULENAME_schema() {
  $schema['MODULENAME'] = array(
    'description' => 'Description of the table.',
    'fields' => array(
      'timestamp' => array(
        'description' => 'Timestamp of the rquest.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      // definitions for the rest of fields here
    ),
    'indexes' => array(
      // define indexes
    ),
    'primary key' => array('NAME_OF_PRIMARY_KEY_FIELD'),
  );
  return $schema;
}

?>

MODULENAME.module file with hook_menu() implementation:

/**
 * Implements hook_menu()
 */
function MODULENAME_menu() {
  $items['page-name'] = array(
    'title' => 'Example title',
    'access callback' => TRUE, // imply no restrictions
    'type' => MENU_CALLBACK,
    'page callback' => 'MODULENAME_pagename_view',
  );
  return $items;
}

function MODULENAME_pagename_view() {
  global $user;
  // insert into Drupal database
  db_insert('MODULENAME')
    ->fields(array(
      'timestamp' => REQUEST_TIME,
      'user_id' => $user->uid,
      'url' => $_GET['url'],
      'redirect' => $_GET['redirect'],
      'uid2' => $_GET['uid2'],
    ))
    ->execute();
}

?>


Drupal not sending emails from contact form

There could be many reasons but here are a few things to check.

Check your logs. Watchdog may tell you the source of the error. For D7, it's at /admin/reports/dblog
Test other mail functions like the reset password link.
Make sure you have a valid email address set: The site email address (used when sending notification emails, and the default for most all modules that send emails) can be set via the Site Configuration > Site information page (admin/settings/site-information).
Check your permissions if you are sending email from a module like webforms.
If you have SSH access to your server, test the mail settings from there.

<?php
    $to = "your@email.com"; // REPLACE
    $subject = "Test mail";
    $message = "Hello! This is a simple email message.";
    $from = "noreply@eample.com";
    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
    echo "Mail Sent.";
Make sure to replace the "to" address, save it as mail.php, and run it using "php mail.php". If you get email from that, then the problem is specific to Drupal, and if not, then your server isn't sending email at all and you should contact your host.

See more at: http://drupalconnect.com/blog/how-debug-drupal-not-sending-email#sthash.Jkxx7ui6.dpuf


check other commerce pane validation error

check errors before call your function

function hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
if (!(form_get_errors()){
 do_update_something($user);
}

}


How do I set a Boolean field with "yes" and "no" values?

The Boolean field accept only 0 and 1 as value.
if you want to add allowed values by PHP Code should be:

0|No
1|Yes

I create a Boolean field on Content type and i set the On value to Yes and
 off Value to No.
As you see In the below screenshot the value of input is 0 for NO and 1 for Yes.


The only workable solution that I've come up with sits in a feature request in that module's issue queue; I haven't had a chance to try it out yet. Basically, I believe you can use a field on the product type as an options mask for the same field on the line item type. When a field is present on a line item type and shown on the Add to Cart form, its options will typically default to whatever is in the field settings. However, if you put that same field on the product type as a multi-value field, you could then use a form alter of the Add to Cart form to only show the options on the Add to Cart form that were selected for the product.

Again, this is just an idea - not implemented yet. But it seems like a very feasible way to accomplish what you want (and it's based on some architecture I actually helped a community member implement during a cocktail reception at DrupalCon Munich ; ).


Which module can create a sitemap based on entity reference rather than menus?

With the XML Sitemap module, the main alternate to menu-based sitemaps, is the XML Sitemap Node submodule.

Enable the sub-module, then edit each content type.  There should be an XML Sitemap tab at the bottom of the form.  Set the inclusion and priority as needed.  An advantage of this, over using menu-based sitemaps, is that modified times will end up in sitemap.xml


Create single exposed filter that does OR filter based on two fields D7 - Views 3

Views 3 views have a neat little semi-hidden feature. Click the arrow on the add button in the Filters section and pick and/or. From here, you can create filter groups and sort your filters to use AND or OR depending on your needs. Play with it; I think you'll be able to solve your issues like this.


how to post an article by jquery using REST service of Drupal?

You need to enclose your javascript

(function ($, Drupal) {

  ...

})(jQuery, Drupal);

to access Drupal and the usual $ for jQuery.


How to exclude a node from being indexed based on a field value?

As said in the API, using hook_search_api_index_items_alter is not the best choice.
You should use hook_search_api_alter_callback_info

Example :

function mymodule_search_api_alter_callback_info() {
  $callbacks['exclude_some_nodes'] = array(
    'name' => t('Exclude some nodes'),
    'description' => t('Exclude some nodes from being indexed based on one field value'),
    'class' => 'SearchApiExcludeSomeNodes',
  );
  return $callbacks;
}

class SearchApiExcludeSomeNodes extends SearchApiAbstractAlterCallback {

  public function supportsIndex(SearchApiIndex $index) {
    return $index->getEntityType() === 'node';
  }

  public function alterItems(array &$items) {
    foreach ($items as $k => $item) {
      if($item->field_your_field['und'][0]['value'] == 'do_not_index') {
        unset($items[$k]);
      }
    }
  }

}

This will appear as an option in the UI of Search API, in the Data alterations section (admin/config/search/search_api/index/your_index/workflow)


How do I use Features to export a custom content type to a stand-alone module

The features eco-system simply implements certain hook functions (like hook_field_info for example). It wraps these core api functions with import/export code.

When you export your content type using Features you can inspect what it creates -- besides a mymodule.install and mymodule.module files.

By examining the hooks the features implements for your exported content type -- there is nothing stopping you from copying/renaming these exported function definitions and migrating them to a new module's hook_install() function. Thus, creating a new content type which you used Features to create the building block(s).


How to display custom data array via Twig

Have you added 'front_page_slider to the variables array in your twig template definition?

File...module_name.module

function hook_theme(array $existing, $type, $theme, $path) {
  return [
    'template_name' => [
          'variables' => [
           'front_page_slider' => [],
      ],
    ],
  ];
}


Ok well I seem to have "solved" the issue.

I had a node with the following PHP code to take the user to their order page when accessing user/me/orders:

<?php
  global $user;
  $orderpath = 'user/'.$user->uid.'/orders';
  drupal_goto($orderpath);
?>

When I deleted that PHP code, everything started working again.

Anyone know why the above code could cause the problems indicated in my question?


Webform adding custom component or modify radio buttons

You should be able to do this with CSS alone.


how to redirect to another site but still have same url

You should be able to do that relatively easily with full HTML mode using an <iframe src='desiredurl'></iframe>. You will most likely want to do some custom styling/template editing to make it look good.

Whether that is a good soluton for you depends a bit on how you want it to look etc. Do note taht security restrictions can break it - and make custom scripting/styling problematic as well inside the iframe. I'd suggest reading the Mozilla Dev Network's iframe page.


How do I alter the HTML outputted by an exposed filter?

Turns out these settings can't be changed in the View (that I was able to find, and I looked pretty extensively). But, with Drupal's module/hook system, it's a pretty quick fix.

Source: How to remove format description in date_popup form field?

First, get rid of Start date and replace End date with And to match the filter on the left:

function edit_date_form_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] === "views-exposed-form-editable-content-page") {
    $form["field_editor_review_date_value_1"]["min"]["#title"] = "";
    $form["field_editor_review_date_value_1"]["max"]["#title"] = "And";
  }
}

Then, get rid of the E.g., 2017-02-01:

function edit_date_form_date_popup_process_alter(&$element, &$form_state, $context) {
  $element['date']['#description'] = "";
  $element['time']['#description'] = "";
}

Plop those into a module, enable it, and your output is:


how to hide a field when adding content through node/add for a content type?

The way I prefer is to use Computed Field module. Not only it creates a field that's not editable for users, it also takes care about hooks, cache, and lets you simply choose recalculation strategy (on save / on display). All you really need to care with it, is the very code that calculates field's value.


Page callback should be drupal_get_form in your hook_menu and form definition handler should be passed as argument.

$items['gift_cards'] = array(
   'title' => 'SELECT A CARD',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('uc_gift_certificate_order_page'),
   'access callback' => 'user_access', // no need to define in case of user_access
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK,
);


Actually the submit handler name should be the form function name with _submit.

So in this case: my_form() returns the form, and my_form_submit($form, &$form_state) is automatically the submit handler. This also works for _validate.

See the Examples project for some working code. It has a submodule called form_example.


Views: Create a block with terms marked (reference field) by the term viewing

2 steps are needed to achieve this with Views:

Relationship:

Add a relationship
1st screen on the popup: Choose Taxonomy term: Styles
2nd Screen on the popup: Choose Require this relationship
Apply

Contextual Filter:

Add a contextual filter
1st screen on the popup: Choose Taxonomy term: Term ID
On the Relationship dropdown choose the relationship you configured above
Choose When the filter value is not available -> Provide default value -> Type dropdown = Taxonomy term ID from URL
Apply

And you're done.


How to write paragraph template to add tags and css classes?

Have a look here for the naming

  The default paragraphs template is in paragraphs-item.tpl.php. It uses
  theme suggestions for other templates, the following suggestions are
  available:

  paragraphs__[view_mode] (e.g. paragraphs--default.tpl.php)
  paragraphs__[type] (e.g. paragraphs--image.tpl.php)
  paragraphs__[type]__[view_mode] (e.g. paragraphs--image--default.tpl.php)

As this seems to be wrong .. Try the suggestion:

paragraphs-items--pr_bg_font_clr.tpl.php
paragraphs-item--pr_bg_font_clr.tpl.php


Module (or code) to display character count?

The Maxlength module has that functionality baked right in:

Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node)
When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation.

It works great for textfields and textareas alike. This is (roughly) what a textarea looks like after Maxlength is applied:


Access denied page for users without permission "View published content"

You can try Custom error module, It allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.


My prefered solution to scrub out extraneous characters in Pathauto URLs is this option under Configuration » Search and metadata » URL aliases » Settings.

It will scrub out all the extraneous characters that can mess up browsers/crawlers. This is assuming you're on an English language website.


How can I schedule in advance an update to a node, to occur at a given time?

This could be done with a Rules Schedule:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

specifically this functionality: Flexible scheduling system that allows scheduling any component / action.


How to integrate Views with apache solr search?

The module you want is the aptly named Apache Solr Views which will allow you to construct views from the SOLR index. Configuration is pretty simple. It's kind of a drop-in module. You'll choose to create an "Apache SOLR view". From the project page:

  Create a view from admin/structure/views/add and choose Apachesolr search. All of the fields indexed in solr should be available as views fields/filters/sort. Configure the view as needed and save it

Hope that helps you. Good luck!


Get a notification if a new version (tag) is created

Not directly through Github, but check https://sibbell.com

It's notifies you of new Github releases.


how do you alter queries for node/# to select entity-referenced node titles instead of just target_id?

I believe @Clive was going in this direction here, but I wasn't clear that the Services does in fact invoke Hook_node_load($nodes, $types) when using the retrieve methods at services/node/#. I suppose I was avoiding the node_load_multiple because they are so heavy for only the few fields I want. Code is below

function HOOK_node_load($nodes, $types){
    if (in_array('yournodetype', $types)) {
        foreach($nodes as &$node) {
            $f = field_get_items('node', $node, 'field_your_reference_field');
            if (!empty($f) && isset($f[0]['target_id'])) {
                $refNode = _mymodule_reference_load($f[0]['target_id']); // this function simply writes a manual SQL query for my title and iata values.
                $node->field_your_reference_field[LANGUAGE_NONE][0]['title'] = $refNode->title;
                $node->field_your_reference_field[LANGUAGE_NONE][0]['iata'] = $refNode->field_iata[LANGUAGE_NONE][0]['value'];
            }
        }
    }
}

function _mymodule_reference_load($nid){
    $refNode = db_query(sprintf("SELECT N.nid, N.type, N.title, A.field_iata_value, R1.field_readmore1_value, R2.field_readmore2_value
                FROM node N
                LEFT JOIN field_data_field_iata A ON N.nid = A.entity_id
                LEFT JOIN field_data_field_readmore1 R1 ON N.nid = R1.entity_id
                LEFT JOIN field_data_field_readmore2 R2 ON N.nid = R2.entity_id
                AND A.deleted =  '0'
                AND R1.deleted =  '0'
                AND R2.deleted =  '0'
                WHERE N.nid =  '%s'", $nid))->fetchObject();
    $refNode->field_iata = array('und' => array(0 => array('value' => $refNode->field_iata_value))); // maintain same structure as node_load
    $refNode->field_readmore1 = array('und' => array(0 => array('value' => $refNode->field_readmore1_value)));
    $refNode->field_readmore2 = array('und' => array(0 => array('value' => $refNode->field_readmore2_value)));
    unset($refNode->field_iata_value);
    unset($refNode->field_readmore1_value);
    unset($refNode->field_readmore2_value);
    return $refNode;
}


http://webwash.net/tutorials/import-and-export-menus-menu-import-module-drupal-7 shows how to use http://drupal.org/project/menu_import which uses path aliases instead of UUID.

I think this would work.


Updating to PHP 5.4 breaks Drupal 7.25 with Strict warning: Declaration on bootstrap.inc

These aren't critical errors right?

No, it's just a warning. Not fatal. It comes from the E_STRICT error constant, which as of PHP5.4 was included in E_ALL. It's quite common to see those errors after upgrading 5.3 to 5.4 (not just for Drupal), as most people copy the bulk of their config from the previous version.

The constant itself provides this to error reporting:

  Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

  What do the following errors mean exactly?

In Drupal terms, it means one or more contrib modules you have installed contain code that targets older version of PHP (or at least hasn't been updated recently). Specifically, PHP is complaining that the arguments or access modification of a method on a child class doesn't match the same method on the parent class.

  Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?

In your case the warning is being caused by the messaging_mail module, so updating core won't do anything (though you should update ASAP, you're a long way behind). You could disable strict errors if you just want to hide the warning, but the best way forward is to report this as a bug to the appropriate module.


How to reset 'new' and 'updated' flags without visiting a node page?

You can use node_tag_new() for that

  Updates the 'last viewed' timestamp of the specified node for current user.

e.g.

node_tag_new($node);


How can I have conditional content within page body that is dependent upon the domain?

The sites module has support for multiple domains and managing content across those domains.

https://www.drupal.org/project/sites

If you are using the same template file for the page where you are displaying your content, then you can implement the 'hook_site_access()' from the sites module in the template file, and gather the content you desire to display based on the domain name.

In addition, depending on the type of content you are displaying, you might be able to get away with simply using the Views or Context integration from the Sites module, rather than editing your template file manually.

Another option is to use Drupal's taxonomies to classify your content. Then, you could use any of the solutions above (custom code in page template, Views, or Context) to filter only the content which is categorized to be displayed on the domain you are on.

In any case, if you want two different versions of the same page to display on different domains, you will need two different nodes, and they will need to be classified accordingly. I'm not sure if there is any way around maintaining multiple nodes if the content varies by domain.

However, when the same node is to be displayed on multiple domains, this kind of architecture will allow you to display it only on a specific subset of domains you choose.


How can I add a way to jump months using the calendar module

Add Below code for your calendar. Click This link for example

$(function () {
  $("#datepicker").datepicker({
    changeMonth: true,
    changeYear: true
 });
});


How to use URL-based AJAX in Drupal 7 to serve all pages?

I'm searching also a solution to do that. I would like to allow users to choose witch content type is displaying in a region.

I started by create one block by region and inside I put different functions like the following one to get different content.

node_view_multiple(array($node->nid => $node), $display_type); // To get a node.
module_invoke($module, 'block_view',$delta); // To get a block.
panels_mini_block_view($minipanel_name); // To get a mini panel.

Now, with the CSS ID of the block, I will try to refresh them using AJAX link.
I think I will have to override all the links of Drupal to somethings like main/nojs/#div_region_id/[drupal-url] (e.g. main/nojs/block-content/node/1) and add them a class="use-ajax".

The management what is refresh will be in ajax_callback_response().

$commands[] = ajax_command_html('#block-content', $output );
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

Another way may be also with the Content page module.


How to hide drupal error message - one or more problems were detected with your drupal installation

You could check the status report and try to resolve the error but I guess you are happy to leave it that way.

Or you could hide the message by selecting the class and choosing not to display it using CSS.
Create a file called style.css in your "Theme" folder (alongside the location of page.tpl.php) and place the class within it (you can check the class by using Firebug/Inspector "right click on it, then inspect element").

I think the class will be .warning or .alert, and an example CSS code would be:

div.warning, .alert, div.error, tr.error
{
display:none;
}

This would however hide all alerts and warnings for elements with the same class.  So be careful because you could miss other critical notifications.  You could have a style sheet for non-admin users that would turn this off and another for admin areas that would display these messages.  Its your choice.


Best way to set up attributes/variations

I'll preface this by saying that every situation is different so it's hard to say what the "best" option is. This tutorial seems to go the route of having different product variation types, with a specific color attribute created per variation type. Having a separate variation type for every item feels a bit awkward, but it might make sense in your scenario.
Two other solutions that I can think of are:
1. Multiple Attributes (only):
You could do this without creating unique product types for every product, or even multiple product variation types. You could have 5, 10, 2000, however many different color attributes, all of which are made available to your single product variation type.
The main drawback that I foresee with having separate attributes for each color set is that, after the fact, any grouping/reporting that needs to be done on colors may need to accommodate all of these disparate attributes in a single place. One way to help mitigate this might be to create an "attribute categories" (or similar) taxonomy vocabulary to group related attributes together, and tag that on a taxonomy ref field on each attribute. If you anticipate this only ever being an issue for "colors" then you could probably also get away with adding a boolean field to do something similar.
That said, having the color sets as separate attributes might be preferred for reporting as well. Hard to say.
2. One Attribute
Another option is to have a single Color attribute containing every single color, but add a Product Entity Reference field onto it. In this case, every color would inherently be treated the same, but you could relate them directly to their associated Products. This avoids the issue of needing to relate the different attributes after the fact. This would give you the option to do a form_alter on the product_variation creation form to limit the options on the color attribute field to those which reference the Product that you're creating a variation of.
This option could end up with a pretty big list of options when editing the attribute, though, so it might be worth populating it with a bunch of dummy data to see how it fares. Devel_generate (included with Devel module) might be helpful, here.
EDIT: I should note that I initially failed to say that option 2 was my preferred option, for the same reason that Ryan notes in his answer. That is to say, all colors are colors and should be present on the same attribute. If Select2 is viable for attributes fields then that's probably the simplest way to make the list more manageable when authoring new product variations.
Alternatively, as mentioned in 2, using a reference field on each color to its related products (or alternatively a reference field on the product to its given colors) would maintain the "correct" single attribute while also allowing you to limit the options to those appropriate for the current product. IMO this probably leads to a less overwhelming interface in the event that the list of available colors is sufficiently large, and could also be paired with something like Select2 to further improve the authoring UI/UX.


migrating from localhost to server - What to do with the folder sites/localhost.mysitename?

I don't know the acquia product you are using. And I don't know bluehost - but it seems to be a "usual webhoster". I assume at bluehost is an ordinary LAMP stack running without any drupal-specific modifications.

update 2 after comments of EB84:

It turns out you are not using multi-sites. Seems to me as you made your setup more difficult than it needs to be:

Just replace the default folder with your localhost.mysitename folder. By doing so you revert your folder-structure back to a simple single-site setup.

Keep in mind, that you need to adopt your settings.php to the preferences of your bluehost webspace (database parameters, etc.). Your settings.php will look different on the server than on your local machine - all other files and directories may be the same.

update 1 after comment of EB84:

Since you are using a multi-site setup the configuration in sites/sites.php will control which site will be used for what domain names in HTTP requests.

Please read following documents:

https://api.drupal.org/api/drupal/sites!example.sites.php/7
https://drupal.org/documentation/install/multi-site

You will read that the directory names are arbitrary - as long as you map the domain name of the HTTP requests to it (via the configuration in sites.php).

Anyhow it might be good to remove the term "localhost" from your directory name - not for the whole thing to run technically, but to not confuse yourself some when in future.


Results page template of Search API module

Search API filters and results are displayed using views - so you need to override the views template.

So if you create a view page for your search called "Search API" (search_api) - and the machine name of that view is page - then you can add the following file to your theme:

my_theme/templates/views-view--search-api--page.html.twig

You probably want to start by copying in the contents of core/modules/views/templates/views-view.html.twig into the above template file and start tweaking it from there.

For help creating the actual view you may find these links helpful:

https://www.drupal.org/docs/8/modules/search-api/getting-started/search-forms-and-results-pages/searching-with-views-0
https://sweethoneycode.com/custom-search-with-search-api-and-views-drupal-8/


Menu endpoint hangs when access callback returns false

To return 403 Forbidden in your callback function, use drupal_access_denied() function something like:

function user_is_api_user() {
  watchdog("GLOBALS", "<pre>" . print_r($GLOBALS['user'], TRUE) . "</pre>");
  if ($GLOBALS['user']->name !== 'api'){
    drupal_access_denied();
  }
}


Make global results header in a view appear below exposed filters

You could create a custom block and execute php. Something like this:

$view = views_get_view('my_view');
// get global header
$view->execute();
$objects = $view->result;


From a custom module. How can I get the typed value from a textfield and put it in a variable?

All entered values are in the $form_state array on submit. It is up to you to process that data and store it in a variable.

For example...

function mymodule_myform_submit($form, $form_state) {
  $text = $form_state['values']['myfield'];
  variable_set('mymodule_var', $text);
}

Then wherever else in the site you want to show it...

$myvar = variable_get('mymodule_var', '');

Of course, be sure to validate your input in the validate handler and anything else you want to process and save. This is pretty much the most basic approach in 7 to collect and store variables (especially not knowing the rest of your setup).


You want db_or().

$or = db_or()->condition('n.title', '%' . db_like('second') . '%', 'LIKE')->condition('n.title', '%' . db_like('title') . '%', 'LIKE');
$results = db_select('node', 'n')
  ->fields('n')
  ->condition($or)
  ->execute()
  ->fetchAll();


I believe what you see is normal. In any case, having the WYSIWYG editor for Plain text would result in that the output would display the HTML source code. Using the WYSIWYG editor for PHP input format would probably reformat and destroy the PHP code.


How to specify a background image in a view so that it doesn't get removed?

To understand why this (= the style being removed) is happening, refer to this comment in the views issue queue:

  Rewrite uses filter_xss_admin and allows only the tags listed there.

It also includes a possible solution for it, which is like so:

  If you need more than this, then you need to use a template where you have complete control. This ensures that data entered via the UI is safe.

For an alternative solution (instead of using a template), you may want to consider the Background Images Formatter module. Here is an excerpt from its project page:

  This module provides an image formatter who allows you to set an image in background of a div. The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.


Add content to a render array in a content type from my custom module

hook_node_view() was made for exactly that:

  Act on a node that is being assembled before rendering.

e.g.

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_type' && $view_mode == 'full') {
    if (in_array($node->nid, $_SESSION['viewed_videos'])) {
      $node->content['viewed'] = array(
        '#markup' => t('You have viewed this video'),
        '#weight' => 10,
      );
    }
  }
}


creating custom panes for field data in drupal 7

Got his one. We need to replace content_fields with entity_+fields in drupal 7 as the content types are entity type in drupal 7 now.

Thanks


Role based exposed filter is not showing anonymous and authenticated roles there. Can anyone tell me any method to add that roles?

That's because they are not really real roles, more just a group of users.

What I mean by this is that the relationship between users and roles is stored in the table users_roles. There is one field for uid (the users ID), and one field for rid (the role ID).

So, the admin user has a uid of 1 and also has the administrator role with an rid of 3, so there is an entry in the users_roles table like: 1 | 3.

Any other roles created and assigned will also have rows inserted into this table.

However when the admin user logs into the site there is not a row inserted into users_roles table for the "authenticated user" role. And likewise when they log out a row is not inserted for the "anonymous user" role.

The actual query used by views would be something like this:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, node.uid, ur.rid
FROM node node
LEFT JOIN users users_node ON node.uid = users_node.uid
INNER JOIN users_roles ur ON users_node.uid = ur.uid
WHERE node.`status` = '1' AND node.type IN  ('article') AND ur.rid = '3'
ORDER BY node_created DESC

Here it is joining onto the users_roles table, but we know that the roles "anonymous user" and "authenticated user" don't have entries in the users_role table so it won't work.

So whilst it is possible to add these 2 roles into the select, the query that runs won't ever return anything.


how to create the pagination for customized portfolio template

First things first, that code shouldn't be in the template file; it should be in a preprocess function. The reasons for this have been documented at great length both on this site and the internet in general so I won't go into them here.

You might also find the l() function interesting, as well as theme_image()...API replacements for the custom HTML you're building up.

Other than that, the only thing you're missing is the code to actually render the pager; that would entail adding this to your preprocess function, after the query has been run:

$vars['pager'] = theme('pager');

And in the template file simply outputting it wherever you'd like it:

<?php echo $pager; ?>


Is it possible to give to a specific user role the permission to create content only in a language?

Create a custom module for this. I'm including some code that may help get you started. The idea behind this code (below) is preventing a user without the role 'admin_de' from editing content that has a different language than what the 'admin_de' user has set for their account. So there are some obvious differences, but this should be a good start.

In MY_MODULE.info.yml:

name: MY_MODULE
type: module
description: Allows user with particular role to edit content of particular
language.
core: 8.x

In a file called MY_MODULE.permissions.yml, include:

edit same language:
  title: 'Edit Same Language Only'
  description: 'Allow user to edit only nodes matching their account language'

In a file called MY_MODULE.module, include:

<?php

use \Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityForm;

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $currentUser = Drupal::currentUser();
  $roles = $currentUser->getRoles();

  if (in_array('admin_de', $roles)) {
    switch ($form_id) {
      case 'node_CONTENT_TYPE_edit_form':
        $currentUserLanguages = getUserLanguage($currentUser->id());
        $submissionLanguage = getSubmissionLanguage($form_state);
        $status = (Drupal::currentUser()
        ->hasPermission('edit same language') && ($submissionLanguage == $currentUserLanguages));
        if (!$status) {
          throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
        }
        break;
    }
  }
}

/**
 * @param $userId
 * logged in user id
 *
 * @return string of language id logged in user is associated with.
 */
function getUserLanguage($userId) {
  $user = \Drupal\user\Entity\User::load($userId);
  $languageId = $user->language()->getId();

  return $languageId;
}

/**
 * @param FormStateInterface $form_state
 *
 * @return string language id of page
 */
function getSubmissionLanguage(FormStateInterface $form_state) {
  $language = '';
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof EntityForm) {
    $entity = $form_object->getEntity();
    $language = $entity->langcode->value;
  }

  return $language;
}

Hope this helps!


AJAX callback on form item generated by AJAX

The Link 4k4 posted in the discussion of the question gives the solution:

  Create a callback function (named by the #ajax['callback']). This is generally a very simple function which does nothing but select and return the portion of the form that is to be replaced on the original page. Note, that as part of the Form APIs security system, you cannot create new form elements in the callback function, as they will throw errors upon submission, and any #ajax on elements created in the callback will also not work. If you need to create new elements on ajax submit, they must be added in the form definition. You can use the values in $form_state to determine whether the form build process is the initial form load, or an #ajax initiated load.

So the following code example is working.

class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['month'] = [
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => [
        $this->t('January'),
        $this->t('February'),
        $this->t('March'),
      ],
      '#ajax' => [
        'callback' => [$this, 'extraField'],
        'event' => 'change',
        'wrapper' => 'week-day',
      ],
    ];

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];

    if ($form_state->getUserInput()['_triggering_element_name'] == 'month') {
      $month = $form_state->getValue('month');
      $hour_options = [];

      if ($month == '0') {
        $hour_options[0] = $this->t('08:00');
        $hour_options[1] = $this->t('09:00');
        $hour_options[2] = $this->t('10:00');
      }

      if ($month == '1') {
        $hour_options[0] = $this->t('12:00');
        $hour_options[1] = $this->t('13:00');
        $hour_options[2] = $this->t('14:00');
      }

      if ($month == '2') {
        $hour_options[0] = $this->t('18:00');
        $hour_options[1] = $this->t('19:00');
        $hour_options[2] = $this->t('20:00');
      }

      $form['week_day']['hour'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose hours @month', ['@month' => $month]),
        '#options' => $hour_options,
        '#ajax' => [
          'callback' => [$this, 'choosePerson'],
          'event' => 'change',
          'wrapper' => 'person-container',
        ],
      ];

      $form['week_day']['person_container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'person-container'],
      ];

      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['John', 'Sarah', 'Peter'],
      ];
    }

    if ($form_state->getUserInput()['_triggering_element_name'] == 'hour') {
      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['Hans', 'Frank', 'Emma'],
      ];
    }

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

  public function extraField(array &$form, FormStateInterface $form_state) {
    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    return $form['week_day']['person_container'];
  }

}


Export Webform submission data into external database

Usually the first step to solving a problem like this in Drupal is finding the right hook.

A quick google search for "webform hooks", and then we pick the hook where we'd have access to the completed webform's data: http://api.lullabot.com/hook_webform_submission_insert/7

The example on that page happens to be exactly what you want to do!


How to definitely stop inside a Rule and prevent any further actions in the rule from executing?

This seems like a perfect use case the Conditional Rules module. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Using this module, there is no need for "PHP inside the first component" (as in your question.

Refer to my answer to "How to prevent a node being saved when using the Rules module?" for an illustration of how to use this module.


You can use:

{{ label }} or {{ node.label }} or {{ node.getTitle() }}.