# Question
Title: Modify the links included in the user menu
On a base Drupal install, there are 2 links included in the User Menu, My Account, and Log Out. I want to modify the My Account link to be expanded, and modify the Log Out link to be a child of the My Account link. How can I do this?

I've tried:

```
function MODULE_menu_alter(&$items) {
  if (isset($items['user'])) {
    $items['user']['expanded'] = true;
  }
}

```

To at least set the My Account as expanded, but that's not working (ie. not setting the expanded property to true). And I don't know how to change the parent of the Log Out link. Preferably this could all be done without a database request.

EDIT: I recently succeeded a little bit in using:

```
function MODULE_menu_link_alter(&$item) {
  if ($item['link_path'] === 'user' && $link['module'] === 'system') {
    $link['expanded'] = 1;
  }
}

```

That modifies the My account link to be expanded, but I still can't seem to modify the plid of the logout link ('user/logout').

# Answer
Tested:

1. Go to yoursite.ca/admin/structure/menu/manage/user-menu
2. Click the edit button for "My account (logged in users only)"
3. Check the "Show as expanded" box
4. Click Save
5. Click the edit button for "Log out"
6. Select "My account" under the Parent link

---

---

7. Click Save
> 1 votes

# Answer
I'm not totally sure about your design.

Since both links are static (no need to add args to path), why don't you just disable User Menu and create a brand new Menu with your custom structure?
> 0 votes

---
Tags: 7
---


# Question
Title: How to use Rules to send separate email to every user referenced in user reference field?
I have a node with a user reference field, in which a user can select unlimited users who they have a relationship with. I'd like for the saving of this node to trigger a separate email to be sent (via Rules) to each user chosen in that reference field, or a single email with all of those users BCC'ed. Currently, the "send mail" action with "node:field-friends-you-wish-to-invite:0:mail" selected in the "To" field of the Rule only sends an email to the first user selected in the list, no matter how many other users have been selected.

How can this be accomplished?

# Answer
You should create a rule that looks like so (in Rules export format):

