# Question
Title: drupal_render() vs drupal_render_children()?
What is difference in functionality between drupal\_render() and drupal\_render\_children() ? When I used drupal\_render for $form derived as follows from hook\_theme

```
function hook_form_alter($form,&$form_state,$form_id) {
if ($form_id == 'content_type_a') {
  $form['#theme'][] = 'custom_content_type_a_node_form';
}

}

function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
       'render element' => 'form',
    );

}

```

Then inside a THEMENAME\_custom\_content\_type\_a\_node\_form

```
function THEMENAME_custom_content_type_a_node_form(&$variables) {
$output = '';
$form = $variables['form'];

$output = <div>Some HTML code</div>;

$output .= drupal_render($form);

return $output;
}

```

While using drupal\_render in the above function the page was going into loop and function was being called by endlessly
But when I replaced that with drupal\_render\_children($form) it did not go into an endless loop
What is the reason for such a behavior?

# Answer
`drupal_render()` renders an item. Rendering it contains theming it. Look into function's code, there is this line:

```
// Call the element's #theme function if it is set

```

So placing render inside theming function is bound to make a loop. `drupal_render_children()` exist to break this loop - it renders element's children only, so you can print element itself in theming function and still have children themed by their own proper functions.
> 3 votes

# Answer
Actually this is a bug that is still haunting us in Drupal 8:

And likely it could still be backported to Drupal 7.

However currently using drupal\_render\_children() is the only way.
> 0 votes

---
Tags: 7
---


# Question
Title: Editing field twig template for taxonomy term
I would like to edit `field.html.twig` for `taxonomy-term.html.twig`. I've tried `field--taxonomy-term.html.twig` and a bunch of other options, none of them seem to work. What is the correct naming convention?

Clarification: I mean the template for fields used on the taxonomy term page, not the fields used in content type to reference a taxonomy.

# Answer
The field type for taxonomy terms is `entity-reference`. You can use the field type for the naming of the field twig:

```
field--entity-reference.html.twig

```

Because there may be more than one reference field, it is more specific to use the field name, for example a twig for the preinstalled tags field:

```
field--field-tags.html.twig

```

If you want to use the target entity of a reference field as theme suggestion you would have implement this in a hook.

**Edit acc. to the clarification:**

If the field is inside of a taxonomy term, you have to add one more detail, either the field name or the name of the vocabulary:

```
field--taxonomy-term--field-body.html.twig
field--taxonomy-term--tags.html.twig

```
> 2 votes

---
Tags: theming, 8, entities
---


# Question
Title: What was killed after the installation and enabling of Devel with Drush 7?
I installed the Devel module in a Drupal 7 site via Drush. After installing and enabling the module, I got an error message which simply said *Killed*.

>

What does that mean? What was killed?

I have installed modules with Drush many times. This is the first time I get an error message like that.

# Answer
> 2 votes
After some chat-back-and-forth, I'm of the mind that this isn't Drupal or Drush related, but, rather, when you enabled the Devel module, your OS killed a process to manage a limited memory condition. Linux kernels will perform memory management by killing processes Adding a module will increase PHP memory, albeit temporarily, and your OS killed a process to manage the spike. I'm curious if you see whether there are "memory exhausted" entries in your site's logs — or, more likely, these will be occurring at the OS level. Stack memory exhaustion isn't too unusual on a low-RAM setup, or where your requested memory allocations, such as explicit Apache, PHP, MySQL or APC memory requests, use up too much memory, and the OS struggles to achieve a running state.

Try reducing your PHP memory allocation in conservative intervals, say, 16 MB, from 256 to 240 to 224, etc. Then test your changes while crawling your whole site to ensure nothing breaks. I'd do this on a staging server that replicates your live server, since the OS impacts how much memory your site will consume. For your site crawl, you can use a site crawler like XENU (Win only) with the Memory Profile module to see what page makes the highest memory request — and then add, say 48 MB on top of that, which should suffice. It is, however, an inexact process, since you must deal with a random number of random page requests.

# Answer
> 2 votes
In my case, increasing the value of memory\_limit in php.ini solved the problem.

I had 128M and I just changed to 512M, for testing purposes, and the "Killed" message just disappeared.

Of course, don't forget restart your web server after that change.

---
Tags: drush
---


# Question
Title: drush cc segmentation error when clearing theme-list
I'm working on Vagrant/Virtual box and get a segmentation error when I `drush cc` theme list (8).

I'm new to Drupal and Vagrant and have no idea what this means. Would anyone be able to point me in the right direction?

Thanks

# Answer
> 0 votes
This turned out to be a problem with the Drush installation on my Vagrant box.

---
Tags: 7, drush, caching
---


# Question
Title: Custom node add/edit form - How to leave value of undisplayed field as set?
I have a person node. There are some internal fields only the admin can change (e.g. Internal person code). Some other fields users with certain roles can change (e.g. first name...).

I have built a custom page using panels for this; I added the desired fields for normal users to the panel and Then I added a selection rule to the variant, enabling the variant for the normal users.

When a normal user opens the form and saves it, the internal fields, which only should be edited by the admin are set to NULL, because they were not submitted of course.

Is there any setting I missed? I don't want to add all the internal fields.

Thanks.

# Answer
> 1 votes
After some research I found out, that it is very important to have the full node form be added to the panel to get all fields (like publishing option, date created...), so the submit routine gets data for all node fields.

You can show/hide fields for certain roles using the Field Level Permission Module for the standard Drupal roles. But I like to use the OG roles to define the permissions. There is already an OG function for this under `admin/config/group/permissions`.

I did it this way:

1. Activate the node/%/edit page under pages
2. Create a variant for editing node of a certain type
3. Add all required fields, which should be shown to the normal user to the form and layout it
4. Add the submit buttons to the form
5. Add `General Form` to the panel, so that all fields, which are not build before are added to the form (like publishing status, author, date created...)
6. Goto `admin/config/group/permissions` and set the edit rights for the fields, the normal user should not see. The fields then are not on the node form anymore, but the values remain in the database.

I hope that helps someone else.

# Answer
> 0 votes
If it's a custom form, use the #access property to set the values.

```
$form['some_field'] = array
(
  '#type' => 'textfield',
  '#title'=> t('Enter a value'),
  '#default_value' => $node->some_field,
  '#access' => user_access('edit_some_field'),
);

```

---
Tags: forms, panels
---


# Question
Title: In which folder should I install Composer on a shared linux server?
The "Questions that may already have your answer" do give various instructions on how to install Drush and/or Composer, but they don't address my question. I did come across this comment:

Q: drush - which folder for install on VPS / root server (newbie): A: "You can install Drush in the folder of your choice. Preferably outside www-directory."

My question: I'm not sure if this is applicable to Composer as well? And if it is applicable to Composer as well, why do people give specific folders into which Composer must be installed into?

The reason for my concern into which folder I install Composer is because I want to run it without problems (in any case with as little as possible).

I'm listing the different options:

1. mdir bin, cd bin, install Composer in \[~/bin\] directory.
2. Install in /home/username/bin
3. Install in \[~/bin\] and move to /usr/local/bin
4. Install in the /usr/local/bin folder That is a hidden folder, I can access it if I say "cd /usr/local/bin" in my terminal, but it doesn't show in the file manager of cpanel. How does that relate to /home/username/bin (or doesn't it)?
5. Install in the public\_html folder (home/username/public\_html)
6. One article says that Drupal is installed in the /var/www/drupal folder.
7. Another articles says that Drupal is installed in domains/websitename.com/htdocs/www

It seems to me that the \[~/bin\] directory is the preferred one?

# Answer
> 2 votes
**TL;DR** My recommendation would be `/usr/local/bin`

It doesn't really matter as long as the directory is in the `PATH` of all users, and as long as it is not one of the locations which the OS wants full control over (those would be primarily `/usr/bin` and `/bin`). For most situations, a reasonable location is `/usr/local/bin` because it should already be in the system's default `PATH` and it is intended precisely for this purpose -- local installations which are not part of the OS proper.

For Linux, you might want to refer to the LHS entry; this standard codifies usage inherited from the original Unix.

If it's convenient for you, installing in `$HOME/bin` and then moving to a system-wide location is fine. In fact, most `make install` etc facilities expect you to be doing something like this.

# Answer
> 0 votes
If you want to install Composer on a shared linux server, do it in the /bin directory if you want it to be used by all cPanel users.

The /bin directory is existing but hidden, just type "cd /bin" (with the slash!) on your command line to get to it.

---
Tags: 8, composer
---


title: Upload multiple media entities at once

text:
# Question
Title: Upload multiple media entities at once
Is there any solution yet which allows me to upload multiple media entities at once? At the moment I've to

* Select a file
* Upload it
* Select the next file
* Upload this

Especially for a gallery, where I've to upload a lot of images, this can be very annoying.

I really like to use the media entity module for this job because this way I can reuse all the images I've already uploaded in my gallery for other content.

# Answer
> 1 votes
Have you already checked the PlUPload module ?

It's still -dev, but should work ..

Another approach could be: Using IMCE browser, that already allows multi-file uploads in combination with filefield\_sources, you should then be able to select the uploaded images for your gallery field and others.

> More sophisticated is the media(-entity)-suite, there's dropzoneJS in place.

---
Tags: 8, media
---


# Question
Title: How to create a rule to send email to users of a role that belongs to a country?
I'm using Profile2 module to assign a Country to a Role. For example I have:

* User1 | Role: "International Members" | Country: "UK"
* User2 | Role: "International Members" | Country: "Poland"
* User3 | Role: "International Members" | Country: "Japan"
* User4 | Role: "International Members" | Country: "US"

