How to display 01, 02... instead of Jan, Feb... on Select List with Date

I have noticed that same issue that the data entry is not actually showing the data entry points that you want it to when entering items in your form. The data is stored in the data base the way you would like but this is more of a theme item I believe. So since you are using the Data API (I think, if not just turn on the Date API and this should work) you can fix this at the theme level and show the data entry the way you would like. The date API offers a hook that you can use called hook_date_select_process_alter() and you should be able to show the data the way you would like in the front end using this hook.

I would not use string overrides module for this b/c as you state you will change the months everywhere, that is not a good thing.

The code to do this (Would be placed in your theme's template.php file Make sure to clear your site cache after adding this):

/**
 * Implements hook_date_select_process_alter().
 */
function THEMENAME_date_select_process_alter(&$element, &$form_state, $context) {
  // dpm($element); // Uncomment to see before render array.
  // Loop through months and change options to numerical options.
  foreach (date_month_names_untranslated() as $key => $month) {
    // Change #options array, key is built with data API function (The same way that the Date API does this).
    // The sprintf() function is used to make things like 1 into 01 since this is technically a string.
    $element['month']['#options'][$key] = sprintf('%02s', $key);
  }
  // dpm($element); // Uncomment to see after render array.
}

You can use the $context variable above to limit this to certain forms like the node edit form ($context['form']['#node_edit_form'] is TRUE on the node edit form) or the form id ($context['form']['#form_id']) would equal your form id. I think that this is almost the way that the Date API intends you to change these items since they offer these hooks.


mythemename.theme

use Drupal\image\Entity\ImageStyle;
use Drupal\file\Entity\File;

function mythemename_preprocess_page(&$variables) {
// change _page to _node or _html depending on the template you are targetting.

  if (isset($variables['node'])) {
    $node = $variables['node'];
    // now you can use $node->field_something

    // Since I have yet to use field collection in D8, I'll let you figure this part out.
    // So all you gotta do is get the fid from your image field.

    // Once you get the FID
    $file = File::load($fid);
    $uri = $file->getFileUri();
    $url_large = ImageStyle::load('large')->buildUrl($uri);
    $url_medium = ImageStyle::load('medium')->buildUrl($uri);
    $variables['large_image_style_url'] = url_large;
    $variables['medium_image_style_url'] = url_medium;
  }
}

Then in twig you can do {{ large_image_style_url }} and {{ medium_image_style_url }}

I had to do it like this, since I needed to print the image in page.html.twig. If you need yours in node.html.twig you could try the answers to How to use an image style in a Drupal 8 twig template?


How to adjust position of drop-down block in Nice-Menu?

You need to be overriding this...

ul.nice-menu-down li ul li ul, #header-region ul.nice-menu-down li ul li ul


HTML tags are counted in for the length of a teaser, instead of words?

Below is a very simple, but mostly complete, and un-tested text formatter with a setting for how many words to allow.

It's five different functions, that

Tell Drupal there is a new formatter.
Provide the "How many words? form.
Outputs the current setting from above in the display settings form
Limits the number of words in the current text field
Render the actual output

/*
 * Implements hook_field_formatter_info().
 */
function HOOK_field_formatter_info() {
  return array(
    'HOOK_limit_by_words' => array(
      'label' => t('Text limited by words'),
      'field types' => array('text'),
      'settings' => array('number_of_words' => 100),
    ),
  );
}

/*
 * Implements hook_field_formatter_settings_form().
 */
function HOOK_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    'HOOK_limit_by_words' => array(
      '#type' => 'textfield',
      '#title' => t('Number of words to use'),
      '#default_value' => $settings['HOOK_limit_by_words'],
    ),
  );

  return $element;
}

/*
 * Implements hook_field_formatter_settings_summary().
 */
function HOOK_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  return t('The current word limit is @wordlimit', array('@wordlimit' => $settings['HOOK_limit_by_words']));
}

function HOOK_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    0 => array(
      '#markup' => word_trim($items[0]['value'], $settings['HOOK_limit_by_words']);
    ),
  );

  return $element;
}

/**
 * Trim a string to a given number of words.
 * Thanks Lullabot.
 *
 * @param string $string
 *   the original string
 * @param int $count
 *   the word count
 * @param bool $ellipsis
 *   TRUE to add "..."
 *   or use a string to define other character
 *
 * @return string
 *   trimmed string with ellipsis added if it was truncated
 */
function word_trim($string, $count, $ellipsis = FALSE) {
  $words = explode(' ', $string);
  if (count($words) > $count) {
    array_splice($words, $count);
    $string = implode(' ', $words);
    if (is_string($ellipsis)) {
      $string .= $ellipsis;
    }
    elseif ($ellipsis) {
      $string .= '&hellip;';
    }
  }
  return $string;
}


How can I access to created "View modes" in views and create a block of it?

Just skip this part of creating a View. Don't create a block or page display yet (that's what I do) and work on a master view. When you go select rendered content as a field, you will have view modes you created as options. Show "Content" as a view mode.

See this for more:

https://www.amazeelabs.com/en/blog/views-field-rewriting-to-views-modes


Register a new user programmaticaly having id proof

Hope this will help  you.

In Drupal 7 you can use file_save_data and file_usage_add.

file_save_data : Saves a file to the specified destination and creates a database entry.
file_usage_add : Records that a module is using a file.

    global $user;
    $path = 'C:\...\Downloads\sample images\drupal_7_icon_0.jpg';//local path of id proof image
    $filename = drupal_basename($path);//get filename
    $file_temp = file_get_contents($path);
    //Saves a file to the specified destination and creates a database entry.
    //Dont forget to create id_proof folder inside files folder
    $file_temp = file_save_data($file_temp, 'public://id_proof/' . $filename, FILE_EXISTS_RENAME);

    // Record that the module (in this example, user module) is using the file.
    file_usage_add($file_temp, 'mymodule_name', 'user', $user->uid);//change the module name

    //Get the values to create new user
    $form_state = array();
    $form_state['values']['name'] = 'robo-user';
    $form_state['values']['mail'] = 'robouser@example.com';
    $form_state['values']['pass']['pass1'] = '1234';
    $form_state['values']['pass']['pass2'] = '1234';
    $form_state['values']['op'] = t('Create new account');
    $form_state['values']['field_user_id_proof'][LANGUAGE_NONE][0]['fid'] = $file_temp->fid;//change it as per your requirement
    drupal_form_submit('user_register_form', $form_state);
    drupal_set_message('User saved successfully');


It's definitely js related, most likely a conflict/error from something in the theme or a contributed module. If you switch to a core theme, are the blocks draggable? If not, it's probably a module (or a script coming from somewhere else, like a block).

If you need to change block position ASAP, you can temporarily disable your browser's javascript, which should then cause the weight positioning drop-downs to appear, which you can use to adjust the order.


How to make sure simpleSamlAuth module is working as intended?

There are hooks and config in the module UI that should aid in this. Here is an example from a Drupal 8 project I did that does just this:

/**
 * Implements hook_simplesamlphp_auth_allow_login().
 */
function MYMODULE_simplesamlphp_auth_allow_login(array $attributes) : bool {
  // Debugging purposes
  \Drupal::logger('mymodule')->log('info', 'Attributes contained: @attributes', ['@attributes' => $attributes]);

  if (empty($attributes['EMAIL_ATTRIBUTE_IDENTIFIER'])) {
    \Drupal::logger('mymodule')->log('info', 'Attribute was not present.', ['@attributes' => $attributes]);
    return FALSE;
  }

  // Run a query to see if the user exists by email address in Drupal
  $exists = // query users by email address

  return $exists;
}

Perhaps a simpler approach in your case would be hook_form_alter, adding a new submit handler and doing the email check there before anything else happens, but the hook above is the final say-so in if a user can authenticate and login or not.


If you want to set a form value from within your validation callback you'll need to use something like form_set_value. Values that are assigned directly in the manner shown above will not be retained, but that function should do the trick! It's specifically intended for this purpose - setting a form value during the validation phase.

For example:

function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
        // Note that the $form array - not $form_state - is used in the first parameter.
        // The second parameter is the value you are setting.
        // Third just pass the $form_state array itself, which will be altered by form_set_vaue().
        form_set_value($form['field_b'], $form_state['values']['field_a'], $form_state);
      }
      if (strlen($form_state['values']['field_b']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}


What are the different ways I can export permissions from a preconfigured Drupal site

This module(Export roles and permissions) allows you to exports roles and permission by generating a hook_install implementation

  This module allows you to generate a hook_install() implementation
  that creates the chosen roles with their associated permissions. The
  main purpose for creating this module was to transfer roles from a
  local dev machine to a remote stage/live server.


Use Regex to insert jQuery querystring before a url anchor

Rather than writing your own solution you could just a solution that's already tried and tested, like the parse_url() function on phpjs.

It works exactly the same way as PHP's parse_url() so you can use it to extract all elements of the url, alter what you need, then build it up again.

For example calling the function like this:

var components = parse_url('http://username:password@hostname/path?arg=value#anchor');

Will yield the following result:

{
  scheme: 'http',
  host: 'hostname',
  user: 'username',
  pass: 'password',
  path: '/path',
  query: 'arg=value',
  fragment: 'anchor'
}

From there it'll be easy to manipulate the values you're interested in and build up a new URL, without having to resort to a another regex.

Basic example:

$('a[href^="/example/"]').each(function(index, element) {
  var components = parse_url($(this).attr('href'));

  var newUrl = components.scheme + '://' + components.hostname + '/' + components.path + '?parent=' + Drupal.settings.nodeinfo.nid + '#' + components.anchor;

  $(this).attr('href', newUrl);
});


Can a disabled module pose a security risk?

I say yes since the vulnerable code is still sitting right there in the web directory which can (will) be scanned by potential attackers. Monitoring disabled modules is certainly part of our update routine.

I didn't find a whole lot of discussion on this in regards to Drupal in particular, likely because it isn't really a Drupal-related issue (see note below). Greg Knaddison (@greggles on Drupal.org) noted on a thread a few years back that:

  Sometimes the vulnerabilities exist regardless of whether or not the
  module is enabled, so I think it's better to warn on all modules.

Source: Issue #942960: Don't warn about security updates for disabled modules

As always, best to err on the side of caution.

Note: I think this is more a server admin related question, but I hesitate to flag it as not relevant since IMHO people who aren't server admins shouldn't really be expected to know that.


How to get MEDIAN of value in a view field

You can use Computed Field  module to achieve this.
About Computed Field

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!


After updating to user_restrictions-7.x-1.0 in drupal7, I can no longer run cron from another host

The User restrictions module just restricts which users can log in basing on their username and email address; if the username or the email address matches a regular expression set in the module settings, the user is not allowed to log in. At the same time, the module doesn't allow users to change their usernames or email addresses to values that match those regular expressions.

The modules doesn't restrict user access basing on their IP, since that functionality is still present in Drupal 7 core, although Drupal core just allows you to set an IP address, not a range of IPs to ban.
If you are experiencing what you reported, then it could a module bug. Report it in the project queue, once you verified there isn't a issue already opened for that, and that the module is really the responsible for that behavior.

Disclaimer

I am the maintainer of the module, although I didn't change the module code recently. I don't plan to develop any Drupal 7 module, since I am focusing on Drupal 8 development.


Changing a plain text field to enable rich editing

There is no official solution. String and text fields have different structure (text has an additional format column), you could try to convert it by hand, but you also need to update Drupal's internal information about the field and resulting database schema.
Your easiest option is probably to create a new field and then write a simple script that loads all nodes of that type and assigns the value of the old field to the new. If there are too many nodes to load for a single run, you'll need to split it up or do a batch.
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'yourtype']);
foreach ($nodes as $node) {
  $node->newfield->value = $node->oldfield->value;
  $node->newfield->format = 'plain_text';
  $node->save();
}


If you want show sql query you can use code below:

function example_views_pre_execute(&$view) {
  if ($view->name == 'search_jobs'){
        dpq($view->build_info['query']);
    }
}

In your code function dpq error because variable $view->build_info['query'] is NULL. The function dpq only run when variable is An object that implements the SelectQueryInterface interface.


How can I get Drupal to hide menu items that user does not have permission for?

Drupal does this using access callback from the menu items.

In the example given:

This was working.
The Application had TRUE for the access callback. As this was not my application, I used hook_menu_alter in my own module to set the access callback for this argument to my own function. This then checked the permission and returned true/false.
The Contact Access module requires rebuilding permissions (/admin/reports/status/rebuild) after any changes.


This method is pretty similar to what Shoaid Nawaz has said above. For Drupal 7, you can use the Views module. Coupled with a custom theme region, you can create a block using the views module which will show an image for each node from a custom image field specified for the content type. You need to have a basic working knowledge of the Views module.

Here is how:

Create a custom theme region, name it something like "Banner Region"
In your content type, add an image field, name it something like "Banner image". If you need description, enable Alt tags for the image field. If you do not need slideshow, restrict the number of image to 1. For slideshow, you can use the views_slideshow module.
To create similar sized banner images, you can create a new image style.
Create a new View. Name it something like "Banner". Choose "block" display and not "page".
In the filter criteria, choose your content type.
Add a contextual filter for "Content: Nid" and save the view.
Now go to the your blocks administration page and add the newly created views block to your new banner region.

In short:

Banner image is a new image field in an existing content type.
Views module understands which image is attached with which node using the contextual filter.

Tip: You might want to disable this block on the frontpage if your frontpage is not a node.

Further tip: You might consider adding other content types to the filter criteria if you banners for multiple content types. Alternatively, you can create a block for each content type and block control visibility using "No results behaviour" in the views' settings.


Print current logged in user without link

l() is the function that creates a link, so...

<?php print $user_name; ?>


This is not a standardfeature of Taxonomy. In fact, it is not a part of the concept Taxonomy, regardless of using Drupal at all.

However, you can achieve this, somehow with Drupal taxonomies, when you abuse them as Facets.

For that, you need to set up your views and provide quite some hacks, amongst others, you need to add some PHP to your views.

From a birdseye, here is what you do:

You create views that list only nodes with term X as parameter: /mypage/12 to show only pages with term 12.
You allow Drilling down in that list, by nesting the parameters: /mypage/12/35 to show only nodes with BOTH term 12 AND term 35.
You abuse the views header to present links with options: links to the nested options: on mypage/12 it would show, amongst others, a link to term 35, a link to /mypage/12/35.
The code to select these options can be simplified by making a second view: a view that lists all options nested under 12.
In the header of the first, node, view, you then place some PHP that fetches and renders these links.

For a long and detailed howto, I think burningbird has a good manual


Theme's css and js files are not being loaded

englishtrainer.info.yml:

name: Englishtrainer
type: theme
core: 8.x
version: '1.0.0'
libraries:
  - englishtrainer/base
regions:
  header: Header

No need for package

englishtrainer.libraries.yml:

base:
  version: VERSION
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

Use base to start things off and the VERSION keyword will take the version info from englishtrainer.info.yml.


How do I detect whether any contact forms have been created?

You can use the D8 config factory interface to retrieve multiple contact form config keys and their corresponding config entities:
$contact_form_keys = \Drupal::configFactory()->listAll('contact.form');
$contact_form_configs = \Drupal::configFactory()->:loadMultiple($contact_form_keys);


How to enable user defined module from the administration menu list?

You should follow these steps. This may help you to better understand that how to create custom module. If you have any query then comment below.

Link


How to apply .diff and .patch file by SSH?

After logging in to your site with SSH, in order to apply patches, you should have or install a program on your server. patch is the most widespread one, but you can also use git for it.

You can find more documentation on applying patches in the Drupal site: https://www.drupal.org/patch/apply


When should hook_post_update_NAME() be implemented instead of hook_update_N()?

Normally when you update Drupal core locally you perform the following:
composer update
drush updb
drush cex

Let's say that there's a core module implementing hook_update_N() to update some content or config – an update that triggers entity load and entity save somehow. Now let's say that in some other core module inside some other hook_update_N() are updates to the database schema which in the end handles how this content or config is actually stored. How can you reliably ensure that the schema updates run before the content/config updates, especially when some users update their site skipping some few minor releases at once?
So hook_post_update_NAME() was introduced to guarantee all schema/structure/format updates have run first and now can be relied on when needing to update content or config on top of them.

[Issue] Add hook_post_update_NAME() for data value updates to reliably run after data format updates
[Change record] hook_post_update_NAME() introduced to change content after hook_update_N() runs

Now let me also tell you that the most reliable hook for simple content updates from a custom module is hook_deploy_NAME(). This hook was introduced in Drush 10.3.0 together with the new drush deploy command. Using this new command to replace the old drush updb && drush cim deployment routines all hook_deploy_NAME() implementations will be picked up after configuration import. Which totally makes sense when you want to populate a new field which has only been created and added to config in the same release.

[Issue] Add hook_post_config_import_NAME after config import


How to show a block on specific content type and combine it with path restrictions

With D8 you can make multiple instances of the same block, just use Place Block to place another copy of it. Then you can have one display on the specific content types, and the other display on the pages you need.


Is there a way to set the styling for the "choose file" button for Webform module?

Yes, actually styling a FILE INPUT field is hard because, just like you're seeing, it's a singular field that is hard to pick apart.

Here is a discussion of styling file input fields from stackoverflow.

As you can see - thought there are many solutions presented, they all require some jquery and essentially hide the input field and replace it with something else.

So in short - there is no easy way to do it.


Why to use [attributes] when adding class to a button inside my hook function

This more a theoretical question. You can see in the documentation or example code how to use the render element.

The technical background is, that each render element defines variables which you can use when building the render array. The variables of a render element are placed on the top level of the render array and prefixed with '#'.