```
{ "rules_send_email_to_selected_email_ids" : {
    "LABEL" : "Send eMail to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to [current-email-id:value]." } },
            { "mail" : {
                "to" : "[current-email-id:value]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Some more details about the above rule:

* **Rules Event**: After saving new content of type "Article" (adapt the type to fit your needs, ie to XYZ).
* **Rules Action**: a "loop" for all selected values of a multi value select list (which contains the eMail IDs), with machine name `field_email_addresses` (adapt the machine name to fit your needs). For each item (= `current_email_id`), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs (there is no way to send a single eMail to all selected eMail IDs).

If you have the Rules UI enabled, you can import the above rule in your own site, after you adapt the machine names of the content type and the field name containing the list of eMail Ids.

After you're convinced the rule works as expected, you may want to remove the Rules Action that displays a message after the node is saved (with `drupal_message`).

**Video tutorial**: have a look at the List and loops video which show a similar scenario.

**Update**

If you don't have such field with eMail IDs, but a field which is an entity reference field to user ids, then you can use a minor variation of the above rule. Instead of `field_email_addresses`, you'd want to loop over the list of users (indicated via the user reference field, let's assume it's named `field_user_ids`). And for each "item" (which I'd name "`current_userid`"), in the "to" field you'd use the `current-userid:mail` token for the user being processed. Here is how such rule could look like (in Rules export format):

```
{ "rules_send_email_to_selected_user_ids" : {
    "LABEL" : "Send eMail to selected user IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-user-ids" ] },
          "ITEM" : { "current_userid" : "Current user ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to eMail ID [current-userid:mail]." } },
            { "mail" : {
                "to" : "[current-userid:mail]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```
> 1 votes

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


# Question
Title: Display Content Type Field in region--footer.tpl.php
First of all I am overriding the default footer template with my own using **region--footer.tpl.php**. In the footer I need to display the fields I have in a content type named 'footer'. Can anyone help me with this?

# Answer
> 1 votes
Like I said, fast and dirty:

```
$nid = XXX;
$node = node_load($nid);
print check_plain($node->field_name['und'][0]['value']);

```

Put this into your Template. I assume your field is not translated.

---
Tags: 7, blocks, theming
---


# Question
Title: hook_form_search_block_form_alter is not working with bootstrap theme?
I am facing an issue where hook\_form\_FORM\_ID\_alter() code is working in bartik theme while same is not working in Bootstrap theme. Any idea what could be the reason or am I missing something? Very Thanks.

***In THEMENAME.theme of bootstrap theme***

```
<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;

function subtheme_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
}

```

***OtherWay,***

```
function subtheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'search_block_form'){
      $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
    }
}

```

***In bartik.theme***

```
<?php

/**
 * @file
 * Functions to support theming in the Bartik theme.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;

function bartik_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
}

```

# Answer
You can try a bootstrap plugin:

**themes/THEMENAME/src/Plugin/Form/SearchBlockForm.php**

```
/**
 * @file
 * Contains \Drupal\THEMENAME\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\THEMENAME\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends \Drupal\bootstrap\Plugin\Form\SearchBlockForm {

  /**
   * {@inheritdoc}
   */
  public function alterForm(array &$form, FormStateInterface $form_state, $form_id = NULL) {
    // Call the parent method from the base theme, if applicable (which it is
    // in this case because Bootstrap actually implements this alter).
    parent::alterForm($form, $form_state, $form_id);

    $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.')
  }
}

```

Reference:

http://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins\_form/8
> 0 votes

---
Tags: theming, 8, hooks
---


# Question
Title: How do I avoid checking for updates for a specific module?
In a current project I have had to patch the life out of a few modules (node hierarchy, workbench access and a few more). These modules are now absolutely perfect for the project's needs and are very unlikely to break with future updates to core.

That being said, when the app is handed over the clients will have full (user 1) access to the system and will therefore be warned when these modules have available updates. And they *will* update them, no matter how many times I beg them not to (oh how easy life would be without clients!).

Is there a way (perhaps in the modules' `.info` files) to persuade the update manager not to check for updates for these modules?

**EDIT**

I'm aware of the `project status url` key that's available for the `.info` file so I guess I could set that to a non-existent URL but I'd much rather do this in a clean way if possible.

# Answer
> 34 votes
You need to implement `hook_update_projects_alter()`.

> Alter the list of projects before fetching data and comparing versions.
>
> Most modules will never need to implement this hook. It is for advanced interaction with the update status module: mere mortals need not apply. The primary use-case for this hook is to add projects to the list, for example, to provide update status data on disabled modules and themes. A contributed module might want to hide projects from the list, for example, if there is a site-specific module that doesn't have any official releases, that module could remove itself from this list to avoid "No available releases found" warnings on the available updates report. In rare cases, a module might want to alter the data associated with a project already in the list.

# Answer
> 24 votes
The `project` key from the *.info* file is added by the packaging script on drupal.org to identify what project the module is from. The primary use is for the Update status module to monitor versions of installed packages and notify administrators when new versions are available.

You just remove or comment this line in *.info* file and Drupal stop checking for updates of this module.

# Answer
> 15 votes
Just providing a code sample to help the chosen answer:

```
function MYMODULE_update_projects_alter(&$projects){
    unset($projects['slug_of_the_module_you_want_to_disable']);
    //dsm($projects);  // view a list of projects
}

```

Enter the module name in the `$projects[]` variable to disable. If you're not sure what the slug is (will be lowercase and underscored), use that `dsm()` call or `print_r()` to print out a list of the modules.

# Answer
> 14 votes
You can do it in two ways.

* drush pm-updatecode --lock=module\_to\_ignore
* Use the update\_advanced module. It allows you to mark modules that you want to ignore on the module administration page.

> In particular, the per-project settings to ignore certain projects or even specific releases, is absent in the core version of the module. The "Update status advanced settings" module restores these settings, and might eventually provide additional functionality for the core "Update status" module.

# Answer
> 3 votes
I get the same issue with the module updates, I installed the Disable Updates module seems working good.

> This is a small administrative module that lets site administrators disable checking for updates on certain themes and modules, by exposing the functionality of hook\_update\_projects\_alter() on the update settings form (/admin/reports/updates/settings). It allows for arbitrary selection of themes and modules as well as auto detection of custom modules, patched modules, and site-specific features modules.

# Answer
> 0 votes
Basically, you made a fork, right? So you should:

1. Rename it to include your fork mark
2. In info file, set `project status url` to your repository of that module.

Last but not least, if it's not supported but was not deprecated in favor of any other module, consider asking to become co-maintainer and share your fixes with community.

---
Tags: 7, updating
---


# Question
Title: What is the purpose of the percent sign in contextual filters?
The percent sign is something I once saw in contextual filters in Drupal 6 and Drupal 7, but not Drupal 8.

What is the purpose of the percent sign in contextual filters?

# Answer
The percent sign in view arguments is to tell Drupal to expect a contextual filter within the view path. It is specific to Drupal 6 and 7, linux doesn't matter.

Drupal 8 uses curly braces to accomplish this instead.

From https://www.drupal.org/node/1578576, the example provided is that `user/%/comments` would provide a contextual filter to show the comments for the specific user.

This resource gives screenshots and examples about how to create a contextual view filter: https://www.drupal.org/node/1578564
> 5 votes

# Answer
Here, you can see the `User ID` in contextual filter which we use in our view path, i.e see in the `Path` settings : "/user/%/profile".

This is an example for you to understand how to use % in view's path.
> 1 votes

# Answer
If you click on your view page path, it tells you:

and as you can tell from the screenshot, it is still used in Drupal 8.

If you still do not understand, basically it is a place holder. Whatever the `%` value is, it gets passed for your contextual filter.

Ex: view path of `hello/%`

When you go to `yoursite.com/hello/benia`, it automatically passes the word `benia` to your contextual filter.

Ex2: in `/user/%/profile` when you go to `/user/10/profile` it atomically passes the `10` to your contextual filter, thus only the stuff related to User ID of `10` shows up.

You could go to `/user/sdlfkjlsadfklsdfja/profile` and it passes `sdlfkjlsadfklsdfja` to your contextual filter, but since this value is no good, nothing shows up in your view page.
> 0 votes

---
Tags: views
---


# Question
Title: Repeatation of class while adding class in twig template
I want to add CSS class to `<li></li>` as shown in the following code. There are three `<li></li>` codes where I have added calss using `{{attributes.addClass('')}}`

***from book-navigation.html.twig***

```
{% if tree or has_links %}
  <nav role="navigation" aria-labelledby="book-label-{{ book_id }}">
    {{ tree }}
    {% if has_links %}
      <h2>{{ 'Book traversal links for'|t }} {{ book_title }}</h2>
      <ul>
      {% if prev_url %}
        <li{{attributes.addClass('page-previous')}}>
          <a href="{{ prev_url }}" rel="prev" title="{{ 'Go to previous page'|t }}"><b>{{ '‹'|t }}</b> {{ prev_title }}</a>
        </li>
      {% endif %}
      {% if parent_url %}
        <li{{attributes.addClass('page-up')}}>
          <a href="{{ parent_url }}" title="{{ 'Go to parent page'|t }}">{{ 'Up'|t }}</a>
        </li>
      {% endif %}
      {% if next_url %}
        <li{{attributes.addClass('page-next')}}>
          <a href="{{ next_url }}" rel="next" title="{{ 'Go to next page'|t }}">{{ next_title }} <b>{{ '›'|t }}</b></a>
        </li>
      {% endif %}
    </ul>
    {% endif %}
  </nav>
{% endif %}

```

The output I am getting is with above code is,

>

**But, I want as following,**

```
<ul>
  <li class="page-previuos"></li>
  <li class="page-up"></li>
  <li class="page-next"></li>
</ul>

```

Am I missing something, or there is other right-way to do that? Very Thanks.

# Answer
> 2 votes
If you don't want to add a class, but to replace the existing classes, you can use `setAttribute()`.

```
<li{{attributes.setattribute('class', 'page-previous')}}>

```

# Answer
> 1 votes
`.addClass()` will add the class to the previous class.

> The `.addClass()` function: A function returning one or more space-separated class names to be added to the existing class name(s).

https://api.jquery.com/addclass/

# Answer
> 1 votes
We can use .removeClass() in the link classes to remove previous classes like this,

**Code** -

```
{% if tree or has_links %}
<nav role="navigation" aria-labelledby="book-label-{{ book_id }}">
{{ tree }}
{% if has_links %}
  <h2>{{ 'Book traversal links for'|t }} {{ book_title }}</h2>
  <ul>
  {% if prev_url %}
    <li{{attributes.addClass('page-previous')}}>
      <a href="{{ prev_url }}" rel="prev" title="{{ 'Go to previous page'|t }}"><b>{{ '‹'|t }}</b> {{ prev_title }}</a>
    </li>
  {% endif %}
  {% if parent_url %}
    <li{{attributes.addClass('page-up').removeClass('page-previous') }}>
      <a href="{{ parent_url }}" title="{{ 'Go to parent page'|t }}">{{ 'Up'|t }}</a>
    </li>
  {% endif %}
  {% if next_url %}
    <li{{attributes.addClass('page-next').removeClass('page-up') }}>
      <a href="{{ next_url }}" rel="next" title="{{ 'Go to next page'|t }}">{{ next_title }} <b>{{ '›'|t }}</b></a>
    </li>
  {% endif %}
  </ul>
{% endif %}
</nav>
{% endif %}

```

---
Tags: theming, 8
---


title: View with Colorbox triggered galleries

text:
# Question
Title: View with Colorbox triggered galleries
How can I create a view that consists of images that trigger a gallery of images (grouped by node ID) in a colorbox?

# Answer
> 0 votes
This how you can create a Views gallery that consists of images that each trigger a Colorbox gallery (with grouped images).

This can be done with a pure views approach.

Install the Image URL Formatter module and create a **basic view** (filtered by the desired content type) **with the following fields**:

* Content: Nid
* Content: Images (your field with images)
* Content: Images (the same field, again)

**Configure the fields as follows:**

> **Content: Nid**
>
> * Check "Exclude from display"
>
> **Content: Images** (the first field, which will be the visible cover image)
>
> * Formatter: Image URL
> * URL type: Absolute file path
> * Multiple field settings: display "1" value(s)
> * Rewrite results: `<a href="[field_images]" class="colorbox" rel="gallery-[nid]"><img src="[field_images]" /></a>`
>
> **Content: Images** (the second field, which consists of links to the other images)
>
> * Formatter: Image URL
> * URL type: Absolute file path
> * Multiple field settings: display "all" value(s) starting from "1"
> * Rewrite results: `<a href="[field_images_1]" class="colorbox" rel="event-[nid]"></a>`

I'm sharing this because I couldn't find any reference myself (this approach didn't do it for me).

---
Tags: 7, views, javascript, media
---


# Question
Title: What may cause duplicate nodes to be created using a Rules action to Create New Entity?
I am using a Rule, along with the Rules Block/Unblock User module, to create a specific type of node when a user is unblocked (a simple custom note called "Photo" that contains an image field and a token field for the title). The resulting node is authored by the newly unblocked user. The Rule is currently creating the node, but it is also creating a duplicate of that new node (with the same values). It is important that only one node be created, because I have imposed a limit on the number of nodes each user can create (5 total, including the node created by the Rule).

As a test, I removed the "user\_was\_unblocked" event and replaced it with "user\_insert" ("After saving a new user account"), and that resulted in only one node (no duplicate), but it is important for my process that the node creation occur on unblock instead of creation.

What would cause these duplicates to occur?

Here is an export of my Rule:

```
{ "rules_create_default_public_photo_node_test" : {
    "LABEL" : "Create Default Public Photo Node TEST",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "rules_block_user" ],
    "ON" : { "user_was_unblocked" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "photo",
            "param_title" : "Default Photo for [account:name]",
            "param_author" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
According to the current status of issue # 2783453 (which IMO should be a support request), this looks like something else is happening in your site.

Something that will help you find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with Rules. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

For way more details about Rules **debugging**, refer to the answer to "How can I display the value of a variable inside a condition?".

---
Tags: 7, nodes, rules
---


title: Captcha Failed on Custom Validation

text:
# Question
Title: Captcha Failed on Custom Validation
I use the following validation handler on the login form.

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

```

How can I call the CAPTCHA validation in my validation handler?

# Answer
> 0 votes
This a improved version of your code

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

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

```

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

This will work for you , but I think is better when the situation is not satisfied in validator set error and set a destination variable on $form\_state ( maybe $form\_state\['redirect'\] or your custom $form\_state\['my\_redirect'\] ) then in form\_alter check if your error exists redirect to that destination with Drupal\_goto.

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

---
Tags: 7, forms, captcha
---


# Question
Title: how to name templates for same content types
I have a Content Type machine name as `"aktionsblock_oben"` and made some content and get the Content ID as 33 for this one. Now I can use template name as `page--node--33.html.twig`, but what if I create new content like this where I get another ID? The `page--node--33.html.twig` won't fire.

My try `page--node--aktionsblock_oben.html.twig` or `aktionsblock_oben.html.twig` was a failure.

Any suggestions

# Answer
> 0 votes
By default page.html.twig won't work content type specific pages, you'll have to assign a template file name manually. Check the example below which create a new template name for content type:

```
function [THEME_NAME]_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
  }
}

```

With help of above code, you can use `page--node--aktionsblock_oben.html.twig` template file as your content type template file.

---
Tags: theming, 8
---


title: how to add search box on specific page?

text:
# Question
Title: how to add search box on specific page?
I need to show the search box on that page and specific search if sometime type related news then search result appear. I need only the search box for this content type.

# Answer
> 2 votes
If I understand your question correctly, you want to display the 'Search form' block for a specific content type.

On `admin/structure/block/manage/search/form/configure` you can change the 'Visibility settings' and show the block for specific content types. Below a screenshot where I have selected to display the search form on nodes of my custom content type 'Blog overview':

---
Tags: 7, search
---


title: Customized node edit page

text:
# Question
Title: Customized node edit page
How to customized the node edit page? i was created one cart site for online education. here i need one button to while edit the node one of the content type? how to create an button in node edit page? how to add function for specific function for that button.

# Answer
You can add a button to the node form, with a submit function for that button, using hook\_form\_alter()

```
function hook_form_alter(&$form, &$form_state, $form_id)
{
  $content_type = 'page'; // change as necessary
  if($form_id == $content_type . '_node_form')
  {
    $form['actions']['my_button'] = array
    (
      '#type' => 'submit',
      '#value' => t('Do something'),
      '#submit' => array('my_submit_function'),
    );
  }
}

function my_submit_function($form, &$form_state)
{
  // Do stuff here
}

```
> 2 votes

---
Tags: views, nodes
---


# Question
Title: How to schedule the execution of a Rules Action based on a webform submission date field?
How do I schedule the execution of a Rules Action based on a webform submission date field?

I have installed Webform Rules so I am able to use the Rules Event *Webform submitted* to trigger the execution of a Rules Action. In my case, I want to schedule the execution of the Rules Action based on the date input of a webform field.

I have no problem scheduling the execution using `node:creation time`, but I need to use the date the user inputs.

I have not found any data-selector that let's me do this.

Any hint's will be much appreciated.

EDIT: I have found a link on StackOverflow that seems related to what I want to achieve.

https://stackoverflow.com/questions/5192108/how-do-i-schedule-a-rule-using-fields

That would reduce my question to : how do I use the **Entity has field** on a webform in order to make the field available ?

# Answer
> 1 votes
The "clue" to what you're trying to get to work, is that you have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

All that's left to fully answer your question is to have your rule use similar tokens.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform)
* the *2nd attempt* explains what to do in case of Webform.

# Answer
> 1 votes
I'm not really familiar with Rules but this might be a step in the right direction.

If node:created worked you could give http://drupal.org/project/webform\_tokens a try, it should define tokens for your form components, however I'm not sure if the date will be in the correct format.

If it's not in the correct format you could alter it for the compontent in a presave hook.

```
function hook_webform_submission_presave($node, $submission) {
  // Use dpm() to find out how the date is formatted, and make it into a timestamp.
  $date = strtotime($submission->data['COMPONENT_ID']['value'][0]);
  $submision->data['COMPONENT_ID']['value'][0] = $date;
}

```

Now you have altered the data for the submisison, converting a date into a timestamp which should then be used through webform\_tokens just like node:created.

# Answer
> 1 votes
**Edit:** Okay, re-read the question and I totally missed the point. Removed all the stuff about e-mail processing.

Step #1: Create a hidden field "processed" which can be used to make sure it only gets processed once

Step #2: create a condition, Execute PHP code:

```
<?php

  // Load the webform by its Node ID
  $webform = node_load(123);

  // Load the webform's submissions by the Node ID
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submissions = webform_get_submissions(123);

  // The submission array uses component ids,
  //   so search through the webform and reference component ids by their field name
  foreach($webform->webform['components'] as $component_id => $component)
  {
    if ($component['form_key'] == 'processed')
    {
      $processed_comp_id = $component_id;
    }
    elseif ($component['form_key'] == 'date')
    {
      $date_comp_id = $component_id;
    }
    elseif ($component['form_key'] == 'time')
    {
      $time_comp_id = $component_id;
    }
  }

  // Check all submissions and see if any need to be processed
  foreach($submissions as $submission)
  {
    // First check if the submission has already been processed
    if (isset($submission->data[$processed_comp_id]) &&
        empty($submission->data[$processed_comp_id]['value'][0]))
    {
      // Check the Scheduled Release time
      if (isset($submission->data[$date_comp_id]) && isset($submission->data[$time_comp_id]))
      {
        if (!empty($submission->data[$date_comp_id]['value'][0]) ||
            !empty($submission->data[$time_comp_id]['value'][0]))
        {
          $now = date("U"); // Current UNIX timestamp
          // Check if the current time is still prior to the scheduled time
          if($now < strtotime($submission->data[$date_comp_id]['value'][0]." ".
                                   $submission->data[$time_comp_id]['value'][0]))
          {
            // If it is, continue on to the next submission
            continue;
          }
        }
      }

      // Set the submission to successfully sent, and then update it
      $submission->data[$processed_comp_id]['value'][0] = 1;

      // If it couldn't be updated, change e-mail settings to notify of the error
      if (!webform_submission_update($webform, $submission))
      {
        $email_to = "your@email.com";
        $email_subject = "Error processing scheduled webform rule";
        $email_message = print_r($submission,true);
      }

      // Return True so that it passes the condition
      return true;
    }
  }

?>

```

# Answer
> 1 votes
Turns out the webform submission data is wrapped with it's own type and thus the date fields from webform submissions are not recognized as Dates by the Rules module.

The only workaround I found was to turn my webform into a different node type and use Views to emulate the webform results. The date fields in my custom node types are recognized by the rules module and I can schedule the mails to send.

There is an open issue on d.o. to change the way webform stores it's data.

# Answer
> 0 votes
Shooting in the dark, but perhaps the Entity API module's "Entity Token" sub-module would help. Here is a quote about that sub-module (from the module's project page):

> ... makes sure there are tokens for most entity properties and fields, i.e. it provides token replacements for all entity properties (or fields) that have no tokens and are known to the entity module.

# Answer
> 0 votes
I believe what you are trying to do is not possible. The reason being that webform submission data are not stored in the database. Therefore you can access the webform data only on a event like "When a form is submitted."

But maybe you could give a little more information on the field you are trying to create a rule frοm. Is it a field that you could possible write to a user's profile so you can have access to it without the need to know the sid of the submission? Maybe after saving it to the profile you could find another way to create a rule around that specific field now that is linked exclusively to the user that submitted the form.

---
Tags: 7, webforms, rules
---


title: Adding status message to mail

text:
# Question
Title: Adding status message to mail
currently I'm using two hooks in my hook.module. hook\_form\_alter() and hook\_mail\_alter().

In hook\_form\_alter() I use drupal\_get\_messages() to retrieve the status message.

And I want to use hook\_mail\_alter() to add this message to the email. But I can't pass the message content from one hook to the other.

A global variable is not working. Is there a better way? Another hook I'm not aware of?

# Answer
> 1 votes
I suppose you have tried to use `drupal_get_messages()` within `hook_mail_alter()` as well?

The reason it probably did not return a value is because the default behavior or `drupal_get_messages()` is to clear the message queue (so it empty the second time). You can however make it persistent by passing FALSE as a second parameter (see the documentation).

So in your `hook_form_alter()` use `drupal_get_messages(NULL, FALSE)` and then you should be able to use it again in `hook_mail_alter()`.

---
Tags: hooks, forms
---


title: Upload images in custom modules

text:
# Question
Title: Upload images in custom modules
I work on D7, and create form from custom modules. Create a field upload images by $form\['#attributes'\]\['enctype'\] = 'multipart/form-data'; $form\['image'\] = array(

```
'#type' => 'file',

'#title' => t('Upload picture'),

'#description' => t('Select a picture of at least @dimensionspx and maximum @filesize.', array(

  '@dimensions' => '1000x1000',

  '@filesize' => format_size(file_upload_max_size()),

)),

```

);

Show form correct.

and submit form by hook\_form\_submit(); print $form\_state, upload images not find. How to get values of upload image.

Write Also

$file = file\_save\_upload('image', array( 'file\_validate\_is\_image' =\> array(), 'file\_validate\_image\_resolution' =\> array('500x500', '100x100'), ), 'public://uploaded\_images/', FILE\_EXISTS\_RENAME);

Not find of upload image.

# Answer
> 1 votes
Drupal makes a distinction between regular files and managed files. The first are only stored on the filesystem, the second are stored in the database (managed) as well.

If you use a manged file (type = 'managed\_file') the `$form_state` will contain a file id (fid) of the newly stored image.

Also note that `file_save_upload` takes the file path as the first parameter, so 'image' means nothing there. And that you still have to store your image as a permanent file after `file_save_upload()`:

```
$file = file_load($logo);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'your_module', 'using_entity_type', $entity_id);

```

# Answer
> -2 votes
The values are in $\_FILES.

You shouldn't need to set the enctype of the form, Drupal will handle that for you automatically.

---
Tags: files, media
---


# Question
Title: Why don't breadcrumbs appear on views generated pages?
I'm maintaining a site I didn't build and I'm running into an issue with breadcrumbs. Pages generated by views don't seem to conform to the existing bread crumb system. For example I have a members section page, which has a sub page with a list of links. The links created from basic pages show the correct breadcrumb trail (i.e. home-\>members-\>subpage1-\>subpage2), while the views generated pages only show a breadcrumb trail back to home. So what is causing this? How I work the views pages in the breadcrumb system? Does each views page need it's own template?

# Answer
Have you tried Views Breacrumb / Custom Breadcrubs / Views breadcrumbs modules?
> 1 votes

# Answer
Just so that other people don't run into this issue: I'm using the context module, which lets you sent custom breadcrumbs for each context, supremely useful, better UI than the programmatic approaches.
> 1 votes

---
Tags: views, theming, breadcrumbs
---


# Question
Title: Zen theme doesn't append content titles to breadcrumbs
I've inherited a site with a subtheme designed on Zen 7x-5.4 to maintain and I'm having a problem with the breadcrumbs. I've checked the append content title to breadcrumb options in Appearance=\>Settings however this doesn't seem to have any effect on the breadcrumb trail (i.e. the individual content page titles aren't displayed in the breadcrumb). So, I assume something must be overriding the breadcrumb settings through the UI. I'm not sure what that could be, or where it would be set/configured. I've looked through the template.php, and theme-settings.php files. I have the following options set in the mytheme.info file

```
settings[zen_breadcrumb]           = yes
settings[zen_breadcrumb_separator] = ' › '
settings[zen_breadcrumb_home]      = 1
settings[zen_breadcrumb_trailing]  = 0
settings[zen_breadcrumb_title]     = 0
settings[zen_skip_link_anchor]     = main-menu
settings[zen_skip_link_text]       = Jump to navigation
settings[zen_html5_respond_meta][] = respond
settings[zen_html5_respond_meta][] = html5
settings[zen_html5_respond_meta][] = meta
settings[zen_rebuild_registry]     = 1
settings[zen_wireframes]           = 0

```

But changing the breadcrumb trailing or title values to 1, and flushing the theme registry didn't pull anything off.

For further context, I do have one breadcrumb set with the Path Breadcrumbs module. For development purposes I have css aggregation turned off.

So, what is preventing my theme from adding the content title to the breadcrumbs and or how to do find where the conflict is?

# Answer
The theme breadcrumbs were being overridden by the Path Breadcrumb module. You can fix this in the Path Breadcrumb settings.
> 0 votes

---
Tags: breadcrumbs, theming
---


# Question
Title: How to show a string once you submit a form in a page reloading the page?
I need to create a page with a form and once you enter some values in the form and send it make some calculations and show a string under the form. Something like this image:

I know how to create a page with a form inside and I know how to show a message but in this case I need to show the string (message) under the form.

So, how to show a string once you submit a form in a page reloading the page?

# Answer
> 6 votes
Add the code to calculate and display the result in the form build

```
  public function buildForm(array $form, FormStateInterface $form_state) {
     $form['number1'] = array(
      '#type' => 'textfield',
    );
    $form['number2'] = array(
      '#type' => 'textfield',
    );

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

    $values = $form_state->getValues();
    if (!empty($values)) {
      $result = $values['number1'] + $values['number2'];
      $form['result'] = ['#markup' => '<p>' . $result . '</p>'];
    }

    return $form;
  }

```

So that the result can be included in the form rebuild when the input values are filled in.

In submit request a rebuild:

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }

```

---
Tags: forms, 8
---


# Question
Title: Where does the style guide get generated?
I just enabled the Zen theme, created a new sub theme and ran gulp successfully. On the Zen documentation, it says a gulp task should generate a styleguide for me, but I am not sure what the url is or how to find the generated styleguide.

> Zen now includes a KSS-based living style guide. KSS reads comments in your Sass files and automatically generates a Style Guide that shows how your actual CSS works on your Drupal site.

# Answer
> 2 votes
Once you run `gulp`, the style guide will be generated in

> /path/to/your/theme/styleguide/

Just open the index.html file in your browser to view the contents.

---
Tags: 8, theming
---


# Question
Title: How to show link upload option on statuses updates form which converts to embedded content?
I am using Statuses (Social Microblog) module to allow users to post status updates like other social networks. To enable users to upload photos and videos, there is a module called Facebook-style Micropublisher, which allows users to upload links, photos, videos and documents. The problem with this is that all photos and videos will be saved on my server and for a community site, it is an expensive thing.

To counter that, I installed the great oEmbed module. When the oEmbed input filter is turned on in any of the text formats, It allows users to share a url of the video or photo and it embeds it into the statuses update a user shares. The oEmbed filter is working perfectly, but when a user shares a url of a video or photo with text before or after the url, the content is not embedded and it simply shows a link in the status update.

Now there are few ideas I have in my mind, but I do not know whether those ideas are possible or not. I guess it's a challenge.

**Here are the ideas:**

**IDEA 1.** The Facebook style micro publisher (fbsmp) module allows to attach a link with the status update. It is designed to work as I want, it is not working as it should. If you install and see this module, i think you will get the idea of how it works.

I have read some where that the statuses module's api is flexible and customizations can be done. I am using the dev version of the statuses and flag 2.

**Important note:** It is not necessary that the answer is restricted to my ideas. Anything which solves my problem will do.

# Answer
> 0 votes
So do you want it to act like Facebook aka pulling in content from the link automadgicly? If so then I did have some success with a alter / Ajax callback and then file read contents and pulling in an image tag at appropriate size was not the best solution but look in to https://stackoverflow.com/questions/6476212/save-image-from-url-with-curl-php

And file\_get\_contents()

# Answer
> 0 votes
I went through the module, however I didn't have the time to try out the module. I think there should be a manner to change the way the request is interpreted. Maybe you should try reading parts of the module to see where you can intercept.

* Implement `hook_oembed_request_alter()` to see if you can alter the way the module interprets the request or to see if the module gets a request at all.
* Implement your own `provider` (if need be) and extract / interpret the URL yourself.

I hope it helps. I am interested in the problem. Will see if I can check it out this weekend.

---
Tags: 7, media
---


# Question
Title: Best practice, removing admin access from many websites
hopefully this is not a repeat question, not sure how to search for this.

I run over 50 websites, not all are on the same server but some do hold many users together. Not all our servers are ours, some are ones we inherited.

Now say you have a developer who is admin on a dozen of these sites, is there an easy way to add/remove developer access to multiple servers across many domains in a low-effort manner? I'm looking at Drupal access but also SSH/cpanel access, database passwords and many other related passwords \[LAMP systems\].

It is a pain, as you know, to have to change all passwords on all systems when someone leaves and I was wondering how other people/organizations deal with this issue?

Thanks for any recommendations or thoughts you might have towards this!

# Answer
> 0 votes
Maybe you could use Drush for these operations, such as change passwords for admins ? Also to write a script with several drush commands, which would run via SSH console.

Unfontunately, I am not expert in writing these scripts, but I think that you should look in this direction.

For Drupal 8 another solution Drupal Console has been developed.

P.S. Drush and Drupal Console hardly work on virtual hosting. If you decide to use it, you will have to host your site on VPS as least.

# Answer
> 0 votes
Best practice to provide a centralized authentication for LAMP systems is OpenLDAP. Drupal integration is provided by the module Lightweight Directory Access Protocol (LDAP)

---
Tags: security
---


# Question
Title: Sub-themes .tpl file is not overwriting parents
In my sub-theme, I needed to adjust the HTML of a component that was part of the parent theme. To that effect I copied that components .tpl into my sub-theme's directory and made the alterations.

I then renamed it in accordance to theme debugs file name suggestions. I've done this many time before with no problem.

However, the alterations are not appearing on my site. I've run `drush cc all` and `drush rr` of course, but to not affect.

Would anyone know what's happening here?

# Answer
> 0 votes
Please try to see to follow same folder structure in base theme which parent theme have for .tpl files. Also check if you added base template file e.g. node.tpl.php for node--type.tpl.php link and also implement THEME\_preprocess\_page.

```
function THEME_preprocess_page(&$variables){
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
}

```

---
Tags: 7, theming
---


# Question
Title: How to programmatically create a title for a new node?
I want the title field of each new node of the *Agenda* content type to be constructed automatically from a date field in that same node.

I have variously tried setting the `#default_value` and `#value` on the `$form` array in `hook_form_FORM_ID_alter()` but without effect.

How can I achieve this?

# Answer
Here's how to do it with an entity builder callback.

```
<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

//Implements hook_form_FORM_ID_alter()
function agenda_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    $form['title']['#access'] = FALSE;
    $form['#entity_builders'][] = 'agenda_node_builder';

}

function agenda_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state)
{

    $date_of_meeting = $node->field_date_of_meeting->date->format('Y-m-d');
    $node->setTitle('Agenda for meeting on '.$date_of_meeting);

}

```

**Notes:**

1. I found that the callback had to be set up in `hook_form_BASE_FORM_ID_alter()` rather than `hook_form_FORM_ID_alter` in which case it didn't get called.
Didn't get to the bottom of this but it's probably something to do with the fact that alter hooks are called in the following order: `hook_form_alter()`, `hook_form_BASE_FORM_ID_alter()`, `hook_form_FORM_ID_alter()`.
2. `Node`s `#entity_builders` offer a `Node` entity object for modification before being stored when the form is eventually submitted.

Thanks to @Berdir for the pointers.
> 10 votes

# Answer
Or possibly you could use hook\_entity\_presave() or hook\_node\_presave(), and change the value of the field there.
> 5 votes

# Answer
You can use the Automatic Nodetitles and the Token modules to achieve this.

I know that the Automatic Nodetitles module doesn't have a Drupal 8 version yet, but if you read Port Automatic Nodetitles to Drupal 8, you can find a working solution.
> 3 votes

# Answer
Another way to accomplish this is with this code:

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_node_CONTENT_TYPE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  //Hide the title
  $form['title']['#access'] = FALSE;
}