My content also has a field Country.

I have this **Rule**:

**Events**:

* After saving new content
* After updating existing content

**Conditions**:

* Content is published

**Actions**:

* Send mail to all users of a role (International Members)

That is sending email to all users in Role "International Members". I would like to:

1. Lookup the Country of the content
2. Send email to only those "International Members" whose profile Country matches the one of the content.

So If I publish a content with Country set as "US" it should only send an email to User4.

Any idea?

# Answer
You need to use the action "fetch entity by property" and then use the country field and supply the country.

That will create a list to loop through so you can send mails.
> 2 votes

# Answer
To make this work you may want to give it a try to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

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

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

* It should include an appropriate filter of the Country.
* It should have exactly 1 result (row) for each user to be eMailed.
* One of the columns should be the eMail Id (I don't see other columns needed for this to work).

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

# Answer
In the end I ended up doing custom **Action** for **Rules** module

```
function rulesemailsamecountry_rules_action_info() {
$actions = array(
    'rulesemailsamecountry_action_sendemailroleandcountry' => array(
        'label' => t('Send mail to all users of a role that match country node'),
        'group' => t('Custom'),
          'parameter' => array(
            'roles' => array(
              'type' => 'list<integer>',
              'label' => t('Roles'),
              'options list' => 'entity_metadata_user_roles',
              'description' => t('Select the roles whose users should receive the mail.'),
            ),
            'subject' => array(
              'type' => 'text',
              'label' => t('Subject'),
              'description' => t("The mail's subject."),
            ),
            'message' => array(
              'type' => 'text',
              'label' => t('Message'),
              'description' => t("The mail's message body."),
            ),
            'from' => array(
              'type' => 'text',
              'label' => t('From'),
              'description' => t("The mail's from address. Leave it empty to use the site-wide configured address."),
              'optional' => TRUE,
            ),
          ),
      'base' => 'rules_action_mail_to_users_of_role_by_country',
      'access callback' => 'rules_system_integration_access',
    ),
);

return $actions;
}

function rules_action_mail_to_users_of_role_by_country($roles, $subject, $message, $from = NULL, $settings, RulesState $state, RulesPlugin $element) {

  $from = !empty($from) ? str_replace(array("\r", "\n"), '', $from) : NULL;

  // All authenticated users, which is everybody.
  if (in_array(DRUPAL_AUTHENTICATED_RID, $roles)) {
    $result = db_query('SELECT mail FROM {users} WHERE uid > 0');
  }
  else {
    $rids = implode(',', $roles);
    $country_code = $state->get('node')->value()->field_country['und'][0]['iso2'];
    // Avoid sending emails to members of two or more target role groups.
    $query = "
    SELECT
    DISTINCT u.mail
    FROM {users} u
    INNER JOIN {users_roles} r ON u.uid = r.uid
    INNER JOIN profile p ON p.uid = u.uid
    INNER JOIN field_data_field_profile_country c ON c.entity_id = p.pid
    WHERE r.rid IN ('".$rids."')
    AND c.field_profile_country_iso2 = '".$country_code."'";

    $result = db_query($query);
  }

  // Now, actually send the mails.
  $params = array(
    'subject' => $subject,
    'message' => $message,
  );
  // Set a unique key for this mail.
  $name = isset($element->root()->name) ? $element->root()->name : 'unnamed';
  $key = 'rules_action_mail_to_users_of_role_' . $name . '_' . $element->elementId();  $languages = language_list();

  $message = array('result' => TRUE);
  foreach ($result as $row) {
    $message = drupal_mail('rules', $key, $row->mail, language_default(), $params, $from);
    // If $message['result'] is FALSE, then it's likely that email sending is
    // failing at the moment, and we should just abort sending any more. If
    // however, $mesage['result'] is NULL, then it's likely that a module has
    // aborted sending this particular email to this particular user, and we
    // should just keep on sending emails to the other users.
    // For more information on the result value, see drupal_mail().
    if ($message['result'] === FALSE) {
      break;
    }
  }
  if ($message['result'] !== FALSE) {
    $role_names = array_intersect_key(user_roles(TRUE), array_flip($roles));
    watchdog('rules', 'Successfully sent email to the role(s) %roles.', array('%roles' => implode(', ', $role_names)));
  }
}

```
> 1 votes

---
Tags: 7, rules, emails
---


# Question
Title: How can I use the same render cache but for json?
I am working on REST API and I would really like to be able to use the same mechanism for responses as Drupal uses for cached content.

Unfortunately there is no render cache, everything is JSON responses. So there are no #ccache setting or page cache policy to be applied out of the box.

So I wonder if it is even possible and if so **how should I approach it**?

What I'm after basically is to cache the responses in the same manner as entities for example. So if the context is specific user and I am displaying entity information I would like to get fresh information if the entity is changed but the same content if not and the user is the same..and so on.

# Answer
You have to use a cacheable response and then you can add cacheable metadata from a render array or from an object directly:

```
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;

  $response = new CacheableJsonResponse($json, 200);

  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));

  $response->addCacheableDependency($entity);

```

If you use the core REST API this should already be implemented.
> 3 votes

---
Tags: 8, caching
---


# Question
Title: Entity reference field definition to auto create entities
I have a field definition set up like below. I want Drupal to do all the heavy lifting for me, so my definitions are minimal and rely on Drupal defaults:

```
    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setSettings([
            'target_type' => 'target_entity',
            'handler' => 'default',
            'handler_settings' => [
                'auto_create' => true,
            ],
        ])
        ->setDisplayOptions('form', array(
            'weight' => $weight,
        ));
    ;

```

`target_entity` is just a simple bundleless entity.

This creates an entity reference auto-complete field in forms, but if I type something that doesn't match any existing entities, Drupal will say that no matching entities found and will refuse to create a new one.

How do I make the `auto_create` setting work?

# Answer
The answer is 'you cannot auto-create bundle-less entities in Drupal 8.2.0. I don't know if this is a bug or a feature, but you have to have a bundle for target entity ('all\_target\_entities' in my example) and indicate that as target bundle in the settings:

```
$fields[$field] = BaseFieldDefinition::create('entity_reference')
    ->setSettings([
        'target_type' => 'target_entity',
        'handler' => 'default',
        'handler_settings' => [
            'auto_create' => true,
            'target_bundles' => [
                'all_target_entities' => 'all_target_entities',
            ],
        ],
    ])
    ->setDisplayOptions('form', array(
        'weight' => $weight,
    ));
;

```

I think it was not the case up to some point, so stating the exact version I am having this issue with.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Should I be using node_load() rather than building my own queries with db_select()?
I'm fairly comfortable with using Drupal 7 functions like `db_select()`. While `node_load()` is obviously very easy to use, I often find that it returns fields I don't need and doesn't provide fields that I do need (field that would require some `join`s to obtain).

Therefore, will building my own queries provide better performance than using `node_load()` in conjunction with other queries? Or is there some kind of performance boost that results from using `node_load()`, perhaps from cacheing, etc.?

I'm far from an expert on MySQL performance issues, but it seems to me that constructing a single, specific query is better than using multiple queries that individually only retrieve part of what I ultimately need (and a lot of what I don't).

# Answer
Technically, yes, writing your own `db_query()` statements will return the data faster and with less overhead. However, it is not really the "Drupal way" to do things.

`node_load()` provides a 'static' cache; in other words, if you load the same node twice in one page request, it will only hit the DB once.

What you are really missing out on by not using `node_load()` is all the API hooks and third-party module integration. If you need a CCK field, `node_load()` gets all that data for you, where as a manual query would require a lot of joins.

As you note, there is a lot of extra processing/loading going on that you may not need at the given moment. If you don't need the data, it won't technically hurt you not to have it. It is really up to you if you want to go this route.

The biggest reason IMO for using `node_load()` even though you might not need the extra data is just for the purpose of standardization. You won't have to worry about what pieces of data you have at a certain point. You will have a fully loaded node and will have more options for adjusting the data as necessary through `hook_nodeapi()`. Other developers looking at your code will have an easier time understanding what they are working with. Also, 6 months down the road when you go to add a new feature/display field you wont have to adjust your queries.

node\_load is definitely a resource hog, but i have found it better to use in my experience. Drupal 7 greatly improves the situation by providing node\_load\_multiple() which, as its name implies, reduces the number of queries when loading multiple nodes.
> 13 votes

# Answer
As explained in jakarska's answer, `node_load()`, `node_load_mutliple()` do more than just DB querying. They take care of calling all the *node building* hooks implemented by the enabled modules of your site.

In addition, in Drupal 7, with the introduction of pluggable field storages, when working on re-usable code, you can't known whether or not your field data will be available in your (main) database. As a general rule, I would use `node_load()`, `node_load_mutliple()` and `EntityFieldQuery` to query for nodes. If you only need a specific field for multiple node you can also use `field_attach_load()` with an `$options['field_id']` on the results of an `EntityFieldQuery`.

So, I wouldn't go for a custom SQL query unless the code is sure to be used in cases where everything that `node_load()`, `node_load_mutliple()` and `EntityFieldQuery` provide are not, and will never be, needed and on data that are, and will always, be stored in the SQL database.
> 5 votes

# Answer
`node_load()` is the "Drupal way"; it means that, by calling this function, the API sends message to modules when node loading has started, so these can add/change/remove their own information. Yes, even `node_load()` uses caching, as it uses a lot of queries.
You can use `db_select()` for selecting concrete data, but be sure that you collect/change/delete correct data.
> 1 votes

# Answer
You can carefully build a view to filter and relate what you want and then use views\_get\_view\_result() function to get the result.