This is an excerpt of the code which prepares the render element for rendering:

  public static function preRenderButton($element) {
    $element['#attributes']['type'] = 'submit';
    Element::setAttributes($element, array('id', 'name', 'value'));

Here you can see that #id, #name and #value are placed in the attributes by the element itself.

If you want to set other attributes, you have to place them yourself in #attibutes.


Try going to admin/config/system/site-information and set the default front page to /node. I think what you describe is related to the Views module which provides the default frontpage in Drupal 8.


How create Redirect pattern from old to new URLs?

You can use the pathauto module to construct your node aliases from tokens (admin/config/search/path/patterns). In addition, there is a setting to tell pathauto to leave the existing alias in place when creating a new one. At admin/config/search/path/settings, you can specify this in the Update action section:


Add value to a custom composite element in webform via hook_update_N

After trawling through the Webform source think I have an answer.

/**
 * Update using hook_update_N for mymodule to add more options to a webform custom composite.
 */

function mymodule_update_8001() {

    . . .

    // Update a composite element in a webform
    $webform = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
    $elements = $webform->getElementsDecodedAndFlattened();

    // Add new options here.
    $elements['my_composite_id']['#element']['my_composite_element_id']['#options']['my_new_option'] = 'My new option text';

    $webform->setElements($elements);
    $webform->save();

    . . .

}

Please let me know if there is a better way.


How to include specific roles in auto-complete search?

The best way to do this is create a View of the search results you would want. e.g. If you create a view of Users with role, "editor", then Autocomplete can be used to pull only from that view. Using the Filters ability of views, this should be a relatively simple task.

http://drupal.org/project/search_autocomplete supports this feature.


Up to how many nodes Drupal can handle without affecting performance?

It very much depends on your hosting and server configuration.

For example one of the projects I worked on handled without performance issues about 10 millions of nodes. But it lived on a cluster of 4 dual-core servers with lots of memory on each, and the cluster was behind load balancer and reverse proxy caching (Varnish).

On another project I had performance issues after something like 1000 of nodes, that was a shared hosting.


Is it possible to alter the cacheability of a specific entity either programatically or via configuration

I just came up with a solution, but I'm not sure it's the "right" way to do it.

Anything entity that implements RefinableCacheableDependencyTrait will allow you to introduce additional dependencies with a call to addCacheableDependency(). I sort of hoped there might be a predefined dependency that was hardcoded to no cache. I didn't find such a thing. What I did find is that if the argument to that method is not an object that implements CacheableDependencyInterface, then it makes it uncacheable. So, here's what I ended up with:

  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('TESTING'), '<front>'));
    $breadcrumb->addCacheableDependency(null);
    return $breadcrumb;
  }


You are looking for field_attach_view

What you would need to do, with your loaded node is something like this:

$fields = field_attach_view('node', $node, 'full');
$body = $fields['field_body'];


How to print a string for flagged nodes?

You can set a new variable in your preprocess function and print it in your node--type.tpl.php as follows:

In template.php

function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'YOUR_CONTENT_TYPE') {
    $flag = flag_get_flag('sold');
    if ($flag && $flag->is_flagged($node->nid)) {
      $variables['classes_array'][] = 'node-flag-sold';
      $variables['flagged_text'] = t('Sold');
    }
  }
}

And in your node--YOUR-CONTENT-TYPE.tpl.php, put simply this snippet wherever you want to print the string:

<?php if ($flagged_text): ?>
  <?php print $flagged_text; ?>
<?php endif; ?>

or the same code shorter:

<?php if ($flagged_text) print $flagged_text; ?>

But the first one is better for readability and follows the Drupal's coding standards for template files.


how to load Ckeditor with IMCE file browser through javascript

Finally i figured it myself, after referring to some of the Drupal forum posts, like this one. I removed the 'Image' button in ckeditor toolbar, and instead used the 'IMCE' button. I realized that i must

Assign a profile to the users under: admin/config/media/imce
Under admin/config/content/ckeditor/edit/Full > Editor Appearance, add 'IMCE' button in the 'Used Buttons' area and check the option "Plugin for inserting files from imce without image dialog" under Plugins. (assuming that i am using 'Full' ckeditor profile)
Under admin/config/content/ckeditor/edit/Full > File browser settings > select 'IMCE' for all File browser type options.
Include the 'IMCE' option while applying the ckeditor for the textarea, like:

CKEDITOR.config.toolbar = [['Bold','Italic','Underline',
'-','JustifyLeft','JustifyCenter','JustifyRight','-','IMCE','Undo','Redo']];

Finally this is what i achieved in the editor:


What I did to change the date format. In modules/advanced_forum/includes/theme.inc I found the function advanced_forum_preprocess_forum_submitted(&$variables) and changed line 249 to $cutoff = variable_get('advanced_forum_time_ago_cutoff', 0) * 60 * 60; and line 254 - to $variables['date_posted'] = format_date($timestamp, 'custom', 'j M Y,    G:i');


Values missing in $form_state inside form function but available in ajax callback

It seems you are a bit confused about how the form API works. What you are seeing is exactly as expected. I'll try to explain about how the form API works.

The ajax callback is called in a context of the form being submitted, which is why, all of the form values are passed along, the actual form function is called in the context of being initialized where no form values exist.

There are different ways of structuring ajax. One way could be to add another input like what's possible with fields that can hold many values. In that case, the ajax callback function should only worry about a subset of the form, and return this (You shouldn't call render inside ajax callbacks).

Another way to use ajax is to restructure the entire form. In that case, what you can do, is to set

$form_state['rebuild'] = TRUE;

Which will force Drupal to rebuild the entire form, with the current values and make it possible to fx create a multistep form. This can be done both with and without AJAX.

It sounds like you will need to rebuild the form, to get $form_state values into the form function. Then you can add ajax behavior to the form, where you get this working.


Linking terms to views instead of taxonomy pages

If you're dealing with a limited number of terms (genres), you can do the following:

Head to Structure > Taxonomy > List Terms (next to your genre category)
Click Edit next to a term.
Uncheck "Generate automatic URL alias" under the URL Path Settings.
Enter the path to your View.
Repeat.

You can also use the PathAuto module to set up rules for automatic forwarding of Taxonomy links to your Views. Install PathAuto, enable, click Configure, select the Patterns tab, and rewrite the URL path for Taxonomy.


Drupal login error message display on page by make new module

I suggest you DO NOT CHANGE DRUPAL CORE , if you want your custom validation use something like this

function usermoved_form_user_login_block_alter(&$form, &$form_state) {
   $form['warning'] = array(
   '#value' => t('oops'),
   '#weight' => 11
   );
  $form['#submit'][] = 'usermoved_form_submit_code';
  $form['#validate'][] = 'yourcustomvalidationfunction';
     }

and in your custom validate fuction  put your error in warning field

 function   yourcustomvalidationfunction(&$form,&$form_state){
    if (your validation accure error) {
        $form['warning']['#value']= t('my error message that come in warning field') ;
       }
    }

or you can  create and initial warning  directly in validation function and not require create warning field in alter


Locking nodes or entities to prevent concurrent editing

I believe this is already implemented to some degree. If two users are editing the same piece of content, and one submits changes, the other user will receive this message when trying to do the same:

  The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

It happens in the node_validate() function in case you're interested in checking out the code.


You need to actually go to the page in the admin that updates the variable and edit it from the non-default language url.

For example, with site name, if you have one other language with 'es' as a path prefix you would go to 'http://example.com/es/admin/settings/site-information' and change the site name. Once you do that in another language it will create the variable in the i18n_variable table.

You will know you are on the right track when the element you want to update in the admin says "This is a multilingual variable"


How to know which users/nodes failed to import in feeds logs?

So views data export will truncate some user names based on their lengths. This resulted in a mismatch between the exported users' name and the user name in the DB, leading to errors.


Where is menu settings for node types stored in database

That data is in a number of different variables in the variable table.

Specifically for menu options, you'll find it in a var named menu_options_CONTENT_TYPE (e.g. menu_options_article for an "article" type). For the menu parent it's menu_parent_article, and so on.

Above assumes Drupal 7, it'll be different for 8.


How does Drupal verify sessions from the cookie value?

I figured it out, but if someone posts a more in-depth answer, I'll accept it.

Drupal has a SessionHandler with a read function:

public function read($sid) {
    $data = '';
    if (!empty($sid)) {
      // Read the session data from the database.
      $query = $this->connection
        ->queryRange('SELECT session FROM {sessions} WHERE sid = :sid', 0, 1, [':sid' => Crypt::hashBase64($sid)]);
      $data = (string) $query->fetchField();
    }
    return $data;
  }

And, if you bootstrap Drupal, or call an external Drush script, you can do this:

$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$logged_in = (bool) $session_handler->read($session);

Here's how I got the cookie out of the Guzzle object:

$request->getCookies();
//var_dump($cookies);
foreach($cookies as $cookie){
  if(strpos($cookie, "SESS") == 0){
    $session = $cookie;
  }
}

If you actually want the UID, you're going to have to not do the (bool) cast and de-blob the thing, because it returns the raw MySQL data.


How to get error messages to display on the form, rather than after the page is refreshed?

You can use contributed module Clientside Validation which is very close to your requirement.

  This module adds clientside validation (aka "Ajax form validation")
  for all forms and webforms using jquery.validate. The included
  jquery.validate.js file is patched because we needed to be able to
  hide empty messages.


Apply multiple Content Type filters to Search Block Form in hook_form_alter()

So, I figured out how to make it work without actually finding any documentation. I just added a new filter for each content type I want to search:

$form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
];
// add filter for current language
$form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . \Drupal::languageManager()->getCurrentLanguage()->getId(),
];
// add filter for each full-page content type
foreach (fullPageNodeList() as $key => $full_page_type) {
    $form['f['.($key + 1).']'] = [
        '#type' => 'hidden',
        '#value' => 'type:'.$full_page_type
    ];
}


Show available languages in content-view

The content admin screen is now just a view.  AFAIK there is no view widget that will do that.

It probably would be possible to write a entity specific global widget for this.  Basically, you can get the list of installed languages from the language manager and then for each entity row use the getTranslations() method to find what has been translated.


Global Filter as main menu drop down link

To rewrite your taxonomy URLs (you should probably rewrite your question to this end) you can use the following.

/*
 * Modify taxonomy uris to point back to facetted search
 */
function my_module_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_my_module_term_uri';
}

/**
 * Rewrite term URIs to point to our search query.
 */
function _my_module_term_uri($term) {
  $path = null;
  // Do your stuff to get your path correct.

  // Return your path if you've managed to rewrite it.
  if ( $path ) {
    return array(
      'path' => $path,
      'options' => array(), // url style options
    );
  }

  // Otherwise just return the default.
  return taxonomy_term_uri($term);
}


It doesn't look like this is causing a memory leak as @tenken said in his comment.  However, since this is going in a node, that whole PHP snippet is stored in the database which isn't recommended.  It will take more memory to grab this code from the database, then run it.

Try sticking the code in a function in PHP file and then running that function somewhere else on the site, i.e. a custom module.  This is a good tutorial on how to do that.


Remove components from a feature using Drush

Remove the component by deleting the corresponding line in your feature's .info file. Then run:

$ drush fu <feature_name>

In your case:

Open the file /sites/all/<features_folder>/myfeature/myfeature.info.
Delete the following line.

features[views_view][] = myview2
Save the file.
Run $ drush fu myfeature in your site's folder.


Nope, not really. Drupal is built from ground up in English and that's the way you need to build your modules too. Some parts of the code tries to enable you provide default texts in another languages, but it's a disaster if you decide to change default language later.

It is possible to built functionality like you need in a custom module, it is even possible someone did, but I don't know of any reliable solution.


What difference between declaration of an ajax callback function with $this and without it?

The ::method as a string is a special feature of the form API.

It's basically a shorthand for [$this, 'method'] and does almost exactly the same. See FormState::prepareCallback

There is one interesting difference, [$this, 'method'] has to serialize the whole form object within the form structure, to then unserialize it to call a method on it. But at that point, on a cached request, it is actually a different object because the form system also created a new form object, as part of initializing it and starting to process the request. ::method will actually call the method on the new form object.

Whenever possible, use the short version, sometimes that's not possible, for example when you are inside a plugin (e.g. a field widget) or other class called by the form, in this case, it is recommend to use a static method.


How do you add a input and a select field with webforms?

Welcome to the Drupal Answers Mel.
You can use the Select or Other module. When you enable it, you get another element called Select other. Please take a look at the below screenshots:

Hope that helps.


acquia cloud - images in content break, different path local vs cloud/server

Implement a directory redirect on your local environment's web server so that any request for /files/*  gets redirected to /sites/default/files/*

For example in Apache,  edit the httpd-vhosts.conf

<VirtualHost *>
  ServerName yourservername
  DocumentRoot "pathtoyourdocroot"
  Redirect /files /sites/default/files
</VirtualHost>


Issue with "Content: Has taxonomy terms (with depth)" with a content type with a repeated taxonomy

My problem was that the view filter Content: Has taxonomy terms (with depth) search in the taxonomy_index table instead of a field of the content type, so I ended duplicating the Simple hierarchical select module (SHS) who's behavior is equal to the Content: Has taxonomy terms (with depth), and editing the query it does.


Running EntityFieldQuery on restricted content (with cron)

Cron runs as the anomymous user. The idea is that it should only call APIs that don't require users. EntityFieldQuery however allows you to either bypass node access checks, or to set the user the query will run as.

Option 1: Set the user to run the query as:

$query = new EntityFieldQuery;
$result = $query
  ->fieldCondtition(...)
  ->addMetaData('account', user_load(1))
  ->execute();

Option 2: Bypass node access by setting the DANGEROUS_ACCESS_CHECK_OPT_OUT tag (since Drupal 7.15 I believe)

$query = new EntityFieldQuery();
$result = $query
  ->fieldCondition(...)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->execute();

Option 3: You can run your cron code as another user by setting the $user global variable. For instance:

function mymodule_cron() {
  global $user;
  $original_user = $user;
  $old_state = drupal_save_session();
  drupal_save_session(FALSE);
  $user = user_load(1);
  _mymodule_do_some_stuff();
  $user = $original_user;
  drupal_save_session($old_state);
}

Option 1 is the cleanest way to do what was requested - it relies on an existing functionality to run a query as a different user. You can use user 1, or create a custom user who has exactly the permissions you require for your operation.

Option 2 is functionally equivalent to using Option 1 with user 1. It is less flexible than option 1, so there isn't really a case to use it (but included here for completeness).

Option 1 and 2 are limited to entity field query, which is what the OP asked. To do other operations as another user, you need to impersonate that user completely - which is what Option 3 does.


There is Auto Username for Drupal 6, and there is a Drupal 7 port of the module sitting in the issue queue.
Perhaps you could test the zip that is attached to that ticket, and help fixing any bugs. ;)

Alternatively, perhaps you could make this happen using the Rules module.


IMCE module is not showing icons on the editor

You need IMCE WYSIWYG bridge module to connect it with WYSIWYG editor.

For CKEditor, configure the editor for your input filter and choose "IMCE" button.

For TinyMCE it is enough to select "Image" button.


How to get value of Textarea in node add form?

Shortly put, you need to do the following:

Use hook_form_alter, the way you do already
Use hook_node_submit, to update the field_title field on the node object, before it gets saved. In your hook implementation you will have access to both $form and $form_state, which should carry your custom textarea submitted value. Even if the nid is not there, your changes should still get stored in the new node.

Hope this helps!


PHP Warning SplObjectStorage::offsetExists() expects parameter 1 to be object, null given

I was able to get this error to go away by deleting my entire project and rebuilding from scratch.  Was not ever able to identify the source for the warnings, so if you come here looking for answers, best of luck.  If you find any, please share!


How to make Drupal 7 render taxonomy tags as RSS categories?

This used to be the default behaviour in D6, but was accidentally removed from D7 after some refactoring. The latest versions of D7 contain a patch that allowed a third-party module to show RSS categories.

Step 1: download and install the RSS field formatters module.

Step 2: navigate to /admin/structure/types

Step 3: click "manage display" next to the desired content type

Step 4: expand "custom display settings" and make sure "RSS" is checked:

Step 5: select the "RSS" tab (after hitting Save if you had to enable the RSS checkbox). This one is a bit hard to notice:

Step 6: add the Tags to the fields list if not already there. Set the format to "RSS category":

Now save and enjoy your taxonomy tags in your RSS feed!


How to remove a page from a books and/or delete a book?

There is a option to remove the any page from the Book outline. Suppose I have created a basic page and put in a Book outline. Now if I want to remove, click outline as shown in the follwoing image

Now, you can see Remove from book outline in red in as show in following option. That will remove that Basic page from the book.

Update:

You can not delete entire book at a once. Why, because Book is just a indexing tool, It is not a content type. Book page is a content type. Book page and Book are two different thing. And it should be that way. Hence, you can delete all nodes of one content type by deleting that content type itself. But, if you are putting some node under book outline, you are not creating a entire group/content type, You are just indexing your node in specific order.

Hence, If you delete any Parent item in book, It shows a message that the child will be re-ordered automatically. Hence, you can understand its just a ordering/indexing tool.

Hence, to provide this feature Book Delete module was created. But still it does not have Drupal 8 Version.


Why is the content of the  tag no longer loading in Google Chrome?

That is for sure not a Drupal problem. I'd check the page source to see the head contents; if they appear there, maybe there is an unclosed tag.


How to get core to leverage a MySQL master/slave configuration?

Here's how I currently implement this.

First you need to set up a SelectQueryExtender class like this:

class SlaveTarget extends SelectQueryExtender {
  public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
    if ($connection->getTarget() != 'slave') {
      $connection = Database::getConnection('slave', $connection->getKey());
    }
    parent::__construct($query, $connection);
    $this->addTag('SlaveTarget');
  }
}

Once you have that, then all you have to do is get all the other queries to extend the extender. :) if that makes sense. Here's the snippet.

/**
 * Implements hook_query_alter().
 */
function example_query_alter(QueryAlterableInterface $query) {
  if (is_a($query, 'SelectQuery') && !$query->hasTag('SlaveTarget')) {
    $query->extend('SlaveTarget');
  }
}

And now all your SelectQuery hit the slave ;-) This is the only way I've been able to accomplish this. Anyways it works great.

Also if you have this on a custom module you can set up the SlaveTarget to be it's on file SlaveTarget.inc and add a files[] = SlaveTarget.inc to your module info file.


Omega theme, global css and the lack of grid at global.css