/**
 * Implements hook_ENTITY_TYPE_create
 */
function MODULE_node_create(NodeInterface $node) {
  switch ($node->getType()) {
    case 'YOUR_CONTENT_TYPE':
      //Change the title
      $node->title = 'TEXT ' . $node->field_YOUR_FIELD->date->format('d-m-Y');
      break;
  }
}

```
> 3 votes

# Answer
The Automatic Entity Label module should be a good solution and has a D8 port (DEV version only for now).
> 1 votes

---
Tags: 8, hooks, forms
---


# Question
Title: Set value of List field of a node with multiple values
I'm attempting to programmatically generate nodes of a custom content type from a form plugin. For most fields I don't have any trouble at all. For example for the title field I can set the value like so.

```
$node->title->value = t('My title');
$node->save();

```

However there is also a list(text) field that allows for multiple values. And I'm not sure how to go about saving values of field with multiple values. I'm assuming if there was only one value allowed I could do it just like I set the title in the previous example, but how do I deal with it when the field is an array? As a test I performed a die statement of the field on a node that already had values in that field to take a look at what it looks like and this was generated:

```
Array ( [0] => Array ( [value] => test_3 ) [1] => Array ( [value] => test_4 ) ) 1

```

But I'm not sure what to do with that. How would I set the field value of a list field with multiple values allowed?

# Answer
You can replace the complete content of a field by assigning an array:

```
$node->field_multivalue = [
  ['value' => '1'],
  ['value' => '2'],
  ['value' => '3'],
];