And by carefully I mean that you only use the fields you need. For example, including a field of node title with a link to it's node will make your query considerably longer in views instead of only using node id without a link.

Views is a powerful query builder and using it programmatically could be a good answer to your problem. You can get the best of both worlds: easy queries that are friendly with Drupal and faster results compared to loading all data from a particular entity.

You must configure your views module to see the generated queries when building it. Also you could find useful to name or tag your views as "system" or something like that, to avoid undesirable overrides.
> 0 votes

---
Tags: database, nodes
---


# Question
Title: How to log in users without credentials?
We need to integrate a CRM into our Drupal site. Storing users in native database is forbidden, so we won't store users in our Drupal database, we will use CRM for that.

But we still need to be able to login/register users from drupal standard login/register forms. On a backend we need to login/register user programmatically so user would think he's logging in/registering on a site, instead he logs in/registers in CRM (which is a third party application).

# Answer
> 1 votes
You can do it like this:

```
global $user;
$user = user_load($uid);

```

Where the $uid is the User ID of the user you want to log in.

Note that this potentially opens you up to major security issues.

# Answer
> 0 votes
What you are looking for requires single sign on kind of functinality which user information and authentication process will be done by third party system which is neither of Drupal and CRM, now this third party could be SAML or anything else. Drupal has SAML integration, the same you might need to implement at your CRM level.

Know how SAML works

---
Tags: 7, users
---


# Question
Title: Checking where are users coming from to the landing pages
We have a site that contains few "landing pages" of different campaings. Links to those landing pages are sent by newsletter. Now if user visit one of the landig pages I would like to programatically recognize if he is coming from outer source (from newsletter link) or is just browsing the site. Is it possible to recognize if the page is opened from email?

One of the solution could be to append a GET parameter to the newsletter links, but I'm afraid it will be not a good idea to force our customer to do it everytime. The other solution could be to check REFERER, but I'm not sure how reliable is this. If I could to decide that user is coming from outer source it could be enough.

What could be a suitable solution for this task?

# Answer
> 1 votes
If you are able/willing to add some type of query parameters, you should be able to make this work using the Rules module, as detailed below.

Assume a path like `/index.php?campaign=123`) you can make the value (= `123`) of the URL argument (= `campaign`) available as a new variable to the Rules module. To do so, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

---
Tags: 7, users
---


# Question
Title: Why do I need to rebuild the route cache to make my module work?
I have a Drupal 8 module that allows banning a user by country.

In the module, I mimic Drupal's 7 hook\_init() in the following way:

```
class IpBanSubscriber implements EventSubscriberInterface {

  /**
   * The user's ban value.
   */
  private $banvalue;

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('hookInit');
    return $events;
  }

  /**
   * MyModule
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The event to process.
   */
  public function hookInit(GetResponseEvent $event) {
    \Drupal::service("router.builder")->rebuild();
    $this->iPBanSetValue();
    $this->iPBanDetermineAction();
  }

  /**
   * Function sets user's ban value (if any).
   *
   * Load the user's country code based on their IP address, then check if
   * that country is set to complete ban, read-only, or has no access
   * restrictions. We then do the same for any additional read-only or complete
   * ban IP addresses added. If the user matched a country or an IP address
   * entered, then they are shown a message and/or redirected based on complete
   * ban or read-only.
   */
  private function iPBanSetValue() {
    // If code is being run from drush, we don't want to take any action.
    if ((PHP_SAPI === "cli") && function_exists('drush_main')) {
      return;
    }
    // If user has permission to bypass ban, set to IP_BAN_NOBAN and return
    if (\Drupal::currentUser()->hasPermission('ignore ip_ban')) {
      $this->banvalue = IP_BAN_NOBAN;
      return;
    }
    $test_ip = \Drupal::config('ip_ban.settings')->get('ip_ban_test_ip');
    // Grab the test IP address or the user's real address.
    $ip = empty($test_ip) ? \Drupal::request()->getClientIp() : $test_ip;
    $country_code = ip2country_get_country($ip);
    // Determine if the current user is banned or read only.
    // Individual IP complete ban trumps individual read only IP, both of which
    // trump a country setting.
    if (!isset($this->banvalue)) {
      $banvalue = (int) \Drupal::config('ip_ban.settings')->get('ip_ban_' . $country_code);
      $this->banvalue = $banvalue;
      // Check the read-only IP list.
      $readonly_ips = \Drupal::config('ip_ban.settings')->get('ip_ban_readonly_ips');
      if (!empty($readonly_ips)) {
        $ip_readonly_array = explode(PHP_EOL, $readonly_ips);
        if (in_array($ip, $ip_readonly_array)) {
          $this->$banvalue = IP_BAN_READONLY;
        }
      }
      // Check the complete ban list.
      $banned_ips = \Drupal::config('ip_ban.settings')->get('ip_ban_additional_ips');
      if (!empty($banned_ips)) {
        $ip_ban_array = explode(PHP_EOL, $banned_ips);
        if (in_array($ip, $ip_ban_array)) {
          $this->banvalue = IP_BAN_BANNED;
        }
      }
    }
    return;
  }

  public function getBanValue() {
    return $this->banvalue;
  }

  /**
   * Function determines action based on current user's ban setting.
   */
  private function iPBanDetermineAction() {
    if ($this->banvalue == IP_BAN_READONLY) {
      $uri = \Drupal::service('path.current')->getPath();
      if (($uri == 'user') || strpos($uri, 'user/') !== FALSE) {
        $path = \Drupal::config('ip_ban.settings')->get('ip_ban_readonly_path');
        $response = new RedirectResponse($path);
        $response->send();
        exit;
      }
    }
    if ($this->banvalue == IP_BAN_BANNED) {
      // Always allow access to the banned page.
      $complete_ban_path = \Drupal::config('ip_ban.settings')->get('ip_ban_completeban_path');
      if (!empty($complete_ban_path) && \Drupal::service('path.current')->getPath() != \Drupal::service('path.alias_manager')->getPathByAlias($complete_ban_path)) {
        $response = new RedirectResponse($complete_ban_path);
        $response->send();
      }
      else {
        drupal_set_message(t(\Drupal::config('ip_ban.settings')->get('ip_ban_completeban')), 'error');
      }
    }
  }

}

```

If I don't add the code `\Drupal::service("router.builder")->rebuild();` in the `hookInit()` function, the module works the first time I attempt to access a page (in that it properly redirects to the page that shows a message if the user is attempting to view the site from a banned country), but if I try to access the page a second time, it allows access.

Any thoughts as to why I need to clear the router cache with every page load?

# Answer
> 1 votes
You need to set the correct priority

```
$events[KernelEvents::REQUEST][] = array('hookInit', 255);

```

so that your event runs before other actions like caching.

This only works for logged in users. For anonymous requests you need a middleware. But the problem is, in a middleware the drupal kernel is not loaded yet.

So this could be a plan:

Use both, a middleware and an event.

In middleware block anonymous users.

An example from the Ban module:

http://cgit.drupalcode.org/drupal/tree/core/modules/ban/src/BanMiddleware.php

Or let them have access to a landing page.

There the user in the correct ip range gets a session, either by clicking on a link or automatic redirect, which gives him read-only access.

Anonymous users with a session cookie can be handled in an event with the drupal kernel loaded.

There you can handle all users that are not blocked in the middlware. Anonymous with an account and session properties or logged in with all properties of the current user.

---
Tags: 8
---


title: Check if ajax in the preprocess_node

text:
# Question
Title: Check if ajax in the preprocess_node
There seems to be a problem when I check if the node is served by ajax or not, I use this function :

```
function mytheme_preprocess_node(&$variables) {
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $variables['is_ajax'] = true;
    }else{
        $variables['is_ajax'] = false;
    }
}

```

The same code works great with **preprocess\_page** or **preprocess\_html**

Is there a way to make it work? or eventually get the page/html variable in the node preprocess ?

Thank you !

# Answer
> 4 votes
The node is cached and this function is only called for the first time the node is displayed for the given view mode.

If you really need to vary your output between ajax and non-ajax context, you need to add a cache context for that. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts and the other related documentation pages. You could use the header:NAME-OF-THE-header cache context I guess.

As an alternative, do whatever needs to be done differently with ajax vs not with Javascript/CSS

---
Tags: theming, 8, ajax
---


# Question
Title: Is every image style I have for each image upload auto-created?
I believe I understand this about Drupal 8: every image uploaded will automatically be created in each of the image styles I have set up (or the default 3 that come with core).

This incentivizes me NOT to create very many image styles, because then I'll end up with a bunch of different copies of my original image, whether they will ever be used in that particular style or not.

Is that correct?

On the other hand, Molot's answer over here mentions that "styled image files are supposed to be created on first access". That gives me hope that if I upload an image, it will only be created in an image style the first time it is requested in that image style. That means I could have as many custom image styles as I need and not worry that an image will be created for each one of those every time.

For example, if I have 12 custom image styles, but I only call a certain image in one style, will I end up with only 2 copies of the image, one as the original upload and one in the only style I called? This is what I would love to be true.

Thanks for any insight.

# Answer
The styled images will be created on first request, creating a new file with the styled image. This will not only save space if you have tons of image styles but also CPU power - because if you attach 10 images to a node and want to create 12 (as you mention the number) different image styles, that will put quite a load to generate all the styled images in one go. Doing this when needed is far better management of resources.
> 3 votes

---
Tags: 8, media
---


# Question
Title: Trying to update taxonomy menu item with hook_taxonomy_menu_update
I'm having issues getting this to function to work, if I understand correctly this hook fires after saving or creating a taxonomy term.