Omega is designed as a mobile-first, breakpoint responsive theme.

global.css is the mobile first sheet, so the grid system doesn't apply.  The grid kicks in with the mytheme-alpha-default.css.

The answer for What's the difference between global.css and default.css files in Omega theme? goes into detail about the stylesheet convention.  In summary:

  How does my site need to look on mobile?  Make global.css
  How do things change when the grid system kicks in?  Make mytheme-alpha-default.css
  How does my site look when I am viewing it in portrait mode on a tablet?  Make mytheme-alpha-narrow.css
  How do things change when I am on a normal desktop?  Make mytheme-alpha-normal.css
  How do things change when I am on a widescreen monitor?  Make mytheme-alpha-wide.css


How to add block to "add/edit" content page?

Here's how to display a block on node add/edit pages in Drupal 8:

Go to Structure -> Blocks.  Select the block layout page for the theme you use to add/edit nodes. This is usually the admin theme, but it may also be the standard theme for your site if you want to display the block to non-admin users. If you want to show the block to both admin and non-admin users, you may need to configure the block settings (as described below) for both the admin theme and the standard theme.

On the block layout page, click Edit on the block you want to display.

Under Visibility, click Pages.

In the text field, enter:

/node/add/*
/node/*/edit

For Drupal 7, don't use the first slash:

node/add/*
node/*/edit

The * is a wildcard that says "any content/value can go here."

Then check the radio button for Show for the listed pages.

If you also want to limit the block to only show for certain content types, you can use the Content types option above Pages.


How to translate countries in multilingual site?

Make sure you have the translated country strings in your database, ready to be used.
country_get_list() calls _country_get_predefined_list(), and inside this function country names are passed through t(). So, if you have country strings translated in your database, translation should work.


this might be what are looking for Adding CSS Classes to Fields in Drupal

  Implementing any type of modular CSS requires fine grain control over
  classes in your HTML. In my last post, we looked at how we can easily
  add classes to blocks in Drupal using preprocess functions. Now let's
  apply the same technique to fields. Fields are a fundamental building
  block of any Drupal 7 site. Fields contain content and content is
  king. Before we dig in and start classing up our fields, let's look at
  how they are rendered to the screen.


It should be

base_path().drupal_get_path('theme', 'THEME_NAME')

Other Examples of path

$GLOBALS['base_url'] => http://example.com/drupal
base_path() => /drupal/
request_uri() =>    /drupal/documentation?page=1
request_path() => documentation
current_path() => node/26419


How to write Custom Javascript in "drupal commerce" checkout page?

As St0ik mentioned, you'll want to use drupal_add_js to add the JavaScript to the page. The real question is, where do you want it to go?

If you want it to show up on every checkout page, use the generic checkout form alter:

// Show on every page of checkout.
function MYMODULE_form_commerce_checkout_form_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

If you want it to only show up on certain pages within the checkout, you can use a more specific form alter to only add it to a certain page.

// Review before payment only.
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

or

// First page of checkout.
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

You'll use MYMODULE_form_commerce_checkout_form_PAGE_alter where PAGE is the wanted checkout step.


Managing user accounts on remote drupal website? (Dev team all needs access)

maybe User Import and keep a running cvs file of users to add to new sites on an as needed basis (?)


Is 'order completed' a safe way to assume that order is paid in full?

No. As with Commerce 1.x, we have a specific event in Commerce 2.x that is only triggered the first time an order is observed to be paid in full. It's defined in OrderEvents.php:
  /**
   * Name of the event fired after the order has been fully paid.
   *
   * Guaranteed to only fire once, when the order balance reaches zero.
   * Subsequent changes to the balance won't redispatch the event (e.g. in case
   * of a refund followed by an additional payment).
   *
   * Fired before the order is saved.
   *
   * @Event
   *
   * @see \Drupal\commerce_order\OrderInterface::getBalance()
   * @see \Drupal\commerce_order\Event\OrderEvent
   */
  const ORDER_PAID = 'commerce_order.order.paid';


How to redirect a menu item to the anchor?

Modules are how you extend Drupal's functionality; there's very little point saying you want to achieve something without a module, as if one exists, you're just going to end up copy/pasting its code into your own module/theme anyway to get the same effect.

Drupal core has no functionality to link to an anchor, so you need to install a module which does, or copy the code from one to your own.

Whichever of those methods you decide to use, Special Menu Items has the functionality you require (you can either install
and use it as normal, or pick the relevant bits of code out into your own module/theme).


PHP calls getIterator() for you, you don't have to do that. Also use $variables['node'], much easier to access.

File/Image references an extension of entity references, which means they inherit the computed ->entity property, which automatically loads the referenced entity. Make sure you check if the file can be loaded, or inconsistent data (if, for some reason, the file gets deleted. Less likely for files but could happen for node or other references) would result in a fatal error.

foreach ($variables['node']->photos as $item) {
  if ($item->entity) {
    $uri = $item->entity->getFileUri();
  }
}

$uri is something like 'public://your_file.jpg'. You can create a public url with file_create_url() or you can also pass it to an image style entity's buildUrl() method to get the URL for a given image style.

See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for common ways to access field values, what properties exist for each field type and much more.


Views Slideshow alternating blank screens with content items

I found that the problem disappeared when I disabled the module "devel_themer." I began to suspect it only after looking at the dynamic code in Firebug, which showed the images trying to cycle and to cross-dissolve by animating transparency. I saw a lot of modified code referring to this module name, and figured that since it's not the native code that should be seen here, it would be worth trying the disable and see what happens. Problem apparently solved.


Design query for job site using subdomains

You are looking for Purl, and would perhaps also benefit from using Spaces.


Use ajax not working in views block displayed programmatically

I found the solution

To have the "use ajax" working, you have to render the view using:

$view->set_display('block_1');
print $view->preview('block_1');


Creating a view that groups results by month/year

You can group by any field, including Month-year. You have to select your date field and customize the output. Then, Views can group on the field, using the "Grouping" options under Format: Settings.


Import Book content and structure from another drupal website

If you haven't got admin access then you'll need to scrape the content. The module Example Web Scraper would be a good starting point.

I think this question on the ethics of web scraping may also be relevant.


Yes it is. In the end even unlimited with custom code ..

To easily limit the access for a vendor to only his products, each one would need one or more product types, then you can apply the right permissions. Also I would add the vendor/user as a reference (field) to that product type.

There very good shipping methods, applicable for different countries etc.


Cant login to my sites on AWS but I CAN login with the same database on my local machine

Well, I fixed it. I had to run the following command:

sudo a2enmod rewrite


Get the node id that have /sign-up as alias (lets say it's node/42)
Go to /admin/config/search/path/add
Fill the form as mentioned in the description :
Existing system path : /node/42
Path alias : /caregiver/sign-up
Save the form
you can now access the node with /caregiver/sign-up alias :)


HTTP 502 Bad Gateway is, as its name says, something that happened on your gateway, not on your server. Since the error is between you and your server, Drupal can't really know it happened unless, of course, you are talking about a job that connects to a remote server and the error happens between your site and that remote server. If so, you can either ask admins to fix gateways, or file a bugreports: one to service provider, and the other to the author of the module you are using.


In Drupal 7, instead of hook_block() there are more hooks:

hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()

In short, you need to split the Drupal 6 code for hook_block() between those hooks.

As side notes:

Every function implemented from a module should be prefixed by the module short name
To load the node, you should use the following code.

if ($node = menu_get_object()) {
  // The page is a node page.
}

To access the content of a field, you should use the following code.

$items = field_get_items('node', $node, 'field_head_img');
$path = $items[0]['filepath'];

To output an image, you should use theme('image'), or theme('image_style'). As you are outputting a field, you should use field_view_field(), as in the following code.

$output = field_view_field('node', $node, 'field_head_img');


Scrape articles from one Drupal site to other?

You do not need to install a module for this. This sort of thing is provided by the Drupal core. It is called an "Aggregator" and you find it as one of the core modules with the following description:

  Aggregates syndicated content (RSS, RDF, and Atom feeds).

It is not enabled by default.  You need to enable it.

Here is a rundown of the UI:

administer your list of news feeds. Admin → Configuration → Web Services → Feed aggregator
add a new feed. Admin → Configuration → Web Services → Feed aggregator → Add feed
add a new category. Admin → Configuration → Web Services → Feed aggregator → Add category
configure global settings for the news aggregator. Admin → Configuration → Web Services → Feed aggregator → Settings
control access to the aggregator module. Admin → People → Permissions
set permissions to access new feeds for user roles such as anonymous users. Admin → People → Permissions
view the Aggregator page. Admin → Configuration → Web Services → Feed aggregator
update the feed manually. Admin → Configuration → Web Services → Feed aggregator

You need to set up cron to update the feed automatically.

If the site you want to use as the source for your feed is running Drupal 7, the export feed is already in place.  The URL should be http://example.com/rss.xml.