```

If you want add another value to the field you can use the field like a php array:

```
$node->field_multivalue[] = ['value' => '4'];

```

You can omit the main property of a field:

```
$node->field_multivalue[] = '5';

```

Now you have 5 values in the field.
> 12 votes

---
Tags: nodes, 8, entities
---


# Question
Title: What is the difference between l() and url()?
Why does Drupal provide `l()` and `url()`, which seems to have the same purpose?

# Answer
`l()` creates a clickable link (an HTML anchor tag), while `url()` creates just a url. If you scroll down in the `l()` page you'll see the following source code:

```
  if ($use_theme) {
    return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
  }
  // The result of url() is a plain-text URL. Because we are using it here
  // in an HTML argument context, we need to encode it properly.
  return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';

```

`theme_link()` has a similar construction. So `l()` is using `url()` to construct the anchor.

So summarizing, the one is for clickable links, the other for plain (unclickable) url's.
> 10 votes

# Answer
If I've understood the documentation correctly, function `url($path = NULL, array $options = array())` returns a string, which is URL of given path.

Whereas function `l($text, $path, array $options = array())` has an advanced parameter `$text` and returns an html anchor with given text, given path and options.
> 1 votes

---
Tags: 7
---


# Question
Title: How to change default language for configuration entities?
I made a mistake during the development of my Drupal 8 site. Some time ago I changed the default language (to german) - but I continued to create the configuration entities (like fields and so on) in English.

Now I found out that this was not really smart - and I want to change the default language of all existing configuration entities.

First of all, I just tried to delete the german language - so Drupal 8 switches back to English as default. Now every new configuration entity (new field) is defined in English. That's fine. But every existing configuration entity shows "Unknown (de) (original)" as the default language. And when I open it to save it again nothing changes.

I took a look into the database considering to change it directly there - but unfortunately, the configuration is stored binary.

Is there any other way to solve this problem?

# Answer
I changed the configuration directly in the MySQL table "config" (In my case table names has a prefix ("something\_config") so change the example below if necessary).

The configuration values are in the column "data".

First I cast the content to a string.

Then I replace the definition of the wrong langcode. In my case I replace 's:8:"langcode";s:2:"de"' with 's:8:"langcode";s:2:"en"'.

In the end I cast the result of this replace operation back to binary and save it in "data".

These three steps can be managed in one single SQL statement:

```
UPDATE `config` SET data = cast(
 replace(
    cast( data AS char ) , 's:8:"langcode";s:2:"de"', 's:8:"langcode";s:2:"en"'
 )
 AS BINARY )