I am also unable to use dpm($item) as nothing is rendered

```
function form_alter_taxonomy_menu_update(&$item) {
    $item['options']['attributes']['class'] = 'myClass';
    return $item;
}

```

Can anyone spot what I have done wrong

# Answer
> 0 votes
If you're just adding a class, I wouldn't rely on a hook from the taxonomy menu contributed module at all. Do it at the theme level like this.

---
Tags: taxonomy-terms
---


# Question
Title: How to check if code is running inside simpletest?
Here's the best I've come up with so far:

```
/**
 * Returns TRUE if our code is running via a simpletest.
 *
 * We don't check for the database prefix so that this can be used by Unit
 * Tests also.
 *
 * We could set a variable in the test setUp method and check that variable,
 * but then some dummy could misuse that variable in code intended for
 * production.
 */
function check_is_simpletest() {
    return class_exists('DrupalTestCase', FALSE) || strpos($_SERVER['HTTP_USER_AGENT'], 'simpletest') === 0;
}

```

Is this crazy? I'd expect it to break in the Testing UI pages of the site, but I'm only concerned with testing custom code which will not affect those pages, and I usually test via drush.

# Answer
In Drupal 7, take a look at drupal\_valid\_test\_ua(), it appears to return the database prefix when simpletest is running, or FALSE otherwise

It is used in **\_drupal\_bootstrap\_database()**:

```
  // The user agent header is used to pass a database prefix in the request when
  // running tests. However, for security reasons, it is imperative that we
  // validate we ourselves made the request.
  if ($test_prefix = drupal_valid_test_ua()) {
    // Set the test run id for use in other parts of Drupal.
    $test_info = &$GLOBALS['drupal_test_info'];
    $test_info['test_run_id'] = $test_prefix;
    $test_info['in_child_site'] = TRUE;

```
> 3 votes

# Answer
In Drupal 7, drupal\_http\_request() use the following code to add an extra header, when tests are running.

```
  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  $test_info = &$GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  }

```

In your module, similar code should work.

```
  $test_info = $GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    // Drupal is running tests.
  }

```

In Drupal 6, the following code is present in drupal\_http\_request().

```
  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
    $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  }

```

The following code should work for a Drupal 6 module.

```
  global $db_prefix;

  if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix)) {
    // Drupal is running tests.
  }

```
> 4 votes

# Answer
This worked for me in Drupal 8:

```
if ( array_key_exists('simpletest.settings', $GLOBALS['conf']) ) {
  return;
}

```

I used this in hook\_node\_presave in a .module file, to stop the hook code being executed during testing.
> 1 votes

---
Tags: testing
---


# Question
Title: How to set a conditional webform to copy the value of a field to another?
I'm trying to design a webform in Drupal 7. We have a separate entries for a "student postal address" and "guardian postal address". A request appeared to have a "use same address" check box.

Is there a way to attempt this without custom coding? Optimaly, I'd love to select the value of another field using the `Webform Conditional` UI shown below.

# Answer
webform sameas

> this module makes a "Same As" component available for use on your webforms. This component allows you to add a "Same as" checkbox to a form allowing you to indicates that one set of fields should have the same value as another set of fields. For example, if you had fields for both a Billing and Shipping address on your webform, you could add the Same As component to allow users to only fill out their billing address if their shipping address is the same.
> 2 votes

---
Tags: 7, webforms
---


title: How do I alter a function?

text:
# Question
Title: How do I alter a function?
I want to track taxonomy term tagging count in the database; for each taxonomy term, I want a term tagged count that stores the number of nodes using the taxonomy term. I know I can retrieve it with a query on `taxonomy_index` but it is too time consuming for me.

I've found `taxonomy_build_node_index($node)` and `taxonomy_delete_node_index($node)`, which are called in `taxonomy_node_insert()`, `taxonomy_node_update()`, and `taxonomy_node_delete()` (node hooks).

I know a form can be altered with `hook_fom_alter()`. Is there a way to alter these functions as well?

# Answer
> 1 votes
Drupal doesn't have a way to generally replace a function in a module with a function implemented by another module.

In the case of hooks, you could alter the output of a hook with another hook, but in your case you don't even need this. Just implement `hook_node_insert()`, `hook_node_update()`, and `hook_node_delete()`, and add the code necessary for counting the tags used by nodes.

As said from Jaypan, you don't say in which way querying the *taxonomy\_index* table would be too expensive. I am not sure it would be that expensive, since the table saves the taxonomy term IDs and the node IDs: You just need to count the table rows with a specific value for *tid*.

---
Tags: 7, taxonomy-terms
---


# Question
Title: Multiple instances of same form in views do not work properly
I have a funny problem with Drupal 7 and Views.

I created programatically a simple form with two submit buttons (yes / no). This form is displayed on a full view of a node and when the 'yes' is pressed, it goes to a 'review' form which autofills the title with the one from the node. It works very well!

```
function mymodule_form($form, &$form_state,$nodeid) {
  global $user;
  $form['nodeid'] = array(
    '#type' => 'value',
    '#value' => $nodeid,
    '#access' => false,
  );

  $form['yes_button'] = array(
    '#type' => 'submit',
    '#value' => t('Yes'),
    '#submit' => array('yes_button_submit'),
  );

  $form['no_button'] = array(
    '#type' => 'submit',
    '#value' => t('No'),
    '#submit' => array('no_button_submit'),
  );
  return $form;
}

//Submit handlers
function yes_button_submit($form, &$form_state) {
    $nodeid = $form_state['values']['nodeid'];
    drupal_goto('node/add/review', array('query'=>array('id'=>$nodeid)));
}

```

I decided to add the buttons on the teasers that I display in a Views block. I call the form through a function which is called via a Global Php field. Here is the code inside the Global Php field, having added 'content: nid' as a hidden field in the view:

```
<?php
  $bling=mymodule_answers($row->nid);
  echo $bling;
?>

```

With the bit of code from mymodule\_answers:

```
function mymodule_answers($nodeid) {
  $theform3 = drupal_get_form('mymodule_form',$nodeid);
  $output .= '<p class="text-center over">'.drupal_render($theform3).'</p>';

  return $output;
}

```

My problem is that if the view is something like this:

* Node 1
* Node 2
* Node 3
* Node 4

If I press 'yes' on any of the node teasers 2 to 4, then the review form is filled with the title of Node 1... meaning, the one at the top of the list!

I have thought about creating uniquely named forms, but I wouldn't know how to automatically generate the differently named submit handlers. Any ideas?

# Answer
After looking for a while on the Internet, I found a solution.

Firstly, you can add a '#name' to your submit buttons to distinguish them, and then do a switch case in the submit handler... I was trying this for a while before realising that it was not my problem.

My problem consists in the fact that I am calling the same form multiple times on the same page. I found a previous post which highlighted the fact that each form should get a unique form\_id in order for it to work. Using hook\_forms was the best method for this. I followed the instructions from here. It worked despite it being for Drupal 6.

Amended code... I added this hook:

```
function mymodule_forms($form_id,$args){
  //Check if the form_id passed to drupal_get_form() contains the string 'mymodule_form'
  if (strpos($form_id, 'mymodule_form') !== FALSE) {
     //Lets attach mymodule_form to $forms[$form_id].  This effectively allows you to use the same form builder function to build a form with any form_id of your choice.
     $forms[$form_id] = array(
       'callback' => 'mymodule_form',
     );
     return $forms;
  }
 }

```

And then, the code that calls the form was amended to this:

```
function mymodule_answers($nodeid) {
   $theform3 = drupal_get_form('mymodule_form_'.$nodeid,$nodeid);;
   $output .= '<p class="text-center over">'.drupal_render($theform3).'</p>';

   return $output;
}

```

Voila!
> 2 votes

---
Tags: 7, views, forms
---


# Question
Title: How do I assign a specific role to each newly registered user?
Is it possible in Drupal 8 to assign a specific role to each newly registered user?

# Answer
> 7 votes
I had to implement a similar feature in a site, where:

* Users are not required to verify their email address
* When users create an account, they get the *unverified account* role
* Once the users verify their email address, the *unverified account* role is removed, and they get a *confirmed user* role

It is pretty similar to what drupal.org does nowadays; I am just using different roles, and custom code that is different from what drupal.org uses.

I didn't use the Auto Assign Role module, since there isn't a working version for Drupal 8. I didn't use the Registration Role module, since it adds the roles to every account being edited, including the accounts with the *administrator* role.

I used a custom module (which I was already using for other purposes), where I implemented `hook_ENTITY_TYPE_presave()` with code similar to the following one.

```
function mymodule_user_presave(UserInterface $user) {
  if ($user->isNew() && !$user->hasRole('unverified account')) {
    $admin = FALSE;

    foreach ($user->getRoles(TRUE) as $id) {
      $role = Role::load($id);
      if ($role->isAdmin()) {
        $admin = TRUE;
        break;
      }
    }

    if (!$admin) {
      $user->addRole('unverified account');
    }
  }
}

```

`hook_ENTITY_TYPE_insert()` and `hook_entity_insert()` are the wrong hooks to use, since they are invoked when the entity is already saved in the database. Calling the `save()` method on the entity passed to those hooks will cause all the hooks invoked when an entity is saved to be invoked again, causing an infinite loop.

# Answer
> 6 votes
You could implement `hook_ENTITY_TYPE_presave()`.

It will act before the entity is created, So you dont have to save the entity second time at your own risk, save will be manipulated by the core itself just add it in presave hook as mentioned.