Near the bottom of the page of any Drupal 7 (unless you've taken steps to remove it), there should be a symbool like this:

If you click on it, you should be able to inspect your outgoing feed (provided your browser knows about RSS feeds).

You can of course use this to aggregate content imported from more than one site, but it will also work fine if you just to import content from your own, old site.


I found out the hard way that what was not working on jsfiddle.net was actually working on mobile. I wasted my own evening on this issue :S Thanks for all the comments though guys.


Adding nofollow to specific internal paths

Since you want to add this attribute only to custom URLs (those matching /user/*) within your content, you might have to write custom code, as I'm not aware of any module which does this.

You could use hook_preprocess_field() and then execute a regular expression to match your pattern and add the rel="nofollow" attribute. However, this could be highly inefficient, as you have to do it every time you render a node, besides the fact that parsing HTML with regular expressions is not a bullet-proof solution.

Here it's a very simple example that just adds rel="nofollow" to all links in the body field (you will have to adapt it to use your own regular expression).

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
     $markup = $variables['items']['0']['#markup'];
     $variables['items']['0']['#markup'] = preg_replace('/href=/', 'rel="nofollow" href=', $markup);
  }
}

Another alternative would be using the Path Nofollow module, that does something similar:

  Specify paths on which a metatag is added to prevent search engines
  from indexing the page.

So you could specify the path /user/* and it will add a metatag in the head of your html <meta name="robots" content="noindex">. As I said, not exactly the same, but it might help or complement your goal.


Inside TWIG Template, how to determine if a paraph is empty or not

Better use the node object to check whether the field is not empty:

{% if not node.field_example.isempty %}


Query for email address already existing

Use this code to check if there is a user with provided email.

$account = user_load_by_mail($email);

if ($account) {
  // Do something.
  $form_state->setError(....
}

Besides, as I know in standard registration form there is already such validation.


How to calculate the sum of the values of a multi value field without page reload

I was going to recommend researching the AJAX in hook_form_alter function(), but when I read that you were using Field Collections I got a little nervous.

The problem with Field Collections is they can be little finicky when you try and do more complex field "stuff" like the scenario you're proposing. I have yet to try using AJAX in combination with Field Collections and I definitely would not want to be the developer who was tasked with it.

However, if you feel like you want to tackle such a problem you are most certainly going to have create a custom module specific to your situation.

Below is the basic layout for a Node Form Alter using AJAX. Ultimately you want to add an AJAX Event function on your select list, so when the value changes it will call a function that adds the values together.

That's even before you factor in the Field Collections module, which is going to add another layer of complexity to the whole operation.

https://api.drupal.org/api/examples/ajax_example!ajax_example_node_form_alter.inc/7

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    ),
  );
  $form['container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ? $node->ajax_example['example_2'] : $form_state['values']['ajax_example_2'],
    );
  }
}

ajax['event']

Description: When this event occurs to this element, Drupal will perform an HTTP request in the background via Javascript.

Values: String. Possible values: Any valid jQuery event, including 'mousedown' (for submit, imagebutton, and button), 'blur' (for textfield and textarea), 'change' (for select). Note that #ajax['event'] does not need to be explicitly specified. Although it can be manually set, usually the default value will be sufficient.


How can I transfer votes to nodes selected from an entity reference list?

Use the Inline Entity form, which allows you to set a view with the list of nodes and modify them directly (you would set the voting in the voted node e.g., the class or teacher, in your example).

The plan is for you to set up the Review content type with a Entity Reference field. This will allow you reference a View where you can set up your Class and Teacher Nodes.

You need the following Modules: Five Star and Voting Api (Which you already have) Views, Entity API, Inline Entity Form.

The way I understand your process is as follows:

You have a set of classes and a teachers
You intend to make available a set of these classes and teachers to a different content type (this is review), to generate votes for that class and/or teacher
The number of classes/teachers available for that review to emit a vote from is unspecified (may be all or a subset of them)

To go about this you need to have the following:

Voting fields in class and teacher content types
Create a Entity Reference View which displays the list of nodes you need (one for each, selecting their respective content types).
Add a Entity Reference field in the review content type with the Inline entity form - multiple values widget.
While setting the field:

Check Allow users to add existing nodes, so that they can select the class/teacher from your current list.
Select in Entity Selection: Views: Filter by an entity reference view
Select in View used to select the entities the view you would prefer for that field (teacher or class)

You should be able to add the classes/teachers you want to vote for. Also, you can control the entities shown by the view (so you could add context filters). Be mindful of setting the votes so you can vote while editing.


Possible timing issues when using setActiveConnection to an external database under normal Drupal 8 operation

In looking at the getConnections method closer you can pass it the $target and $key parameters directly and it will return a handle to the specified database.

$this->_db = \Drupal\Core\Database\Database::getConnection('default', 'notificationsdb');

This way you don't have to mess around with setting the active database.


You could just type it into the template and dont have to do anything clever or twig based? e.g.

Show more

The core html.html.twig quite happily does this for the #main-content link:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21html.html.twig/8.2.x


How to instantiate a service inside ServiceProvider?

You can't get services at this point.
This interface ServiceProviderInterface is only for registering services, not for retrieving
For retrieving service with future altering try to use ServiceModifierInterface


Drupal 8 REST add custom error messages to existing core /entity/user/ resource

You can't return a response from a presave hook. You can however throw an exception, which in a json route will return a json error message:

throw new NotFoundHttpException('Region not found!');

If you want to change the default error response, implement an exception subscriber to catch this exception and return your own response.

For reference the default exception handler: ExceptionJsonSubscriber::on4xx


Optional configuration and order of enable modules on profile

My problem is a bug of the configuration system. An issue exists for this exact problem: https://www.drupal.org/project/drupal/issues/2922417


we have a webform views module
which may help you I suppose


How to search by hierarchical taxonomy in views?

You can use Chosen Module and it supports for hiererchical select

  By default the module will automatically apply itself to any select
  elements that have more than 20 options, which is a reasonable default
  for which having Chosen will be useful. To change or disable this
  automatic enhancement, you can change the selectors (or remove all
  selectors) from the Apply Chosen to the following elements field on
  the Chosen administration page.


Circular Search view not returning results if city exists in UK AND elsewhere

The Geofield proximity Views filter doesn't have any default location settings. The filter passes the given string value on through to the geocoder without any additional settings:

  $geocoded_data_raw = geocoder($geocoder_engine, $location);

As such, your only option is to form alter the submitted data as answered in this question:

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#submit'], 'MYMODULE_form_views_exposed_form_submit');
}

/**
 * Modify submission value with " UK" if given origin has been supplied.
 */
function MYMODULE_form_views_exposed_form_submit($form, &$form_state) {
  if (isset($form_state['values']['field_geofield_distance']['origin']) &&
      strlen($form_state['values']['field_geofield_distance']['origin']) > 0) {
    $form_state['values']['field_geofield_distance']['origin'] .= ' UK';
  }
}


How to get all group content from group?

All the contents are associated in og_membership table. If you can get the gid (group node id), then it will be easier to get the content associated with that group.

$og_contents = db_select('og_membership', 'ogm')
->fields('ogm', array('etid'))
->condition('ogm.gid', $gid, '=')
->condition('ogm.entity_type', 'node', '=')
->execute()
->fetchAll();


How to get ordered list display for Top Emails in Forward Module?

Found Go to forward.module

search for this "function forward_top5_list(" and change

"$query->range(0, 5);" from 5 to 10

this will work


Your form submission handler should take the submitted values from $form_state['values'], not $form. The node object is then available in $form_state['node'].

For such task it would be better to implement hook_node_presave(), which is called right before a node is saved.


Get all nodes of a specific content type and print the data of each node inside page.html.twig

Putting this in page.html.twig is a bad idea. Since this template will be used for every page rendered from Drupal using that theme.

Instead you should simply create a View. Views can be used to query a certain content type and to list nodes in a certain view mode or just certain fields of these nodes (the title and a color field for example). Then configure your view to provide a block and place that block in the region you wanna have the Flowers printed.

Views and block will take care of the caching. And you can use the block's visibility settings to have it displayed only on paths or nodes where you really need it.

If you still insist on coding this in a template (not recommended, too performance-heavy, too much logic in templates) you first have to pass all Flower nodes to the template.

/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {

  $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();

  // Get all Flower node IDs.
  $nids = $query->condition('type', 'flower')->execute();

  // Load all Flower nodes.
  $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  // Pass them to page.html.twig.
  $variables['flowers'] = $nodes;
}

Then in your page.html.twig:

{% for flower in flowers %}
  {{ flower.title.value }}
  {{ flower.field_color.value }}
{% endfor %}


How can I rewrite a content link and replace spaces with dashes?

The field Link to Content can only link to content lol, it doesn't seem you can override the link URL there (that is why there is no Link path field there, Views interface and features can be confusing at times, you have to know a bit of background to understand the less polished parts).

You should Exclude from display the Link to Content field, move the Title field down so it's the last field, and unhide it.

Then you will be able to contruct what you want using the Title field, using the Output this field as a custom link option.

The option Override the output of this field with custom text doesn't provide the option to Replace spaces with dashes.

Make sure that the Link to the Content in the Title field is not ticked, and the Formatter is set to Plain text to avoid clashing between different features when Drupal is constructing the output.


Custom Content Type with Custom Fields creation

I created the content type in a test environment, and populated all of the fields I wanted using the UI.  Then I went to the site configuration and did an export on the entire site. I pulled all of the yml files I needed for the fields and node types, and it works beautifully.


Set default value of field in a field group

I was able to spend some more time on this and figured out that the field group was not where I should be changing the value in the form.

I am using the field group multiple module so the value is not being set at the field or the field group. If using devel, look for something like 'fgm_node_YOURNODE_form_group_YOURGROUPNAME' where YOURNODE will be the name of your content type and YOURGROUPNAME will be the name you gave to your field group. I'm assuming 'fgm' is short for field group multiple.

You will have to travese 'fgm_node_YOURNODE_form_group_YOURGROUPNAME' to find the specific field within the field group multiple that you want to set the default value.

Example:

$form['fgm_node_YOURNODE_form_group_YOURGROUPNAME']['fields']['items'][0][field_YOURFIELD']['und'][0]['value']['#default_value'] = t('Some text');

My form alter code works now.


I would rather implement hook_form_FORM_ID_alter() to alter the form returned by search_box(). If mymodule.module is the name of your module, then you should add the function mymodule_form_search_box_alter(&$form, &$form_state). You need also to replace the form submission handler with your own.

function mymodule_form_search_box_alter(&$form, &$form_state) {
  $form['submit']['#weight'] = 10;

  $form['search_type'] = array(
    '#type' => 'radios',
    '#options' => array(t('Whole site search'), t('Google search')),
    '#default_value' => 1,
    '#weight' => 5,
  );

  // Replace the search.module handler with your own.
  if (in_array('search_box_form_submit', $form['#submit'])) {
    $key = array_search('search_box_form_submit', $form['#submit']);
    unset($form['#submit'][$key]);
  }
  array_unshift($form['#submit'], 'mymodule_search_box_submit');
}

You could also show the form field containing the text to search inline with the radios you add.
The code I reported replaces the form submission handler with mymodule_search_box_submit() that must be implemented from your own module. This is the code executed from the submission handler implemented by search.module; I report it as reference.

function search_box_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_REQUEST['destination'])) {
    unset($_REQUEST['destination']);
  }
  if (isset($_REQUEST['edit']['destination'])) {
    unset($_REQUEST['edit']['destination']);
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/node/' . trim($form_state['values'][$form_id]);
}

As reference, I report here the code of the search.module function that builds the search box form.

function search_box(&$form_state, $form_id) {
  $form[$form_id] = array(
    '#title' => t('Search this site'),
    '#type' => 'textfield',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

  return $form;
}


What you're describing is the expected behaviour for a managed_file widget. If you dig through the functions you eventually get to file_managed_file_save_upload(), which is responsible for actually saving the file.

That function calls file_save_upload() without the 4th parameter, which is $replace.

Since the default for that parameter is FILE_EXISTS_RENAME, file_save_upload() has no choice but to use in that context.

When you refresh the page, the original file that was uploaded has not been cleared up; in fact it won't be until the temp file cron job runs. So Drupal is "correctly" ensuring that the original file doesn't exist, because the managed file field is telling it to rename, not replace, files.


jquery date picker in views exposed filter changes the date values

This is a known issue (bug) of Views. You can find details here: Exposed grouped filter for date not working.


Create a View which shows Nodes AND Taxonomy Terms

Create a view and select show content of type All
Under format in show fields select fields.
3.Create a relationship Content: Taxonomy terms on node
Select Content: Title and  Taxonomy term: Name fields under Fields
Under filter criteria select two fields first one Content: Title  and second one  Taxonomy term: Name and dont forget to check the Expose this filter to visitors, to allow them to change it


How to add HTML5 attribute "autocomplete" to form fields?

I think it's possible to add this attribute to all input fields using a bit of JS, something like this should work:

(function($, Drupal) {
  Drupal.behaviors.autocompleteFieldBehavior = {
    attach: function (context) {
      $(context).find('input').each(function () {
        var name = $(this).attr('name');
        if ($(this).attr('autocomplete').length === 0) {
          if (name) {
            $(this).attr('autocomplete', name);
          }
          else {
            $(this).attr('autocomplete', 'Default autocomplete value.');
          }
        }
      });
    }
  };
})(jQuery, Drupal);

The other solution would be alter all forms using hook_form_alter, see @berramou's comment.


Filter after Custom Field Type in Custom Filter

If you create a new field type, you need to tell Views about it. The hook in question is  https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7

Through entries in this hook you tell views how to build its SQL queries and render the results. Once you have implemented the hook you'll need to clear cache and hopefully you'll see your fields appearing in the list of filters. If the query/render requirements are not addressed by Views' existing handlers, you'll need to write your own. https://api.drupal.org/api/views/views.api.php/group/views_handlers/7


Rules module doesn't send emails to user roles once conditions are met

Attempt to answer this part of your question:

  Any insight to why rules isn't generating emails would be helpful.

I doubt that Rules is the culprit ... and that it is rather something in actually sending the eMails. To verify this, just add a Rules Action to "Show a message" (as the very first Rules Action), and with actual content something similar to the subject / message body as what you have already in the Rules Action to send an eMail. Pretty sure that each time you'll get such extra message shown on your site. If it does indeed, you found a confirmation that there is nothing wrong with your rule itself.

However, just looking at the subject / message body of the eMail you want Rules to send: make sure to also verify that all those tokens (such as node:field_announcement) are available (not blank).

PS: a completely different explanation might be related to your event "after saving content", whereas the saving actually happens ... "before saving content". To verify if that's what your issue is about, replace your Rules Action by an appropriate Rules Component (which does the same thing), and actually "schedule" that Rules Component (using the rules Scheduler) to run after just a few seconds or minutes (at that time, for sure the save will have been completed).


Unable to set placeholder on password input

Wish I'd seen this sooner. You've probably moved on from this problem, but for the benefit of other people seeking an answer to this question: (obviously replace mymodule with the name of your module)

/**
* Implementation of hook_element_info_alter ()
*/
function mymodule_element_info_alter (& $type)
{
  if (isset($type['password_confirm']['#process'])) {
    $func = '_mymodule_process_password_confirm';

    $type['password_confirm']['#process'][] = $func;
  }

  return $type;
}

/**
 * Do a bit of processing for the password_confirm element.
 * Original processing happens in expand_password_confirm()
 */
function _mymodule_process_password_confirm ($element)
{
  // Use the element's title, or create a custom title with the t() function.
  $element['pass1']['#attributes']['placeholder'] = $element['pass1']['#title'];
  $element['pass2']['#attributes']['placeholder'] = $element['pass2']['#title'];

  // Remove these lines if you want to keep the field labels.
  $element['pass1']['#title_display'] = 'none';
  $element['pass2']['#title_display'] = 'none';

  return $element;
}


Well that's  very vast topic, however few things I would like to share with you are:

The best place to start can be the documentation of ZEN theme: https://drupal.org/node/193318. They are having pretty good maintained doc.
Must go through tutorial is drupal's theming guide: https://drupal.org/documentation/theme
To undertand the basics of theming: http://drupalize.me/videos/introduction-theming-basics-drupal-7
How to create the subtheme: here is official doc on how to create a sub-theme as per drupal standard.
Also there is one nice video tutorial on creating a sub-theme of Zen: http://www.youtube.com/watch?v=y-IXpbdgA3A
One good answer on creating a theme with drush command: How do I create a Zen's sub-theme using Drush?
Moving further you can check how do drupal process theme variables for templates: Setting up variables for use in a template (preprocess and process functions)
It would be good to learn few of the CSS frameworks: SASS framework, LESS framework

I tried to cover few of the quick points that striked me first, but anyways there is no limit of learning, so keep on exploring!!


Results of a Views display as an array (D7)

I think it has been replaced by the views_get_view_result() function. It returns:

  An array containing an object for each view item.

e.g.

$result = views_get_view_result('view_name', 'block_1');


How do I set, and return, a value in Views PHP?

It works for me. I put the information you said in a PHP field and it printed out as expected. I imagine it's a caching issue or something else about your site that is causing the issue.


Pre-populate a user reference field during drupal commerce checkout - buying a gift for a user without manual username entry

I don't know ready solution from the box for your use case but it's possible to implement it with Drupal Commerce and Line items functionality.

You can extend Line Item with the user reference field "gift recipient".
User value will be saved on line item but not a product.
Than everything is in your hands.
E.g. you can click on option "Include this field on "Add to Cart" form. Or you can prepopulate this field using special get parameter in the "buy gift for this user" link.

For more information about extending Line Items see the video: http://vimeo.com/31459435


Views: changing the language for taxonomy terms

By default views doesn't allow to filter the taxonomy terms by the language, only with nodes.

But, you can use the Internationalization Views:

http://drupal.org/project/i18nviews

After you enable the module go to relationships and add "Content: Taxonomy terms on node"
Then you can find " Taxonomy term: Language " under filters. This should do the trick.

Good luck.


Using clientside_validation project, default validation plugin message not being overridden for states dependent field

Turns out this is a bug. The hot fix is to add the $message argument to the _clientside_validation_set_equal() call on clientside_validation_fapi.module. So that it looks like:
_clientside_validation_set_equal($name, $title, $params[0], $js_rules, $message);.

I've started an issue and submitted a patch https://drupal.org/node/2140163


Class 'Drupal\user\Entity\User' not found when running drush

I had the same problem, it's related to the Drush version used by the DrupalVM.
You can change the Drush version in the config.yml file.

More info: https://github.com/geerlingguy/drupal-vm/issues/1020


advagg drupal module breaking my js file

You do not need to add document.ready to a behavior.
Read about drupal behaviors HERE or at a good blog post HERE.
Basically I think Drupal adds a document.ready which calls all the behaviors. The behaviors are also called after an ajax call is returned (sending the new content returned by the ajax to the behaviors via the context variable). Which is why we use the context variable in the jquery selector.
Your javascript should probably look like this.

(function ($) {
  Drupal.behaviors.myfunction = {
    attach: function (context, settings) {
      $('#gl_img_datepicker', context).datepicker({
        onSelect: function(dateText, inst) {
          alert(dateText);
        }
      });
    }
  };
})(jQuery);


I've got answer from drupal.org and this is the right solution:

<?php
if(isset($user->roles[5]))
{
  echo l(t("My offers"), 'user/' . $user->uid . '/offers');
}


Your idea to rebuild the menu cache on each login would certainly be resource intensive, but it would moreso just not work either as the cache is system wide and isn't somehow custom cached across page loads of a user, so, once someone logged in, it would be rebuilt and then accessible to both that as well as any other currently logged in user.  Then, when the next user logged in, it would be rebuilt for all to use by everyone logged in, etc etc etc.

But, you could rather easily as you intimated do this with php inside a new page callback, eg, something along the lines of...

if ( /* users we are looking for is TRUE */ ) {
  // use our new callback
} else {
  // call original callback
}

By doing it inside the callback, you wouldn't be duplicating menu paths, eg, not having module/callback1 and module/callback2 but rather module/callback in itself would do things differently based upon your new logic...much like how going to user as an anonymous user presents a login page, but going to it once logged in presents your profile.

ADDITION:

Given additional commentary, you most probably could overload/overuse the capabilities of hook_translated_menu_link_alter() to accomplish this, eg, something like:

function YOURMODULE_menu_link_alter(&$item, $menu) {

  if ( /* whatever is true for your $item */ ) {
    $item['options']['alter']=TRUE; // Flag this link as needing an alter at display/run time.
  }

}

and then

function YOURMODULE_translated_menu_link_alter(&$item) {

  if ( /* whatever is true for your $item */ ) {

    // do whatever you want to do to it, eg...

    if ( /* this is a special user */ ) {
      $item['localized_options']['attributes']['class']='foo';
    }

  }

}


I think it is:

setsebool -P httpd_can_network_connect on


How to filter content (admin view) based on taxonomy term

Using [Administration Views] https://www.drupal.org/project/admin_views you should be able to enable or extend an existing view.  I have done it for content but have had trouble with that module and had to revert a few times.


Nice menu works in same way as you required. Did you configured this module correctly?

First you need to look into configuration of this module(Nice menus).

After that you need to configure your nice module correctly in block list as in attached image. If still error persists then look for JS error.


Can't get data from drupal_http_request result

I got it working myself.
Kudos to Clive who mentioned that the data is binary which probably means why I can't view it with dpm().

In closure, here is a code example to fetch a zip file with drupal_http_request where you can set header information.

function MY_MODULE_download_zip($service_url, $token, $request_body) {
    $request_headers = array(
        'Content-Type' => 'text/xml', //sending additional data as XML
        'Content-Length' => strlen($request_body), //See options['data']
        'charset' => 'utf-8',
        'loginToken' => $token, //I needed to pass a login token
        'Cache-Control' => 'no-cache',
        'Pragma' => 'no-cache',
        'Connection' => 'keep-alive'
    );

    $options = array(
        'method' => 'POST',
        'headers' => $request_headers,
        'data' => $request_body, //I needed to pass more info here as a XML
        'timeout' => 60.0, //it's a big file
    );
    $result = drupal_http_request($service_url, $options);

    if ($result->code != 200) {
      watchdog('ERROR', 'ERROR: :error', array(':error' => $result->error);
      return FALSE;
    }

    $temp_filename = "my_zip_file.zip";
    $zip_file = fopen($temp_filename, "w+");
    fwrite($zip_file, $result->data);
    fclose($zip_file);

    return TRUE;
}


Show specific articles when clicking on tag

Give the page view a contextual filter for the taxonomy term field in question and click "Specify validation criteria", then choose the "Taxonomy term" validator, select your vocab, and select "Term name converted to Term ID" for the "Filter value type" setting, like this:

Then in your tags view, for your term name field, select "Output this field as a link" and set the "Link path" to be the path of your page view, with the term name on the end for the contextual filter, like so ([name] is the term name field in my case):

- Note that if this is a content view instead of a taxonomy term view you will have to add a relationship for your taxonomy term field before you can use the term name field. In your case the relationship should be "Content: Tags".

This would be the same for other entities, for example if your view was a user view and the user had the  tags field on it.

Alternatively you could use the term ID contextual filter and term id field instead of using term name and the convert term name to term id option.

I prefer the term name as it looks nicer than term id in the url, but if you have really long term names or they have strange characters in them or anything the term id might be preferable.


How do i verify users passwords from the hash in the database without drupal core logic

A long time ago, I had to move from one system to another and there was a similar concern about migrating hashed passwords. I set up things to check for a password in the new system. If one exists, authenticate against it. If not authenticate against the old system, as it seems you're already doing with Drupal. However, instead of just handing out the cookie, use the opportunity to store whatever was sent in the new system, or physically take the user to a "verify your password" in the new system, and get it saved properly there.


Display an image through page.tpl.php only on front page

Rather than editing in page.tpl.php which applies on all pages, you should create a template file called page--front.tpl.php and add image there if you want to display the image only in front page.

EDIT

For more theme hook suggestions refer this page


Where to place PHP code for a node if not in the node body block itself?

One of two places, hook_node_view() or hook_preprocess_node(). They can both be used in a module file, but only the latter will work in your theme's template.php file.

hook_node_view() example:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_node_type') {
    $args = array(':nid' => $node->nid);
    $my_value = db_query('SELECT my_field FROM {my_table} WHERE nid = :nid', $args)->fetchField();

    $node->content['my_value'] = array(
      '#markup' => 'My value is: ' . $my_value,
      '#weight' => 10 // Controls the display order of this piece of content
    );
  }
}

hook_preprocess_node() example:

function MYMODULE_preprocess_node(&$vars) {
  $vars['content']['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}


How to use form_set_value for a select list field?

<?php form_set_value($form['field_statut_metier2'][LANGUAGE_NONE], array(0 => array('value' => 2)), $form_state); ?>

From the form_set_value() documentation on the first argument:

  you can just pass in the element from the $form array, although the only component that is actually used is '#parents'

Alternatively you can do:

<?php $form_state['values']['field_statut_metier2'][LANGUAGE_NONE][0]['value'] = '2'; ?>

... which is what form_set_value() does anyways.


Show parents at first level then child in each page

If I am understanding your requirement correctly, you want to display "Parent Term" in top of the view page and when user click on any "Parent term", you want to display child of that term in the same page.

I have created a views and add attachment to display "Parent term" in top of the page. I have added "Taxonomy Vocabulary" filter, so please change filter in views as per your requirement.

Exported version of the view:

$view = new view();
$view->name = 'test_category';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Test Category';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test Category';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Parent term */
$handler->display->display_options['relationships']['parent']['id'] = 'parent';
$handler->display->display_options['relationships']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['relationships']['parent']['field'] = 'parent';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Taxonomy term: Parent term */
$handler->display->display_options['arguments']['parent']['id'] = 'parent';
$handler->display->display_options['arguments']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['arguments']['parent']['field'] = 'parent';
$handler->display->display_options['arguments']['parent']['default_action'] = 'empty';
$handler->display->display_options['arguments']['parent']['default_argument_type'] = 'taxonomy_tid';
$handler->display->display_options['arguments']['parent']['default_argument_options']['node'] = TRUE;
$handler->display->display_options['arguments']['parent']['default_argument_options']['vocabularies'] = array(
  'product_category' => 'product_category',
);
$handler->display->display_options['arguments']['parent']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['parent']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['parent']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  3 => '3',
);
/* Filter criterion: Taxonomy term: Term ID */
$handler->display->display_options['filters']['tid_raw']['id'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['tid_raw']['field'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['relationship'] = 'parent';
$handler->display->display_options['filters']['tid_raw']['operator'] = 'not empty';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-category';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Taxonomy term: Term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['default_action'] = 'summary';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['count'] = FALSE;
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['tid']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['tid']['validate']['fail'] = 'summary';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  3 => '3',
);
/* Filter criterion: Taxonomy term: Term ID */
$handler->display->display_options['filters']['tid_raw']['id'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['tid_raw']['field'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['relationship'] = 'parent';
$handler->display->display_options['filters']['tid_raw']['operator'] = 'empty';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['inherit_arguments'] = FALSE;


How to pass multiple IDs to a Views exposed filter?

You can pass it using contextual filter,

Remember to choose multiple selection

if we have url http://example.com/test/20+10+12