```

Then clear the cache and you are done.
> 2 votes

# Answer
Export the full configuration in admin/config/development/configuration. You get the untranslated yaml files in the main folder. The translated yaml files are in languages/\[languagecode\].

The untranslated yaml files have the line

```
langcode: [languagecode]

```

You can change the language code in each yaml file and then import the full configuration back.

If you have translated text in the untranslated yaml files you can move this text to the translated yaml files in the language folder.

For a better workflow put the configuration in the sync folder (sites/default/files/config\_HASH/sync) and import all in synchronize.
> 1 votes

---
Tags: 8, i18n-l10n, configuration
---


# Question
Title: How can I avoid the output of my module is cached?
I have a module I wrote that prints dynamic data for JavaScript variables.

```
function javascript_api_page_attachments(array &$page) {
$page['#attached']['html_head'][] = [
        // The data.
    [
        '#type' => 'html_tag',
        // The HTML tag to add, in this case a  tag.
        '#tag' => 'script',
        // The value of the HTML tag, here we want to end up with alert("Hello world!");.
        '#value' => javascript_api_print_parameters(),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world'
];}

```

My problem is when Drupal caches the page.Need to stop caching my pages in drupal.

How can I avoid the output of my module is cached?

# Answer
> 3 votes
As Eyal mentioned, you can pass the variables from your module to jQuery like this:

**mymodule.module**

```
function mymodule_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'mymodule/auto';
    $attachments['#attached']['drupalSettings']['cool'] = 'hello world';
  }
}

```

**mymodule.libraries.yml**

```
auto:
  version: 1.0
  js:
    js/auto.js: {}
  dependencies:
      - core/jquery

```

**auto.js**

```
(function($, Drupal, drupalSettings) {

    $( document ).ready(function() {
      alert(drupalSettings.cool);
    });

})(jQuery, Drupal, drupalSettings);

```

This will show a js alert message saying "hello world".

# Answer
> 0 votes
I suggest you first create a Js file, put your Js function there then pass desire variable ( or object) to it with using `drupalSettings` and try to get variable(s) in your js files. ( I guess you are know how attach js libraries to page if not take a took at Helper1 and Helper2

```
$page['#attached']['drupalSettings']['myvars'] = $myvars;

```

Then `Drupal.drupalSettings.myvar` will be exists (it's will be dynamic and not cached) in your Js file.

# Answer
> 0 votes
To disable the page cache for anonymous users try the first method:

```
// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

```

Else, you need to set max-age 0 in e.g. hook\_node\_view().

```
function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'yourtype' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

```

OR, if you like to remove cache from route, provide no\_cache in `routing.yml` of your module.

```
newsletter.signup:
  path: '/abc'
  defaults:
    _controller: '\Drupal\your_module\Controller\your_controller::render'
  requirements:
    _permission: 'access content'
  options:
    no_cache: TRUE

```

# Answer
> 0 votes
Thanks for the help i came up to create a new page with a controller and this page will be attached to the page .

```
<?php

namespace Drupal\javascript_api\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class PageParamsController extends ControllerBase {
    public function build(){
        $result = javascript_api_print_parameters();
        return new Response($result , 200 , array('Content-Type'=> 'application/javascript'));
    }}

pageparams:
  # Block the page from being loaded until Modernizr is initialized.
  header: true
  version: "v1"
  js:
    /javascript_api/pageparms.js: { preprocess: 0, weight: -21, minified: true }

```

Now i have a dyanmic js that i can put on the page and to use my Variable in the global area.

Thanks All :)

---
Tags: 8, caching, page-controller
---


# Question
Title: How can I create a view which includes all parent terms of a taxonomy term?
I am creating a view which takes a tid as an argument. I then want to generate the full list of tids which includes the one directly referenced plus all those above it in its taxonomy.

How could I do this?

# Answer
I guess you can't do it directly in views. You can use "Contextual filter: Taxonomy term: Term ID" and write small php code by selecting "Provide default value".

Here is the code you can use:

```
$parent_terms_string = '';
$current_tid = 3; //The term ID of whose all parents you want to fetch.
$parent_terms_tid_array = array();
$parent_terms_array = taxonomy_get_parents_all($current_tid);
foreach($parent_terms_array as $term){
  if($current_tid != $term->tid){
    $parent_terms_tid_array[] = $term->tid;
  }
}
$parent_terms_string = implode('+',  $parent_terms_tid_array);
return $parent_terms_string;

```
> 2 votes

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


# Question
Title: How can I theme the webforms preview page, and what's the template file for it?
I want to alter some data on preview page of a Webform and I want to add a template file for it.

How can I theme the webforms preview page, and what's the template file for it?

# Answer
I find two solution links, please check them:

Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)

Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)

I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.

```
function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

```

And when you create tpl file you can check preview variable to check and theme accordingly.

If this doesn't help try second solution.
> 1 votes

---
Tags: 7, theming, webforms
---


# Question
Title: Contextual links only appear the first time
I know this is a really specific issue, but it's a mystery that annoys me.

The contextual links menu that allows me to edit articles is only showing up the first time I view it. By this, I mean, if I refresh the page, they will no longer work. If I click the edit tab, save the node and let it return me to the node's view page, they work again. But, then I refresh, and they are broken again.

I've noticed that the `focus` class is appended to the article (on hover) on the page when it works, but not when it doesn't work after being refreshed. I've also noticed by debugging that in StateModel.js and VisualView.js, that toggleOpen happens twice (on the broken version -- after refresh), opening and then closing the contextual links menu. But, I can't figure out why.

The content div, which contains the html for the article & contextual links, is 99% identical in bother versions with the only difference being a changed form-build-id for the comments.

The css/js files loaded on the page when it works/doesn't are nearly identical in both versions, with the only differences being a css file that does 2 unrelated things.

This is on both Firefox and Chrome.

If anyone has any ideas, it would really help me sleep at night.

# Answer
> 2 votes
I figured out that someone else has hit this error, and has contributed a patch for it:

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

The patch stops the Contextual Links module from adding a contextual link placeholder to the array if it's already in there. I'm still not quite sure why there's a cookie for the contextual link (as I said in the comment above) if it's going through them and adding them anyway. If anyone else knows more about this issue, feel free to answer.

---
Tags: 8, navigation
---


title: How do I clean up the sessions table?

text:
# Question
Title: How do I clean up the sessions table?
I need to delete entries about anonymous user login from the sessions table.

I read what reported in https://techcommons.stanford.edu/topics/drupal/sessions-table-cleanup.

Which PHP setting in the page above ensures automatic removal of anonymous user login entries from the sessions table handled from Drupal? Do the suggested settings have any effect on that database table?

# Answer
> 1 votes
Go to your Drupal installation directory /sites/default/settings.php and add the following line

```
ini_set('arg_separator.output',     '&');
ini_set('magic_quotes_runtime',     0);
ini_set('magic_quotes_sybase',      0);
ini_set('session.cache_expire',     10800);
ini_set('session.cache_limiter',    'none');
ini_set('session.cookie_lifetime',  10800);
ini_set('session.gc_maxlifetime',   10800);
ini_set('session.save_handler',     'user');
ini_set('session.use_only_cookies', 1);
ini_set('session.use_trans_sid',    0);
ini_set('url_rewriter.tags',        '');
ini_set('session.gc_probability', 1);