```
function modulename_user_presave(Drupal\Core\Entity\EntityInterface $entity) {
 if($entity->isNew()) {
   $entity->addRole('rolename');
 }
}

```

You could also use the Registration Role module.

> Registration role lets an administrator select a role to automatically assign to new users. The selected role will be assigned to new registrants.

# Answer
> 3 votes
Assigning some role to **newly** registered users makes it possible to have features, functions, etc., that would be specific to NEWLY registered users. Like links to some "getting started" topics (e.g. in a block, or some menu links), which you don't want to show anymore to (eg) users that were registered X months ago, right?

IMO there are at least 2 ways of doing so, as further detailed below.

# Auto Assign Role

This is what you could do using the **Auto Assign Role** module ... From its project page:

> The Auto Assign Role serves three primary purposes. The first is to provide an automatic assignment of roles when a new account is created ...

This module is available for D6 and D7, for D8 you'll have to wait for issue #2220653, which includes a link to a sandbox project about it that you might want to look at ...

# Rules

It's pretty forward to implement this functionality using the **Rules** module, at least in D7.

That would be my recommended approach. Because assuming you have rules installed for other modules, you don't need another module to be added, so it reduces the risk about *modulitis* (= way too much modules enabled)

Though for using Rules in D8 it's also too early (work in progress). But, modules with "*many reported installs*", often get more attention (and assigned resources) to be upgraded.

# Answer
> 1 votes
You can use `hook_ENTITY_TYPE_insert()`, which is invoked after data is saved in the database.

```
function MY_MODULE_user_insert(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->addRole('myrolestring'); //no rid!
  $entity->save();
}

```

You could probably also use `hook_entity_presave()` instead of `hook_ENTITY_TYPE_insert()`. I didn't test this, though.

---
Tags: users, 8
---


# Question
Title: How to send an email to all members of a group after the group is flagged?
I use the Group module. I create a flag to mark groups. I wish that when a group is marked, an email is sent to all members of that group. How to do this ?

I created the following rule, but I find nothing in "conditions" in relation to the groups :

```
{ "rules_email_groupe" : {
    "LABEL" : "Email groupe",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_achats_groupes" : [] },
    "DO" : [
      { "mail" : {
          "to" : "contact@mathieulebert.xyz",
          "subject" : "Invitation \u00e0 la vente group\u00e9e de [flagged-group:title]",
          "message" : "Bonjour,\r\n\r\n\r\nle groupe [flagged-group:title], vous invite \u00e0 sa vente group\u00e9e.\r\nElle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2].\r\n\r\n\r\nCordialement,\r\nL\u0027\u00e9quipe [site:name]\r\n[site:url]\r\n\r\nPour rester inform\u00e9 des nouveaut\u00e9s et b\u00e9n\u00e9ficier de nos offres promotionnelles, suivez-nous sur :\r\nhttps:\/\/www.facebook.com\/S1biosecom\r\nhttps:\/\/twitter.com\/S1biosecom\r\nhttps:\/\/plus.google.com\/+S1biosecom\r\nhttps:\/\/www.pinterest.com\/S1biosecom\r\n\r\nPS : ceci est un mail automatique, merci de ne pas y r\u00e9pondre.",
          "from" : "[site:mail]",
          "language" : [ "flagging-user:language" ]
        }
      }
    ]
  }
}

```

Any suggestions?

Some more details about my setup:

* An overview of the Flags I've defined:
* More info about some of my fields (I also use Display Suite):
* The fields I defined for my Group Type "*Entreprise*":

**Update**: By using the Rules Component included in the answer to "How to pass a Flag field's value to a Rules Component triggered by the flag?" I'm getting closer, but I still have to find out what to do with those 2 date variables I've to pass to that Rules Component, as shown here:

# Answer
Looking at the rule you included, it seems that your Rules Event is fine. But obviously your Rules Action (to send an eMail) is to only send it to 1 (hardcoded) eMail ID. Read on for more details about how you can get this to work ...

### Step 1:

Create a flag (similar to yours) to flag a group. In my case I named it (surprise ...) "***Flag a group***", and with machine name "`flag_a_group`" (just replace in what follows this machine name of that flag with your own flag's machine name).

### Step 2:

Create a Rules Component "***Send eMail to all members of a Group***", which you can do like so:

* The type of this component is an "Action Set" (no need for any conditions).
* ***Action 1*** is to build a list of all the members of the flagged group. It uses "Fetch entity by property", with these additional specs:
    + Entity type value = Group Membership.
    + Property value = Group.
    + Value of the data selector = Group.
    + limit result count = blank (we do not want to limit the nr of results).
    + Provided variables = "Group members" (variable label) and "group\_members" (variable name).
* ***Action 2*** is to iterate (= loop) over each of the members of the flagged group. It uses "Add a (rules) loop", with these additional specs:
    + The list to loop over = group-members
    + Current list item = "Member of group" (variable label) and "member\_of\_group" (variable name).
    + Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with a message something like `"Group member named "[member-of-group:user:name]" and eMail "[member-of-group:user:mail]"` `will receive an eMail because of flagging this "[group:group-type]" group titled "[group:title]" and id "[group:gid]"` (note the various tokens which might be interesting).
    + Sub-action (ii) of this Action 2 is to actually send an eMail to the "member\_of\_group" being processed in the loop, using various tokens similar to those in Sub-action (i).

Here is how the Rules Component looks like (in Rules export format):

```
{ "rules_send_email_to_all_members_of_a_group" : {
    "LABEL" : "Send eMail to all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group" : { "label" : "Group", "type" : "group" } },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail \u0022[member-of-group:user:mail]\u0022 will receive an eMail because of flagging this \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and id \u0022[group:gid]\u0022" } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail since user [site:current-user] just flagged this group.\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

If you have the Rules UI enabled you can simply import the above rule in your own site, no need to tweak anything in it, though you may want to tune the Subject and Message content of the actual eMail as you want (just remember the various tokens you may want to use).

### Step 3:

Create a rule "***Send a group notification by flagging a group***", which you can do like so:

* Rules Event: When a group is flagged with the flag from Step 1.
* Rules Conditions: none (no need for it).
* Rules Action: perform the Rules Component from Step 2.

Here is how the rule looks like (in Rules export format, disabled as shown here):

```
{ "rules_send_a_group_notification_by_flagging_a_group" : {
    "LABEL" : "Send a group notification by flagging a group",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_flag_a_group" : [] },
    "DO" : [
      { "component_rules_send_email_to_all_members_of_a_group" : { "group" : [ "flagged-group" ] } }
    ]
  }
}

```

If you have the Rules UI enabled you can simply import the above rule in your own site, after you adapt the flag's machine name to fit yours. Don't forget to *enable* the rule also.

### Step 4:

Add any additional parameters to the Rules Component to pass any relevant extra data from the rule (from Step 3) to the Rules Component (from Step 2). E.g. that date field you added to the flag to be included in the email also (as in your question, like "*Elle commencera \[flagging:field-flag-date:value\] et se terminera \[flagging:field-flag-date:value2\].*".

For more details about this, refer to the answer to "How to pass a Flag field's value to a Rules Component triggered by the flag?". Some more details about how to use that answer in the context of this question also:

* looking at the message of the eMail in your rule here, I see 2 tokens that look like dates: `[flagging:field-flag-date:value]` and `[flagging:field-flag-date:value2]`. But your screenprints do not show how this "`field-flag-date`" is defined.
* My best guess is that you have 1 field with 2 values, no?. If so, you only need 1 Rules Condition to check "***Entity has field***", which I think will be "`flagging:field_flag_date`". And in the Rules Action you should then be able to specify (drill down) to both `[flagging:field-flag-date:value]` and `[flagging:field-flag-date:value2]`.

# Voilà

So here you go: only 3 (robust) modules (Flag, Rules and Group) is what's needed to be able to trigger an eMail of all members of a Group that is flagged by an authorized user (with zero custom code).

True, the actual eMail is hardcoded in the Rules Component (would be nice to transform that into something with 2 extra Flag "fields", to specify during the flagging what the actual Subject and message content of the eMail should be).

# VBO alternative

Another solution could be to use a combination of Rules and VBO. That would have the advantage that you get all the power of Views available to filter which group members you want to be eMailed ...
> 0 votes

---
Tags: 7, rules, emails, flags, group
---


# Question
Title: Is the #disabled form element property different from the html disabled attribute?
Looking at the documentation for `#disabled` in the form API documentation, one finds this:

> Setting #disabled to TRUE results in user input being ignored, regardless of how the element is themed or whether JavaScript is used to change the control's attributes.

If I'm reading this correctly, this seems to indicate that this is different from the HTML `disabled` property.

If I want to make an element disabled, to later enable it via javascript, and have its value come through in `$form_state['values']`, I should not use this?

# Answer
> 5 votes
Yes it's different, as well as rendering the attribute the form API also ensures server-side validation is taken care of.

As with all Drupal form manipulation, the right way to remove the disabled attribute is with the Ajax API, not by manipulating the input directly with JavaScript.

Once you use that method, you'll be able to get values for the input(s) in the form state as normal.

# Answer
> 1 votes
For anyone else in a situation similar to mine, the `#states` FAPI key can do a lot of what you want, without AJAX callbacks.

Any form element that is disabled in JavaScript should be validated by the back end

---
Tags: forms
---


title: Flags, rules and node type situation

text:
# Question
Title: Flags, rules and node type situation
got a situation with flags, rules and node type...

I have an event website where people can add events to their own calendar. Once the event is completed, they can then edit their "registration" to add comments and other details.

I am acheiving this using Event type, Flags and action. Node type: Event Node Type: Registration Flag: Add to calendar (attached to the event)

When the event is flagged by the user, a rule is set to to create a registration and update some field to link to the related event and keep the flag id in the registration. Another rule is triggered if the Registration is deleted, it unflag the event.

Not sure if there's a better way to do this? Any suggestions? Better practice? It's working, but the problem I have is that it's taking a lot of time to load the edit form of the registration. I am going to try the token tree optimisation, but if there is a better solution, I'm willing to give it a try. Also, using the current system, it creates a node for every event added to the user calendar.

Thanks

# Answer
> 0 votes
It sounds to me that you should have a look at the Entity Registration module as an alternative to simplify your current setup. Some more details about it, from its Community documentation:

> The Entity Registration module provides the ability for users to register for any entity in Drupal. Registrations are fieldable entities and can collect any information you need from your registrants. By attaching a Registration field to any entity, you enable users to fill out a form containing customized fields to register for that entity.
>
> Entity Registration currently has the following features:
>
> * Registrations are fieldable entities, so collect any information you need from your registrants
> * Unlimited types of registrations, or bundles.
> * Enable registrations of a given type/bundle on any entity type or individual entity through a registration field.
> * Per entity registration settings like capacity, reminders, etc. Send broadcast emails to registrants.
> * Allow a single user to register multiple registrants.
> * Integration with Views and Rules via Entity API.

---
Tags: rules, flags
---


# Question
Title: How to pass variable from block and access in it twig template
I'm trying to make custom block but I have problem accessing variables in template.

My block code:

```
namespace Drupal\more_topics_rollout\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 *
 * @Block(
 *  id = "more_topics_rollout",
 *  admin_label = @Translation("More topics rollout"),
 *  category = @Translation("Blocks")
 * )
 */
class more_topics_rollout_block extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#title' => 'More topics'
        );
    }
}
?>

```

My module file:

```
function more_topics_rollout_theme($existing, $type, $theme, $path) {
    return array('more_topics_rollout' =>
        array(
            'variables' => array(
                'title' => null,
                'body' => null,
                'description' => null
            ),
            'template' => 'block--more-topics-rollout'
        )
    );
}

```

And when I'm trying to display title with `{{ title }}` it doesn't render. When I'm trying to access variables I know for sure don't exist like `{{ dasdasda }}` it doesn't throw any errors. Can someone explain this behavior to me?

# Answer
## Can someone explain this behavior to me?

The render array returned by the build method in the block plugin does not have a theme or type. This means that it will default to markup (iirc). The theme/template is not being used because the render array does not specify to use it.

You can find an example of implementing render arrays on drupal.org's documentation page, Render arrays. This explains the default element properties.

## How to pass variable from block and access in it twig template?

The render array should have the `#theme` element property set to the theme definition key.

```
  public function build() {
    return [
      '#theme' => 'more_topics_rollout',
      '#title' => $this->t('More Topics'),
      '#body' => 'My body',
      '#description' => 'My description'
    ];
  }

```
> 5 votes

# Answer
I figured out why I wasn't able to access my variables from twig. In order to to this your custom block class needs to implement BlockPluginInterface. Maybe it will help someone else.
> 0 votes

# Answer
We ended up solving this issue by adding a param during the preprocess hook - in our case we were modifying the easy\_social module to include the current page url

```
/**
 * Implements hook_preprocess_HOOK() for easy_social theme.
 *
 * @see easy_social_theme()
 * @see theme_easy_social()
 */
function easy_social_preprocess_easy_social(&$variables) {

  // ...

  $variables['path'] =  Url::fromRoute('<current>',array(),array('absolute'=>'true'));

  // ...
}

```

And then in our Twig file:

```
<p>Your current page is {{ path }}</p>

```
> 0 votes

---
Tags: theming, 8, blocks
---


title: Drupal core update

text:
# Question
Title: Drupal core update
I had a message that Drupal 5 was no longer supported and to update to Drupal 5.1. I went to drupal.org to see how to back up and install manually as I was instructed, and I followed the instructions to the letter.

I've cleared the cache (3 times), ran Drush which tells me everything is up to date, then I get urgent update messages like this.

Basically, should I go and re-do the core upgrade when it's obviously already there, or is it safe to ignore? I'm totally new to Drupal, but can't find any way to get help directly from them.

# Answer
> 1 votes
D.o was down for a half hour or so between 4 and 5pm Pacific. If you tried to do updates around that time, this message may have been presented. It's back up as of now, you can check again and see if it still occurs.

---
Tags: 7, updating
---


# Question
Title: Why arn't changes I am making in CSS appearing?
This is weird. I've just started at a company that uses Drupal (I havent used it before) and I've been tasked with making some simple CSS changes to a site.

I find the site's theme folder and corresponding CSS and make a simple change just to test things out. Nothing happens. I clear the cache via admin and get a 500 error. Fine. So I use drush to clear CSS and JS. It says it works but still no change. I clear my browser cache too just to be sure.

I use Chrome's inspector to trace back the paths of the CSS files I'm working on - they're correct. I even check the themes .info file to see if all the .css files are linked - they are.

So...what am I missing here? What on Earth is going on?

(Edit: CSS aggregators are off)

# Answer
Turned out this was because the Theme I was working on refused to be 'activated' despite this appearing so in the UI. I don't know why Drupal was doing this.
> 0 votes

# Answer
I'd turn off CSS aggregation temporarily to see if that makes any difference. The settings are in admin/config/development/performance

That way you can see which CSS files are being used directly. This sounds like it might be a configuration problem with the server itself and not something with Drupal.

Also, check the response headers for the CSS. That will give you more info about whether it's serving cached versions and if there's something like a reverse proxy serving old versions of the files.
> 0 votes

---
Tags: 7, theming
---


title: Location Module and Search api

text:
# Question
Title: Location Module and Search api
I am using the Location Module to add a location to a field on a content type I am then using Views and Search Api to create an index and a view of this content type. The problem I have is that I cant find any way to get the data from the location to the view. At the bottom of the search index page I can add other entities such as users that are linked to this node but not the Location this is the same for Relationships section in the view.

# Answer
This was a compatibility issue with the Location module moving over to geofield module allowed me to add the coordinates to the search api index
> 1 votes

# Answer
The Search API Location module provides integration with the Location module, indexing location data.
> 0 votes

# Answer
Currently only the Solr Search API back-end with the Geofield module is supported for location searching. In order to mimic the behaviour of the Drupal Location address field entry first install these three modules:

Managing the Fields of the Entity create an Address field (Postal Address). Then create a Geofield field with a widget type of 'Geocode from another field'. Then select the first Address field as the 'Geocode from field' in the options. Also select the service that will do the Geocoding (Google, Yahoo, Bing, etc.).
> 0 votes

---
Tags: 7, search, location
---


title: Cannot find module folder

text:
# Question
Title: Cannot find module folder
I installed Simplenews 8.x-1.0-alpha2 using `/admin/modules/install` and then pasting the url to the tar file.

Now I want to uninstall/delete it, but I cannot find where the folder is.

I have checked in `/modules` and `/core/modules`

I even tried uploading the dev version to the `/modules` folder, but it does not ask me to overwrite.

This is so strange, where else could it be?

### Update

I tried as suggested by sanzante using Devel and `echo drupal_get_path('module', 'simplenews')`

it says `modules/simplenews`

but when I try to go there with FileZilla, it does not let me. I also re-started FileZilla multiple times.

# Answer
Turns out that his site was moved to another server.

The FTP that I was seeing was from the old server. When I installed the simplenews it got installed in the new server.
> 1 votes

---
Tags: 8
---


# Question
Title: How enable PHPMailer to write complete persistent log?
I am using the PHPMailer module to send emails to a user group (role) by a poormanscron-job.

I can see errors in my "**recent log entry**" view in the backend but I cannot get a **persistant log** with all log entries (I set the phpmailer settings to INFO or DEBUG level in the backend) somewhere.

I would like to check afterwards, **who got the email** and **if there were dropped mails** without errors (if that is possible).

# Answer
> 1 votes
It's not clear from your question what Drupal version you are on. But the Maillog / Mail Developer module might be handy here. Some more details about it (from its project page):

> ... provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally you can immediately display the mail through the Devel `dpm()` facility.

But you might get integration problems, since it's not easy and highly Drupal version dependent to get more than one email module at a time working.

# Answer
> 1 votes
Make sure that you are using the correct phpmailer version(library) php5 or 4.

Do not use SMTP and phpmailer MODULES together.

Try to connect to localhost (port 25) first.

---
Tags: emails, debugging
---


# Question
Title: Javascript does not work when signed in or when comments are open
This is my info.yml file.

```
name: tnt
description: Drupal 8 starter theme
type: theme
core: 8.x

libraries:
  - tnt/global-styling

regions:
  header: 'Header'
  primary_menu: 'Primary menu'
  breadcrumb: 'Breadcrumb'
  content: 'Content'
  sidebar_first: 'Sidebar first'
  footer_first: 'Footer first'

```

This is my libraries.yml file.

```
global-styling:
  version: VERSION
  css:
    theme:
      styles/style1.css: {}
  js:
    js/js1.js: {}
  dependencies:
   - core/jquery

```

This is my JavaScript file.

```
$(document).ready(function() {

  alert("Here I am");

});// end ready

```

This works fine unless one of these conditions is true.

* User is signed in
* User is on a page where comments are open

Obviously, I had much more complicated JavaScript code, but I reduced it to something simpler to illustrate the point.

I am currently using Drupal 8.1.10.

How do I get this to work when users are signed in and/or comments are open?

What am I doing wrong?

# Answer
To get the jquery alias `$` working in drupal, you have map it like this:

```
(function ($) {
  $(document).ready(function() {
    alert("Here I am");
  });
})(jQuery);

```

The document ready function is not the best option, better use `Drupal.behaviors` and `once()`:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: Search autocomplete - what is the proper way to make it work for more that 13000 nodes?
I use Search Autocomplete module, it works fine but only for small amount of nodes. I have more than 13000 nodes and this module just stacks. Is there a solution for this case?

# Answer
I have not run into this directly with Search Autocomplete, but have run into similar issues with Views autocompletion with very large node sets. There are two things that have helped me in the past.

One, is to make sure your database is truly optimized, to eliminate that from any speed problems. mysqltuner will give you a good starting point.

The second thing requires monkey patching misc/autocomplete.js to use your own version of `Drupal.ACDB.prototype.search` which uses a minimum search needle length to lower the initial result set. TBH, I have done this before, but it was so long ago that I forget the details.

Also keep in mind that single word searches will be against the index (which has a MySQL index), but multiword searches are against the dataset, which is essentially a `LIKE` query, which can be slow. Enable query profiling to see what is going on there.

This should give you a starting point.
> 1 votes

---
Tags: search, ajax
---


title: How to change drush drupal folder

text:
# Question
Title: How to change drush drupal folder
i install 3 drupal site without drush in xampp localhost in ubuntu and now install drush. how to use drush with 3 drupal local site??? first drupal site in dr7 folder second drupal site in drupal7 folder third drupal site in mydrupal folder

# Answer
Install Drush globally, and ensure that it is in your `$PATH`. Assuming that you have used Composer to install your site-local Drush, then you may run the global `drush` command, select the site you want to use either via an alias (`@exampleorg`) or commandline options (`--root=/path/to/drupal --uri=http://example.org`), and Drush will automatically redispatch to the site-local copy. You may use different versions of Drush in your different local sites, if you wish, and it will still work correctly.
> 3 votes

---
Tags: drush
---


# Question
Title: Search through a specific field - Drupal 7
Is it possible with Drupal to create a seperate search field to search in a custom field for a specific content type?

For example I have a text field in a content type with the name keywords. I gave some important keywords for that specific node.

What I want is that a user can search through these words with a custom search field, that is displayed on a specific page.

I know I could use something like exposed filters in views, but it is not working in my case. The reason is the nodes are having a relationship with a taxonomy list. The nodes are showing based on the taxonomy term ID in the URL.

For example, my taxonomy list called 'Jobs'. The terms in the list are 'sanitary', 'interior' and 'garden'.

When I'm on the page with the sanitair, there is a search field. If I search in this field it should take a look for all the nodes not only the nodes that are related with the 'sanitair' term. If I used exposed filters the filter is only searching on the current term, so only the kind of jobs for 'sanitair' are showing up.

Is there a way to do this with or without views and is it also possible to create this search field in a block, so I can use it on different places?

Thanks!

# Answer
You could:

* create a new separate view for searching across all nodes and display it in a block on the taxonomy term page, or
* use solr search and set up facets (requires a lot of setup)
> 2 votes

---
Tags: 7, views, taxonomy-terms, search
---


# Question
Title: How to create flexslider slideshow as a background in drupal 8?
My slideshow is working but it is not in the background -- I am using paragraphs that I thought would make it easier for my client to add new images - the "flexslider" is in the header and I did create a twig template to put it in the background - "paragraph-frontage-flexslider.html.twig" ; the "flexslider" is there but not in the background (I modified a slideshow background twig that I found)

```
[section class="region-header.outer-wrapper" style="background-image: URL('{{file_URL(content.field_background_flexslider_imag['#items'].entity.uri.value)}}');"]
  [div class="overlay"][/div]
  [article]
    {{content.field_background_flex_caption}}
  [/article]
[/section]

```

**Any help would be most appreciated!**

# Answer
> 1 votes
Flexslider is a javascript library that makes a bunch of changes to the markup once it is loaded. Instead of trying to put the images in as background images I suggest using `position: absolute` on either the flexslider itself, or the items you want to sit on top of it.

You may also need a `z-index` on some items to bring the to the front or send them to the back.

---
Tags: views, javascript
---


# Question
Title: Drupal 7 Can a custom textarea render html without a rich texteditor enabled?
I am using Drupal 7, (fairly new to module dev) here's my use case- I am trying to add a terms and conditions field directly within the user\_registration screen. The Administrator sets the terms, so they have access to change the field values, but the authenticated user will not.

I am adding a custom field and when the field is loaded paragraphs, breaks, quotes are converted to html characters instead of rendering as an actual paragraph - I am assuming because the textarea isn't seen by ckeditor library? Im trying to display the field with the rendered paragraphs and breaks as this displays fine for admin users. It almost as if I need to specify **rich-text**

**How would I do this?**

```
function myModule_form_user_register_form_alter(&$form, &$form_state, &$form_id) {

 $form['field_agreement']['#access']=FALSE; //the default field is hidden from authenticated users

 //adding in custom field for auth users

 $form['Agreement'] = array (
  '#type' => 'textarea',
  '#title' => t('Terms & Conditions'),
  '#default_value' => $form['field_venue_agreement']['und']['0']['#default_value'],
  '#weight' => '10',
  '#description' => t('You must agree to our terms each time a new user is added'),
  '#disabled' => TRUE,
);

}

```

# Answer
I didn't find the answer I wanted to find, but after careful examination of the form api, I discovered markup and it led me down the path of fooling the end user into thinking it looked like a field with some css manipulation. This is working for me

```
$form['Venue Agreement'] = array (
 ['0']['#default_value'],
  '#weight' => '10',
  '#markup' => $form['field_venue_agreement']['und'['0']['#default_value'],
  '#prefix' => '<div class="form_input">',
  '#suffix'=> '</div>',
);

```
> 0 votes

---
Tags: forms
---


# Question
Title: Check required directory structure on module install/enable
I am working on a drupal 7 module which acts as a interface for real estates. The interface works with xml files. Because of this i need some folder in the private files system.

I have defined my required folders as constants in the .module file. Now i wanted test with file\_prepare\_directory if the folders exist and if not create them. I want to do this on module install (hook\_requirements) because the module works in the background with crons, so i would never get an error message if there is something wrong with the folder structure. The problem is that i could not access the constants from the .module file in the hook\_requirements function.

So what is the best way to do this in drupal 7? Should i use hook\_requirements, and if yes, how could i get my constants working? Or is there an ever better way to do this?

# Answer
The Drupal API function `drupal_load()` will let you preload your .module file so you can make its constants/functions available during your `hook_requirements()` invocation:

```
/**
 * Implements hook_requirements().
 */
function MYMODULE_requirements($phase) {

  // @TODO: misc code.

  drupal_load('module', 'MYMODULE');

  // @TODO: code that requires MYMODULE_CONST_DEFINITION
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Button on user profile page to send email
I think this is pretty simple, but I don't know what's the best way to achieve this.

This is what I need:

* Add a button on each user profile page. When another user clicks on the button, it opens a form (in a popup window would be great) to write the message. The email should be sent to the user of the profile page we are seeing.

If it's not possible to add a form, I just need a "mailto:useremail" so when i click the button opens the outlook our gmail, wtv.

How can I do this? Is there a simple way?

Thank you!

# Answer
To get what you want, you need to modify the template user, to do this you need to follow the next steps:

1. Find the file called **user-profile.tpl** it is in the module user **modules\user** (**NOT** inside **sites/all/modules**).
2. Once you found it, open it, and you should see at the end of the file something like this:

> print render($user\_profile);

3. Now copy and paste this line of code inside php tags:

> $usr = user\_load(arg(1));
>
> echo 'mail.'?Subject=textyouwant" target="\_blank"\>Send Mail';

That should work !
> 2 votes

# Answer
@Drii7, Drupal provides with a default contact us form, but if you insist to use the `mailto:username`, you can overwrite the template in the `user` module as suggested by @DarkteK. You can copy the file in your `theme's` templates folder and add a `mailto` link where you want.
> 2 votes

---
Tags: users, emails
---


title: Search API node access limitation

text:
# Question
Title: Search API node access limitation
The Search API has a Node Access Data Access Alteration which adds info into the index which can be used to implement 'normal' drupal node access restrictions to searches.

This was working fine until recently when a particular user was granted one too many Realm + grant Ids: now the Search API is throwing a hideous exception that's killing my site.

Basically Search API seems to create a JOIN for each realm:gid combo, and MySQL is limited to 64 JOINS.

**Is there any way around this or is it a limitation of the Search API?**

Would using Solr (never done it), for example, provide a solution?

# Answer
My solution was to patch the search api db implementation.

This looks to see whether the field is a one-to-many relationship; if it is, then the table is added for each condition. I presume that this is so that these matches can then be counted and add towards the relevance score. However, for access restriction we're only interested in a single match, and (presumably) shouldn't add this to the score anyway. Therefore for this case there is no need to add a join for each possibility.

The patch below looks for this use case and ensures the user access table is only joined once.

```
--- a/sites/all/modules/search_api_db/service.inc
+++ b/sites/all/modules/search_api_db/service.inc
@@ -1028,7 +1028,12 @@ class SearchApiDbService extends SearchApiAbstractService {
           $cond->condition('t.item_id', $query, $f[2] == '<>' || $f[2] == '!=' ? 'NOT IN' : 'IN');
         }
         else {
-          $alias = $this->getTableAlias($fields[$f[0]], $db_query, search_api_is_list_type($fields[$f[0]]['type']));
+          // the user access node table only needs joining once; we're not interested in
+          // scoring based on access; access is a boolean, so we do not need muliple joins
+          // which can break the query if there are more of them than the SQL engine allows joins
+          // (e.g. MySQL is limited to 64 joins).
+          $rejoin = search_api_is_list_type($fields[$f[0]]['type']) && ($f[0] != 'search_api_access_node');
+          $alias = $this->getTableAlias($fields[$f[0]], $db_query, $rejoin);
           $cond->condition($alias . '.value', $f[1], $f[2]);
         }
       }

```

---

EDIT: LOL - or as they did it...

```
+          $new_join = search_api_is_list_type($field['type'])
+              && ($filter->getConjunction() == 'AND'
+                  || empty($first_join[$f[0]]));
+          if ($new_join || empty($tables[$f[0]])) {
+            $tables[$f[0]] = $this->getTableAlias($field, $db_query, $new_join);
+            $first_join[$f[0]] = TRUE;
+          }
+          $cond->condition($tables[$f[0]] . '.' . $field['column'], $f[1], $f[2]);

```

**Answer is: upgrade module to v7.x-1.0!**
> 0 votes

# Answer
May be you can check if node access is being indexed in filter options. Building a search View that respects access control
> 0 votes

---
Tags: users, search
---


# Question
Title: How can I implement AJAX form submission?
My task is to submit a contact form **via AJAX** and then to show a "Thank you for submission!" message, loaded in place where the form was. So I need to ajaxify existing contact form.

I found some examples of how to **validate** form fields using AJAX in D8, but I can't find any example of how to implement an **ajax form submission** and load some content via AJAX then.

How can I implement my task? How should I alter the contact form to add the required functionality?

# Answer
When working with ajax in forms you have to keep in mind the following things:

* know if you are rebuilding the whole form or only part of it and wrap the form accordingly with **div** element that has **ID attribute** that you will use in the #ajax definition on the triggering element as 'wrapper'. Use #prefix and #suffix attributes for this(`$form['#prefix'] = '<div id="myform-ajax-wrapper">'; $form['#suffix'] = '</div>';`). Also keep in mind that if you have custom template for your form to **NOT** render the prefix and suffix in this case(`{{ form|without('#prefix', '#suffix') }}`) otherwise they will get rendered twice - by your template and also by the form theme wrapper. You cannot prevent this by setting #theme\_wrappers to empty array since the form template contains the actual form html element.
* in your ajax submit handler, return the whole form or portion of it that you've wrapped and want to rebuild(`return $form` or `return $form['myelement']`). You can additionally use ajax commands instead of just returning the form structure but that is more advanced stuff.
* store every value in form state's storage until you submit the form. Do this in the submit handler(`$form_state->set('somevalue', $form_state->getValue('somevalue'))`) and always call `$form_state->setRebuild()` if you are not doing the final form submission. I prefer having custom submit handlers but having more logic in the primary submit handler is totally ok as well.
* always use `#name` attribute on the button that is doing the submission and if you have only single form submit handler use `$for_state->getTriggeringElement()['#name']` to detect which element has submitted the form.
* if you are using 'trigger\_as' in the #ajax definition, in case you want to submit the form with select element for example, always use the same #ajax definition like you do on the button. In my experience it is required - although not stated in the documentation.
* using `#limit_validation_errors` can get very tricky sometimes and to figure out why the form is not working can take quite some time, so use it carefully(this is good for isolating form errors only on the element(s) that you are actually rebuilding so that your code does not influence other parts of the form).
* always use buttons to submit the form and if you want to have something fancy, like select being the triggering element, use the 'trigger\_as' option of the #ajax configuration and hide the real button with 'js-hide' class for good UI.
* in the form definition, get the default values from the form state's storage if they exist or assign them into the storage if they don't. Otherwise the form won't work properly.
* don't use $this or anything else that you don't have access to externally, otherwise it will break the ajax. always use static ajax handlers.
* when finally submitting the form, depending on the fact that you (don't)have a custom form submission handler for the ajax, disable the form rebuilding by calling `$form_state->setRebuild(FALSE)`.
* you can use the :: shorthand calls in the ajax submit element(`$element['#ajax']['callback'] = '::ajaxFormRebuild';` and `$element['#submit'] = [['::ajaxFormSubmitHandler'];`).
* the ajax callback is purely to return the rebuilt form or ajax commands. Never return altered form(ie. do not alter the form array in this callback).
> 33 votes

# Answer
To add to this checklist, if you are displaying a form in a modal window there is a possibility that the error messages will not be displayed. As Ivan Jaros said, you have to ensure that the form has a wrapper:

```
$form['#prefix'] = '<div id="my-form-wrapper-id">';
$form['#suffix'] = '</div>';

```

You'll also need to add the following to the element that is submitting the form. In most cases it would be your submit button:

```
$form['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Save Changes'),
    '#attributes' => [
        'class' => [
            'btn',
            'btn-md',
            'btn-primary',
            'use-ajax-submit'
        ]
    ],
    '#ajax' => [
        'wrapper' => 'my-form-wrapper-id',
    ]
];

```
> 2 votes

# Answer
I use the Contact ajax module. Some more details about it (from its project page):

> Contact Ajax implements ajax submission for Contact form in Drupal 8.
>
> ### How it works
>
> After enable the module, each contact form will show a checkbox "Use ajax". When this checkbox is enabled the contact form will show you another option "Confirmation type" with these options:
>
> * Load the form: will send the form without reload the page.
> * Load from custom message: load a custom text.
> * Load from node: load a node after form submission.
>
> ### This module could help you if:
>
> * you need to customize the confirmation message
> * you need to submit a contact form without reload the page.
> * you want load a custom text or another node after form submission.
> 2 votes

---
Tags: ajax, 8, forms
---


# Question
Title: Inline labels for exposed filter forms in Views 3
How do I make labels inline for exposed forms in Views 3?

# Answer
Might be worth checking out the Better Exposed Filters module, and Better Exposed Filters (the handbook). I haven't used this module.
> 0 votes

# Answer
If you create a small module (or already have one), you could use the form\_alter (or rather the form\_FORM\_ID\_alter) hook to add the "container-inline" class.

Here is some sample code:

```
/**
 * Implements hook_form_FORM_ID_alter()
 *
 * Display views 3.x exposed filters' field labels and fields inline
 */
function mymodule_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  // If you want to only affect specific views' exposed forms, select the view name here
  if ($form_state['view']->name == 'myviewname') {
    // Add a class to the attributes
    $form['#attributes']['class'][] = 'container-inline';
  }
}

```

Replace "mymodule" with your custom module name.

Replace "myviewname" with the view's machine name, or remove the if statement completely to affect all exposed filter forms.
> 0 votes

---
Tags: 7, views
---


title: Displayed content by alphabetical order

text:
# Question
Title: Displayed content by alphabetical order
I have a custom content named course and each time the admin wants add a course, it is displayed in a form with all courses, my issue is it is displayed by date and I want to change by alphabet, how can I do that? please help!!

# Answer
> 1 votes
If you are creating the form with the help of a custom module, you can sort the options in the form at the time of db query before displaying them. You can do something like this.

```
$query=db_select('table name','n');//here your table name
 $query->fields('n', array('title'));//SELECT the fields from table
 $query ->orderBy('title', 'DESC')//ORDER BY create
 $opts=$query->execute()->fetchAllKeyed();

$form['courses'] = array(
    '#type' => 'select',
    '#title' => t('courses'),
    '#multiple' => TRUE,
    '#options' => $opts,
);

```

---
Tags: views, forms, blocks
---


# Question
Title: How to get accurate information about available security updates after End-of-Life?
For a Drupal 6 site that use the ***update*** module, the "Available updates" report no longer shows accurate information about available security updates.

Of course, this is because after Drupal 6's End-of-Life date, all Drupal 6 modules on Drupal.org were marked as unsupported.

Is there any other way to still get accurate info about available security updates for Drupal 6?

# Answer
> 6 votes
Have a look at the myDropWizard module, a recently released module for Drupal 6. Some more details about it (from its project page, which also includes a screenprint about it):

> Reports accurate update status for Drupal 6 modules now that Drupal 6 is End-of-Lifed and most contrib modules are unsupported by the community.
>
> It does four main things:
>
> * It still shows security updates if a module is unsupported, so you'll know about security updates you haven't applied, regardless, and
> * It uses an alternate data source that reports whether a module is supported by the Drupal 6 Long-Term Support (LTS) vendors, so you'll know if it'll be getting security updates going foward
> * It will let you know about additional security updates made by the D6 LTS vendors! The LTS vendors are required to post their patches publicly, but there won't be any Security Advisories going out to let people know, and it won't be in the normal Drupal.org update status data (we create special security releases for the patches released by the LTS vendors, which appear in our data)
> * It integrates with Drush 7 or later. See "Drush integration" section below for more information!
>
> While it uses a different data source, it continues to report usage information back to Drupal.org, so the community won't lose that valuable resource. This will let us know how many people are still using Drupal 6 in the next months and years!

Refer to "Getting accurate 'Available updates' for Drupal 6" for a related article about it also.

---
Tags: 6, security
---


# Question
Title: How to access the administration panel if you cannot login again?
I have created a custom theme. I have added the region user account menu in footer, but I forgot to add the region primary admin access.

Unfortunately I clicked on the logout button, and I am not able to log in again. The page at `/user/login` appears empty. Now how can I access the administration page?

# Answer
> 1 votes
You change your default theme in setting.php.Uncomment this line in your setting.php file

```
 $conf['theme_default'] = 'garland';

```

---
Tags: 7
---