```

---
Tags: 6, sessions
---


# Question
Title: Rebuild form is not working in #ajax callback
I've tried to build a form with #ajax submit function and rebuild the form. The following is my code.

```
function campaign_new_form($form, &$form_state){

 if(!isset($form_state['num_names'])){
   $form_state['num_names']=2;
 }

 // Create wrapper for ajax
 $form['#prefix'] = '<div id="form-wrapper">';
 $form['#suffix'] = '</div>';

 for ($i = 1; $i <= $form_state['num_names']; $i++) {
   $form['name_' . $i] = array(
     '#type' => 'textfield',
     '#title' => 'Value ' . $i,
     '#required' => true
   );
 }

 $form['add_button']= array(
  '#type' => 'submit',
  '#value'=> 'Add more',
  '#ajax' => array(
    'callback' => 'campaign_new_form_callback',
    'method' => 'replace',
    'effect' => 'fade',
    'wrapper' => 'form-wrapper',
 ),
);

 return $form;
}

function campaign_new_form_callback($form, &$form_state){
  $form_state['num_names']++;
  $form_state['rebuild'] = true;
  return $form;
}

```

It always renders two fields. What is the problem in my code?

# Answer
> 4 votes
Setting the rebuild in the ajax callback will not work, as the form has already been built at that point. It needs to be set in a submit function, which is fired before the form is built. You also need to increment your counter in the submit function for the same reason - if you do it in the ajax callback, the form is already built so the increment is not saved. It needs to be done in the submit function.

```
function campaign_new_form_submit($form, &$form_state)
{
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

```

---
Tags: 7, forms, ajax
---


title: Converting url() to routing based URL

text:
# Question
Title: Converting url() to routing based URL
I am converting a simple module from Drupal 7 to Drupal 8 and I used the Drupal Module Upgrader to do this. The code has been reformatted and some @FIXME notes have been added, I have no experience developing modules though and I'm not sure what to do.

When I search for more info concerning my problem I found this link https://www.drupal.org/node/2346779 but I'm not sure how to rewrite my code snippet exactly.

This is the .module file.

```
/**
 * @file
 * The littlurl module does little urls.
 */

/**
 * Implements hook_menu().
 */
function littlurl_menu() {
  $items['n'] = array(
    'title' => 'Forward n to node',
    'access arguments' => array('access content'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  $items['u'] = array(
    'title' => 'Forward u to user',
    'access arguments' => array('access user profiles'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  $items['t'] = array(
    'title' => 'Forward t to taxonomy/term',
    'access arguments' => array('access content'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Page callback to forward people along their merry way.
 */
function littlurl_forward() {
  // Get the elements of the URL.
  $args = explode('/', $_GET['q']);

  // Get the elements of the query string.
  $query_string = $_GET;
  unset($query_string['q']);

  if (count($args) > 1) {
    switch ($args[0]) {
      case 'u':
        $args[0] = 'user';
        break;

      case 't':
        $args[0] = 'taxonomy/term';
        break;

      case 'n':
      default:
        $args[0] = 'node';
        break;
    }
    // It's easier to use url than deal with drupal_goto's arguments.
    // @FIXME
// url() expects a route name or an external URI.
// $destination_url = url(implode('/', $args), array('query' => $query_string, 'absolute' => TRUE));

    drupal_goto($destination_url);
  }
  else {
    // This should never happen.
    drupal_goto('<front>');
  }
}

```

This is the Controller.php file. It has the same code the .module file has. Should I remove the redundant code snipped from the .module file?

```
/**
 * @file
 * Contains \Drupal\littlurl\Controller\DefaultController.
 */

namespace Drupal\littlurl\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Default controller for the littlurl module.
 */
class DefaultController extends ControllerBase {

  public function littlurl_forward() {
    // Get the elements of the URL.
    $args = explode('/', $_GET['q']);

    // Get the elements of the query string.
    $query_string = $_GET;
    unset($query_string['q']);

    if (count($args) > 1) {
      switch ($args[0]) {
        case 'u':
          $args[0] = 'user';
          break;

        case 't':
          $args[0] = 'taxonomy/term';
          break;

        case 'n':
        default:
          $args[0] = 'node';
          break;
      }
      // It's easier to use url than deal with drupal_goto's arguments.
      // @FIXME
      // url() expects a route name or an external URI.
      // $destination_url = url(implode('/', $args), array('query' => $query_string, 'absolute' => TRUE));

      drupal_goto($destination_url);
    }
    else {
      // This should never happen.
      drupal_goto('<front>');
    }
  }

}

```

This is a routing.yml file. It seems to be linking to the controller.

```
littlurl.forward:
  path: /t
  defaults:
    _title: 'Forward t to taxonomy/term'
    _controller: '\Drupal\littlurl\Controller\DefaultController::littlurl_forward'
  requirements:
    _permission: 'access content'

```

# Answer
The hooks/functions you shown for the .module file can be removed, since Drupal 8 doesn't use `hook_menu()`; therefore, Drupal will not use the `littlurl_forward()` function defined from the module.

The code in the Controller.php file needs to be rewritten for Drupal 8, since:

* It should not access `$_GET['q']`
* Instead of `drupal_goto()`, it should use the redirect() method of the controller

The first point means you should have three different methods you assign to the three different paths, which makes also more sense. It doesn't sense to assign the same method to three different paths, and the method then still need to understand for which path is being called.

As side notes, keep in mind that:

* If you are editing a module that is already installed, or any of its files, you need to uninstall it first, since Drupal keep in a cache the list of hooks the module is implementing
* The method of a class should not be named like `lower_case()`, but `camelCase()`
* From the code you are showing, it seems you are redirecting from n to node; if that is the case, then you can simply use a path alias
* If instead you are redirecting from /n/node-id to /node/node-id, then it is probably better to use the Pathauto module which creates path aliases for nodes, taxonomy terms, and users (and lets you decide which pattern to use for those path aliases)
* If the routes you are defining get arguments, you should define them in the routes, such as /n/{node}
* If all the routes are doing is allowing to use /n/node-id instead of /node/node-id, I don't see much of a reason to write the code just for that
> 2 votes

# Answer
You need to replace the calls to `drupal_goto()`.

Write this line at top of the file.

```
use \Symfony\Component\HttpFoundation\RedirectResponse;

```

Replace the call to `drupal_goto()` with the following code.

```
$response = new RedirectResponse($url); // $url = '<front>';
$response->send();

```
> 0 votes

---
Tags: 8, page-controller
---


title: How to make twig rules based on paths?

text:
# Question
Title: How to make twig rules based on paths?
I want to make some rules in twig based on current page path. To be precise I want to make the page template look a little different when node is in edit form, revision history page and translation overview.

I want to do something like this, but doesn't seem like working;

```
{% if path('<current>') is path('entity.node.edit_form') %}

```

I want to make rules for all these paths;

```
entity.node.edit_form
entity.node.version_history
entity.node.revision
entity.node.content_translation_overview
entity.node.content_translation_add
entity.node.content_translation_edit

```

Are all available at any page template where a node will be rendered?

# Answer
> 1 votes
Put the route name in a variable in preprocess

**mytheme.theme**

```
function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::service('current_route_match')->getRouteName();
}

```

and use it in twig:

**page.html.twig**

```
{% if route_name == 'entity.node.edit_form' %}
  This is a node edit form.
{% endif %}

```

---
Tags: theming, 8
---


# Question
Title: Creating a Rule condition that evaluates a field an entity that is referenced by a created node
I'm trying to create a rule for new node content that is based on entity references.

To give some background I have story pages and chapter pages. The story pages are story meta data, the chapters are real content. The chapters reference the story pages and are sorted by chapter numbers set by the users.

I want to create a rule for when a new chapter is published. But it needs to be able to evaluate a field on the Story the chapter is a part of. How do I get rules to go to that story entity in question and check the value of the fields in question?

# Answer
Okay, I think I figured out a way to pull this off, and even if it's not the best practice for what I'm attempting to do, it is working.

So like I said, I was trying to create a condition that relies on information contained in a node that is being referenced as an entity. One of the discussion posts indicated I may need to create a component.

So I went to components and created a new component. Data type I set for Any Entity then named it story page (story\_page).

I set conditions that the entity is content, and then a condition where content is of type story page.

Now that we have the content type identified and set we create a condition for list contains item and search for the item in the specific taxonomy I'm looking for.

TO understand this component understand that there are some folk who post more mature content on my page that I DON'T want exposed to the general public. So I require that that kind of content be marked by a specific setting in two fields.

This checks one of those fields and makes the determination. The information however on a chapter for that to be determined is stored in a referenced node which is set in field\_story. You have to be able to get the information from that node, and that information is stored in field\_genre. So the Componenet is built like this.

```
{ "rules_check_for_erotica" : {
"LABEL" : "Check for Erotica",
"PLUGIN" : "and",
"OWNER" : "rules",
"TAGS" : [ "Entity Reference", "Node", "Twitter" ],
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "story_page" : { "label" : "Story\u00a0Front Page", "type" : "entity" } },
"AND" : [
  { "entity_is_of_type" : { "entity" : [ "story-page" ], "type" : "node" } },
  { "node_is_of_type" : {
      "node" : [ "story-page" ],
      "type" : { "value" : { "story_front_page" : "story_front_page" } }
    }
  },
  { "list_contains" : { "list" : [ "story-page:field-genre" ], "item" : "161" } }
]

```

} }

Now, we have a component that can test and figure out if the attached story field has that entry. We can then use it for rules related to story pages to test for it, and make a determination on what to do based on it.

I then created another rule similar to this but it was checking a different field to determine if the story in question is an original story or if it's part of an original series on this page. I then created a new rule to check the chapter page.

```
{ "rules_publish_new_chapter_darkscribes_" : {
"LABEL" : "Publish New Chapter (Darkscribes)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Facebook", "Social", "Twitter" ],
"REQUIRES" : [ "rules", "twitter_actions", "fb_autopost_entity" ],
"ON" : { "node_insert--chapter_page" : { "bundle" : "chapter_page" } },
"IF" : [
  { "component_rules_check_for_original" : { "story_page" : [ "node:field-story" ] } },
  { "NOT component_rules_check_for_erotica" : { "story_page" : [ "node:field-story" ] } }
],
"DO" : [
  { "rules_core_twitter_actions_set_status_action" : {
      "message" : "[node:author] just posted a new chapter for [node:field_story] | Chapter [node:field-chapter-no-]: [node:title] | [node:url]",
      "sender" : "Darkscribes"
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "facebook_publication",
        "param_type" : "post",
        "param_user" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-link" ],
      "value" : [ "node:url" ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-message" ],
      "value" : [ "node:body:summary" ]
    }
  },
  { "publish_to_facebook" : {
      "USING" : { "publication" : [ "entity-created" ], "pages" : "215544991848808" },
      "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
    }
  },
  { "data_set" : {
      "data" : [ "facebook-publication-id" ],
      "value" : [ "facebook-publication-id" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } }
]

```

} }

I tested it to see if it would post a message to one of the two twitter accounts in question, and it SEEMS to have done just right.

I may need to revisit this answer later and add an image or screenshot to it at some point. Or find a way to consolidate my content checking rules.
> 1 votes

---
Tags: entities, rules
---


title: Change button markup of searching form

text:
# Question
Title: Change button markup of searching form
I am trying to find a way out about five hours now, i have studied and tried a lot of different things but i couldn't find the right drupal way to do what i want... Please help with the following.

I have the search-block-form which displays a search input text field and a button. The markup for the button **now** is the following (produced by drupal core):

```
<button class="form-submit" id="edit-submit--2" name="op" value="Search" type="submit">Search</button>

```

I want to add extra markup **inside the `<button></button>`**, like the following:

```
<button class="form-submit" id="edit-submit--2" name="op" value="" type="submit"><i class="fi-magnifying-glass"></i></button>

```

I know of course how to set the value=' ' and i have to say that i've already tried #prefix and #suffix parameters. I don't want to add markup prior to the button element or after that. I should put markup inside, between the element's tags. I tried also change the hook *theme\_button($variables)* but my problem is that i want to change **only** the button for search-block-form and not all the button elements.

As some of you have already understand, i use foundation 5 framework and i want to make the search button like this:

# Answer
*** Updated ***

You can do this by overriding theme\_button() in your theme. Note that the code here is copied from theme\_button(), with the return value adjusted accordingly:

```
function THEMENAME_button($variables)
{
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled']))
  {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  if(isset($element['#search_button']) && $element['#search_button'])
  {
    return '<button' . drupal_attributes($element['#attributes']) . '><i class="fi-magnifying-glass"></i></button>';
  }
  else
  {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

```

Then you need to add #search\_button = TRUE to the button in hook\_form\_alter()

```
function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'MYFORMID')
  {
    $form['actions']['submit']['#search_button'] = TRUE;
  }
}

```

Note: This will render the button as requested. No guarantees that it will actually work with the Form API. That needs separate testing.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: Verify a node with a given node ID exists
I created a module that receives the node ID from the form. On form validation, it needs to verify a node with that node ID exists.

How can I verify it?

# Answer
> 10 votes
You can pass the nid to \Drupal\node\Entity\Node::load(). It will return an object if it exists, NULL if it doesn't.

# Answer
> 17 votes
If you don't want to load the entire node then you can use entity query:

```
$values = \Drupal::entityQuery('node')->condition('nid', $id)->execute();
$node_exists = !empty($values);

```

This will be much more efficient because it only asks for the ids and not all the node fields.

---
Tags: forms, 8
---


# Question
Title: How can I access raw field values in a view template?
I am writing a template for a views field in Drupal 8. How can I access the **raw values** of a multi-value field in views? I tried this but it doesn't work.

```
{% for i in 0.. row.field_color['#items']|length - 1 %}
{{ row.field_color[i] }}
{% endfor %}

```

# Answer
Since you are using it in views-view-fields--styles.html.twig, it would be `{{ fields.field_color.0 }}` or `{{ fields.field_color.content|striptags }}`.
> 2 votes

# Answer
Use the entity to get the raw values from the database:

```
{% for item in row._entity.field_color %}
  <p>{{ item.value }}</p>
{% endfor %}

```
> 1 votes

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


# Question
Title: How to show one field in more than one regions?
I'm using Drupal 7. I have used *two column stacked* layout to display Node Fields. I created one *Rating Field* and I showed it in top region. I want to show the same field in bottom region also. How can I show the same field in bottom region?

# Answer
> 2 votes
You can achieve this using ***Dynamic fields*** in **Display Suite** Module. Check this ans.

Please find the detailed steps below to achieve this:

1. Navigate to **Manage Display** page of *Content Type* and click on "**Add a Dynamic Field**".
2. Add **Unique Label** (e.g. "*Duplicate Field*") to Field and Select valid **Entities (e.g. "*Node*")** based on your requirement.
3. Click on **Save**.
4. This will create a Dynamic Field and Display on ***Managed Display*** page of ***Entities*** you've selected.
5. Re-position newly created field (*i.e. Duplicate Field*) into another region, say as **Footer** and click on **Settings** icon as shown in screenshot.
6. This will open a *display settings* for this field. Click on **Select Content**, to select the field you want to display the content of.
7. From left menu, select **Node** and then click on **Node field (*e.g. "Field: Body (body)"*)**.
8. On next screen, change settings based on your requirement for *displaying label, display formatter* and click on **Continue**.
9. Click on **Finish**
10. Now you need to tell Display Suite that I've selected field and attached it to **Dynamic Field** by clicking on **Update** Button.
11. This will show a preview of *Field Name*, you've attached to Dynamic field.
12. Click on **Save** of *Manage Display* Page.

---
Tags: 7, nodes, entities, display-suite, theming
---


# Question
Title: How do I redirect from /index.php/event/* to /event?
I have old links, for example the following ones.

* index.php/event/nr1
* index.php/event/nr2

If users are coming on index.php/event/\*, they should be redirected to /event.

How can I achieve this?

# Answer
You can use Match Redirect module.
**How to use:**
1) Enable module as usual
2) Go to configuration page /admin/config/search/match\_redirect
3) Add redirect settings there
> 4 votes

# Answer
Check `if(!empty(arg(1))) { drupal_goto('events')}`

You can write this in any of your custom module using hook `modulename_init()` function.

In your case the argument number may change, please do check and change the argument number.
> 0 votes

# Answer
There are Rewrite Rules that can be used to achieve the same thing on drupal 7 as well as on drupal 8. Use this Rewrite Rule in .htaccess file located in Drupal Root directory.

```
RewriteEngine on
RewriteCond %{REQUEST_URI} index.php/event/
RewriteRule ^(.*) http://www.domain.com/event [L,R=301]

```
> 0 votes

---
Tags: 7, uri
---


# Question
Title: How do I redirect users visiting a path matching a regular expression?
My question is the same asked in How do I redirect from /index.php/event/\* to /event? but for Drupal 8.

Since the module suggested in the accepted answer for that question doesn't have a version for Drupal 8, how can I achieve the same with Drupal 8?

# Answer
> 2 votes
In Drupal 8 you use an event subscriber for this. You subscribe to a REQUEST kernel event, get the original url from the request, apply a regular expression and if this finds a replacement set the new url as a 301 redirect response.

**mymodule/src/EventSubscriber/RedirectSubscriber.php**

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirectIndexPHP(GetResponseEvent $event) {
    $old_url = $event->getRequest()->getUri();
    $new_url = preg_replace('|/index.php|', '', $old_url, 1, $count);
    if ($count > 0) {
      $response = new TrustedRedirectResponse($new_url, 301);
      $event->setResponse($response);
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('redirectIndexPHP', 39);
    return $events;
  }

}

```

**mymodule/mymodule.services.yml**

```
services:
  mymodule.redirect:
    class: Drupal\mymodule\EventSubscriber\RedirectSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

```

# Answer
> 0 votes
I believe you can do it as follows (untested):

```
use \Symfony\Component\HttpFoundation;

function somePageCallback()
{
   ...

   return new RedirectResponse('/path/to/redirect/to');
}

```

# Answer
> 0 votes
Here is the Rewrite Rule to be written in .htaccess file located in Drupal Root directory.

```
RewriteEngine on
RewriteCond %{REQUEST_URI} index.php/event/
RewriteRule ^(.*) http://www.domain.com/event [L,R=301]

```

Hope, it makes sense to you.

---
Tags: 8, uri, redirection
---


# Question
Title: How to resolve Catchable fatal error in entity.inc?
Locally (WAMP) I have created a new GIT branch to install Drupal Commerce on my site. Everything went well and I have begun configuring my new shop. But when I decided to pull this branch into my remote test site, I get this error:

> Catchable fatal error: Argument 2 passed to SelectQuery::fields() must be of the type array, null given, called in /home/httpd/mysite/test.mysite.se/includes/entity.inc on line 317 and defined in /home/httpd/mysite/test.mysite.se/includes/database/select.inc on line 1316

Since I can't reach my admin pages (white screen with error message) and Drush stopped working as well, I used MySQL from the command line to import the database on the remote test site. So now both the codebase and the database should be the same on the remote test site as I have locally. Instead I get the above error. Any ideas? I have a feeling that Rules is involved in this, but that's just a feeling.

I have now done everything from the beginning, with the same result. I have installed all the commerce modules and their dependencies (Entity api, Rules, Address field etcetera) in the suggested order. Everything works fine until I export a database dump and add & commit all changes to my new git branch. After pulling that branch and importing the database dump in my test site (or even locally), I get the message above.

I have managed to run cron, which gave me this message:

> User warning: Missing database columns for the exportable entity rules\_config as defined by entity\_exportable\_schema\_fields(). Update the according module and run update.php! i \_entity\_defaults\_rebuild() (rad 872 av C:\wamp\www\sites\all\modules\entity\entity.module).

... allthough I am using the latest version of Rules and when I run the database update, the message is that there is no update pending.

I have also seen this warning:

> Warning: array\_flip() expects parameter 1 to be array, null given i DrupalDefaultEntityController-\>buildQuery() (rad 308 av C:\wamp\www\includes\entity.inc).

Any hints on what I can do to get my site back on track?

# Answer
In case anyone else has a similar problem, here is how I solved it. I began by using Drush to disable the commerce modules one after another (in the correct order) to detect which module caused the error. I got so far that in the end I had disabled all the commerce modules, plus Rules and Entity token. And still the same error message was showing (the first one in my question).

I suspected that I really needed to flush all cache, but I could not reach any page in the site, and still it was not enough to truncate all the cache tables in the db and to run Drush cc all. So what to do? I finally found a way to flush all caches with this snippet (https://www.drupal.org/docs/7/administering-drupal-7-site/clearing-or-rebuilding-drupals-cache) in a file named for example clear.php in the web root:

```
<?php
// Define static var.
define('DRUPAL_ROOT', getcwd());
// Include bootstrap.
include_once('./includes/bootstrap.inc');
// Initialize stuff.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Clear cache.
drupal_flush_all_caches();

```

After saving the above file in the web root, you can just navigate to it whith the browser. In my case I also had to comment out all the memcached rows in settings.php in order for this to work (I got a "Cannot redeclare ..." error message).

When I finally managed to flush all caches this way, the site began to work. I still don't know how I would have done this otherwise. And "Flush all caches" obviously does somehting more than what is accomplished by executing `drush cc all` \+ manually truncating all the cache tables in the database.

So if anyone else has a similar problem with white screens and error messages, first try to flush all caches with the method above. And if you use memcached, you will have to comment out everything that regards memchached in settings.php in order to do this.
> 2 votes

---
Tags: 7, entities, commerce
---


# Question
Title: hook_theme() in a custom file of my module
I'm facing an issue for a few hours now. I created a new module that must render an admin page with some settings and another one with analytics data. The second one must use a custom template file that I created for the occasion.

I added a `hook_theme()` in my **.module** file and everything worked fine for a while.

When refactoring my code I wanted to move the `hook_theme()` in a **subfile.inc** of my module. Even though I cleared the caches, I always get the issue *Theme hook "my\_custom\_template" not found.*.

After moving back the hook in the **.module** file everything work again.

Are they some hooks that must be in the **.module** file only. As the `hook_install()` and `hook_uninstall()` must be in the **.install** file?

# Answer
Just to clarify, you mean the actual hook\_theme() implementation, correct? Not a theme hook you are defining in hook\_theme(). If so, by default, all hooks must be in the .module file. Hooks are meant to be callable at any time, and only .module files are loaded by default on every page load. However you can tell Drupal that a hook is in a different file by implementing hook\_hook\_info():

```
function hook_hook_info()
{
   $hooks['theme'] = ['group' => 'theme'];

   return $hooks;
}

```

With this code, Drupal will look for the hook (the array key 'theme') in the file MODULENAME.GROUPNAME.inc. In this case your GROUPNAME is defined as 'theme' in hook\_hook\_info(), so Drupal will load MODULENAME.theme.inc, whenever hook\_theme() is invoked.

Now, if you meant that you want to put a theme hook that you define inside hook\_theme() in another file, then you need to declare the file for that theme hook:

```
function hook_theme()
{
  return array
  (
    'some_theme_key' => array
    (
      'variables' => array(),
      'file' => 'path/to/file.inc', // relative to module root
    ),
  );
}

```

In this case, when the system tries to load the theme some\_theme\_key, it will load the file \[MODULEFOLDER\]/path/to/file.inc.
> 3 votes

# Answer
Try using **module\_load\_include()** in your custom\_module.module to load your .inc file
> 1 votes

# Answer
Try adding the reference to your file subfile.inc into info-file of your module.

```
files[] = subfile.inc

```
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Is it possible to give a language prefix to all the nodes without third-party modules?
I have a site with about 500 pages, all in Hebrew. I want to change all the all paths to include the language prefix. This would be the first stage in turning this site into a sub-site (with a sub-domain).

Is this possible without third-party modules?

# Answer
> 3 votes
These are the rewrite rules to add in the .htaccess file located in the Drupal root directory.

```
RewriteEngine on
RewriteCond %{REQUEST_URI} !/he
RewriteRule ^(.*) http://www.domain.com/he%{REQUEST_URI} [L,R=301]

```

# Answer
> 3 votes
Since you are making this specific to a language prefix, I would suggest using the Language module, since it is part of Drupal core and it's easy to manage.

Enable the Language module, which isn't enabled by default, unless you made your site explicitly multilingual, your content is in Hebrew, but your site default language is English.
You need two languages for the language prefixing to work. On /admin/config/regional/language, add a second language. This will enforce the use of language prefixes.
On /admin/config/regional/language/detection, configure the URL detection method; this should be in fact activated and preceding all other options. Set the path prefix for the default language to *he*.
Save and clear the cache. All your Drupal paths now will be prefixed by *he*.

The existing URLs are still valid. A couple of clicks into navigation and your URLs should be prefixed with *he*.

# Answer
> 2 votes
If you wish to have different subdomains for different languages, I think Drupal should be able to detect the language code from the sub-domain and there should be no necessity for adding URL prefixes. You can take the first step by setting up the sub-domain `he.example.com` and redirecting requests from your main site to the `he` subdomain until you add other languages and a language selection dialog in `example.com` (without sub-domains).

Hello! I can see the following solutions:

**Solution 1: Altering node paths**

* Using pathauto (which you do not wish to use) you can set the node prefix to `/he/`.
* Running a one-time script to add a prefix to all node URL aliases and in the future adding the `/he` prefix manually.

**Solution 2: .htaccess**

Using `.htaccess` to re-write all URLs to interpret `/he/*` URLs as `/*`. But this might also apply the prefix to other paths - doing this only for nodes might be difficult depending on their existing URLs.

```
RewriteEngine on
RewriteCond %{REQUEST_URI} !/he
RewriteRule ^(.*) http://www.domain.com/he%{REQUEST_URI} [L,R=301]

```

**NOTE:** Code extract copied from Ashish Deynap's answer.

But I've heard that it is better to avoid `.htaccess` redirects as far as possible because:

* The `.htaccess` might be updated with Drupal versions.
* The rules in `.htaccess` are evaluated for every request! The more rules you have, the more time the server spends evaluating them.

Hope it helps.

---
Tags: 8, uri
---


# Question
Title: How do I create translation without default language content?
In Drupal 8, my default language is English, but I also have German. How can I create a content item that will only be available for German, and not in English? In other words, how do I created "translated only" content?

When I add new content, I can use the Language select box, but it still creates content available in the English language.

# Answer
It used to take several contributed modules to make even a small multi-lingual Drupal 7 site. Now, you can translate everything using just the Drupal 8 core.

**Step 1: Enable the translation modules**

You need to enable these four core Drupal modules in order to translate your site.

**Step 2: Translate the Drupal core**

First, let's translate of the core language inside the Drupal. In this example, I'm going to add Spanish as an option on my site:

* Go to Configuration \> Languages
* Click "Add language"
* Choose your language and click "Add language".  Click on the percentage area, under "Interface Translation".  You'll be able to search for and manually translate all the language strings in here:  **Step 3: Translate your own site set-up**
* Go to Structure \> Content types, you'll see a "Translate" option for your content types:
* Inside the next screen, you'll see similar "Translate" links for all your fields:

**Step 4: Add content**

Now we can add content to your Drupal site.

* Go to Configuration \> Content language and translation.
* Click the box next to "Content":

**Note:** This is an important step as you can set a specific translation for your content type. That means, the content type default language will be set to a particular language(like German).

> After this step, all content of "Biography" type will be by default translated to german.
> 1 votes

# Answer
In your node type multilingual settings, you can switch to fixed language. (Sorry for my short answer, I'm using my phone)
> 0 votes

---
Tags: 8, i18n-l10n
---