# Question
Title: Selecting from a column in a joined table in Views
I've got two tables: {students} and {student\_names}. Students is the base table, with a primary key of {students}.sid. Student names is the joined table, and has a key of {student\_names}.sid.

I've defined my join in hook\_views\_data:

```
$data['students']['table']['join']['student_names'] = [
  'left_field' => 'sid',
  'field' => 'sid',
];

```

I want to select the given name of the student from the joined table. I've defined the field as follows (again in hook\_views\_data()):

```
$data['students']['given_name'] = [
  'title' => t('Given name'),
  'help' => t('The given (first) name of the student'),
  'field' => [
    'handler' => 'views_handler_field',
 　　'click sortable' => TRUE,
  ],
  'sort' => [
    'handler' => 'views_handler_sort',
  ],
  'filter' => [
    'handler' => 'views_handler_filter_string',
  ],
  'relationship' => [
    'base' => 'student_names',
    'field' => 'sid',
    'handler' => 'views_handler_relationship',
  ],
];

```

I'm getting this error:

> Column not found: 1054 Unknown column 'students.given\_name' in 'field list'

How can I tell views that the column is in the {student\_names} table and not the {students} table?

# Answer
> 1 votes
I solved my own issue.

I needed to expose the joined table to views as well. So on top of setting up $data\['students'\], I also needed to set up $data\['student\_names'\], with a join back to the original table. Here is my hook\_views\_data() in its entirity:

```
$data['student_names']['table'] = [
  'group' => t('Student'),
  'base' => [
    'field' => 'sid',
    'title' => t('Student'),
  ],
  'join' => [
    'students' => [
      'left_field' => 'sid',
      'field' => 'sid',
      'type' => 'inner',
    ],
  ],
];

$data['student_names']['given_name'] = [
  'title' => t('Given name'),
  'help' => t('The given (first) name of the student'),
  'field' => [
    'handler' => 'views_handler_field',
    'click sortable' => TRUE,
  ],
];

return $data;

```

---
Tags: 7, views
---


title: How to use Webform values in Rules?

text:
# Question
Title: How to use Webform values in Rules?
I am using the **Webform Rules** module and I created an event '*After submitting webform*', and an action '*Fetch webform submissions*'.

When I add an action '*Show a message on the site*', I get all the webform data values and I can print them out in status message.

Now I want to **Get the user ID who submitted the webform** to send that user a private message (about the form data). But when I add an action '*Fetch entity by ID*', I get no webform data values there (I'd like to use a data value as entity ID).

Am I missing something, is this the right way to achieve this ? Any other idea on how to do this please?

# Answer
> 0 votes
Using the Webform Rules module is indeed part of the puzzle to answer your question, as you can read also on its project page:

> This module adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event?
>
> Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

### 1. Get the user ID who submitted the webform

Have a look at this example rule (in Rules export format):

```
{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

I intentionally did not include any Rules Conditions here, just to illustrate that by using the Rules Event you're already using, you do have access to a limited set of tokens related to the user who submitted the webform, such as `[user:id]`, `[user:name]` and `[user:mail]`. In other words, you don't need a Rules Action like "*fetch entity by ID*" for these kinds of tokens to be available.

Of course, because of the nature of your question, you may want to add a Rules Condition to check that the user is not an anonymous user.

### 2. About the Webform data

The "Webform data"-part of your question seems like an example (variation?) of what's asked for in the feature request "Expose submission data to rules". Here is a summary of it:

> Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue though.

The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

> You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words: checkout the screenprint included in that comment.

So you could use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
* In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

PS: I'm assuming this question is about D7.

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


# Question
Title: How to solve a situation where two or more routes with different controllers point to the same path ?
For example, we have two routes, which points to the same path.

And each route has its own controller.

For example, I have defined a route with controller, which has a path "node/1", whereas a node with id=1 is already added to the site.

How can we determine, which controller will be started ?

And how can we select and assign forcibly controller to start, which we need ? For example, in my case for path "node/1" we don't want to start the NodeController, but we want to use the controller, defined in our module. Or Vice versa.

# Answer
> 4 votes
Drupal uses always the most specific route. If you define for the path `/node/1`

**mymodule.routing.yml**

```
route.for.node.1:
  path: '/node/1'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::content'
    _title: 'Override of node 1'
  requirements:
    _permission: 'access content'

```

then the custom controller `\Drupal\mymodule\Controller\MyController::content` is used instead of the node controller `\Drupal\node\Controller\NodeViewController::view`.

But I don't understand "Or Vice versa". For that you would have to remove the more specific route, so that the less specific node route for `/node/{node}` can take over again.

If you want a dynamic solution, you can route all nodes to your custom controller and then decide in this controller what to do, display the node or your own content.

For this you can extend the NodeViewController class and define a new view() function, in which you call parent::view() for the original node content. Then replace the class in a route subscriber:

```
$route->setDefault('_controller', '\Drupal\mymodule\Controller\MyController::view');

```

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

---
Tags: 8, routes
---


# Question
Title: Views 3.8: Show taxonomy hierarchy in three columns (grandparent, parent, child)
I have a taxonomy with a three-level hierarchy, and would like to display the three levels in a views table, but separately. I'd also like to have an exposed filter using that taxonomy and let my users pick the term.

Here's what I've done:

1. Added the contextual filter **Has taxonomy term id depth modifier**
2. Added the relationship **Content: Taxonomy terms on node** with an identifier "term"
3. Added the relationship **Taxonomy term: Parent term** with an identifier "Parent" and set its relationship as "term"
4. Added the contextual filter **Taxonomy term: Parent term** and selected the "Parent" relationship
5. Added the taxonomy term field

At this point I can display the hierarchy in a single column and can choose between the lowest level child or all three (e.g. Grandparent \> Parent \> Child). However, I want to be able to display the grandparent, parent and child in separate columns.

Is this possible? I was hoping to maybe add the field three times and pick the hierarchy level, but I don't see how to do that.

# Answer
> 3 votes
If you've only 3 level of hierarchy then you can create a view as below:

Above view should give the output as below:

Hope this helps.

# Answer
> 0 votes
First you need to generate the desired **3 column table** without *Views*. Then you can use *Views*'s to load the desired *nodes* with contextual filters. Possible to do following the stes below, but there is many different ways to do.

1. Create a **module** with the mymodule\_taxonomy\_get\_tree\_nested() **function**
2. **call** it from the template.php
3. figure out what and how do you want to **display**
4. you can **render** Arrays with Drupal after some *"makeup"*
5. load the desired content with **View**, using the *Content: Has taxonomy term ID* **contextual filter**

# Answer
> 0 votes
Also. I believe, you can use ready-done module for it https://www.drupal.org/project/views\_tree.

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


# Question
Title: Drupal files folder owner/group for CentOS?
This is my first time installing Drupal on CentOS. I know for Ubuntu it needs to be `www-data` as the /files folder owner, but what is it for CentOS?

# Answer
> 6 votes
I faced with this issue before, it was because of SELinux on CentOS, So you should try to Disable SELinux on Centos

> From the command line, you can edit the /etc/sysconfig/selinux file. This file is a symlink to /etc/selinux/config. The configuration file is self-explanatory. Changing the value of SELINUX or SELINUXTYPE changes the state of SELinux and the name of the policy to be used the next time the system boots.

```
[root@host2a ~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0

```

Change it from `SELINUX=permissive` to `SELINUX=disabled`

Once you have saved the changes `sudo shutdown -r now` to restart now.

---

Also you can disable it temporary ( until next restarting ) with

```
sudo setenforce 0

```

How to Disable SELinux

# Answer
> 2 votes
In CentOS, Apache/HTTPD username is normally `apache`. During installation, `apache` user should have read-write access to `sites/default` directory.

After installation, `apache` user should have read-write access to the `sites/default/files` directory. Check Drupal Docs for more details on file permissions.

***Note:*** *If giving permissions doesn't help, make sure `SELinux` is disabled. Check @zhilevan's ans above.*

---
Tags: 7, files
---


# Question
Title: Create a Rules link to update a field in a submitted webform
I have a view which is a list of submitted webforms. I want to add a link using Rules link that, when clicked, updates a field in the submitted webform (specifically, updates a hidden field with the current date).

Is this possible?

# Answer
> 0 votes
Have a look at what's asked for in the feature request "Expose submission data to rules", status is "Needs review". Here is a summary of it:

> Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

So if submission data are not even exposed yet (in the current version of Rules), then it might not be obvious (if possible at all) to update such data.

### Possible alternative

I'd rather try to come up with some kind of alternative for such hidden field to "record the clicking of such link" (also using the Rules Link module). A possible alternative is to use the Message module to create a message like so:

* Date = date the link was clicked.
* User target = the user who clicked the link.
* Message type = something like "Webform processed via Rules link").
* message text = whatever you want and possibly using "Replacement tokens" to have any of the available webform tokens available in your rule included in your message text also.

Since messages are entities, you could add any additional fields you may need to complete such custom logging.

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


title: How do I load taxonomy terms?

text:
# Question
Title: How do I load taxonomy terms?
I want to load taxonomy terms by tid, but I didn't found how. Only how to load taxonomy by name, but now I have term id and I need to get value of fields.

I call this on public function `build()` for custom block.

My code:

```
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('menu');
foreach ($terms as $term) {
    //var_dump($term->tid);
}

```

# Answer
in Single Manner

```
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(TID);
    $value = $term->FIELD_MACHINENAME->value;

```

Example : load title and language of term id =2

```
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(2);
    $title = $term->name->value;
    langcode = $term->langcode->value;

```

And for load Multiple as you wanted

```
  $terms = $entityManager->getStorage('taxonomy_term')->loadMultiple($terms);
  foreach ($terms as $term) {
      var_dump($term->tid->value); //return tid of term
   var_dump($term->name->value); //return title of term
  }

```
> 20 votes

# Answer
You can also do like this:

```
$tids = [1,2,3];
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);

```

Example from : http://www.drupal8.ovh/en/tutoriels/17/get-taxonomy-terms-of-a-vocabulary-drupal-8
> 9 votes

---
Tags: 8, taxonomy-terms
---


# Question
Title: How to create horizontal tabs using FAPI?
I have a custom form where I need to group fields with horizontal tabs, seems Drupal Core doesn't have something similar for horizontal tabs like it has for vertical tabs, I'm constrained to use Drupal Core API (no contrib dependencies).

Thank you for any help!

# Answer
> 1 votes
Maybe you should use twig template + JQuery for it ?

That is, you create a twig template for your form, add it to your theme and also add the JQuery widget for Tabs ?

---
Tags: forms, 8
---


title: Add attributes to the render array

text:
# Question
Title: Add attributes to the render array
I am trying to add some attributes to a render array. In Drupal 7, we can do this by adding a property in an array like the following.

```
$items[] = array('data' => $item_data, 'id' => 'someId'); // attribute = 'id'
$variables['subpanels'] = theme('item_list', array('items' => $items, 'title' => NULL, 'type' => 'ul'));

```

In Drupal 8, there's no `#attributes` property documented in Render Arrays in Drupal 8. How can I add this **id** as an attribute in a render array, with Drupal 8?

This is the code I am using so far.

### mymoduleController.php

```
public static function _mymodule_f1($users_online) {
  $user = \Drupal::currentUser();

  $render_array_1 = array();
  $render_array_1['name'] = 'test-name';
  $render_array_1['header'] = t('test-header');
  $render_array_1['contents'] = array('#value' => '<div class="test_options">' . '<a class="test_loading" href="#"></a>'. '</div>');

  $items = array();
  foreach ($users_online as $key => $value) {
    if ($key != 'total') {
      $items[] = array('#value' => '<a class="' . $key . '" href="#">' .   $value['name'] . '</a>', 'class' => array('status-' . $value['status']));
    }
  }
  //print_r($items);
  if ($items) {
    $item_list = array(
      '#theme' => 'item_list',
      '#items' => $items,
    );
    $render_array_1['footer'] = $item_list;
  }
  $render_array_1['text'] = array('#value' => t('T1') . ' (<span class="online-count">' . count($items) . '</span>)');
  $image = [
   '#theme' => 'image',
   '#uri' => drupal_get_path('module', 'mymodule') . '/css/themes/images/loading.gif',
   '#width' => NULL,
   '#height' => NULL,
   '#class' => 'icon'
  ];

  $render_array_1['icon'] = $image;
  $mymodule_subpanel = array(
    '#theme' => 'mymodule_subpanel',
    '#subpanel' => $render_array_1
  );
  return $mymodule_subpanel;
}

```

### mymodule.module

```
function mymodule_theme() {
  return array(
    'mymodule' => array(
      'variables' => array('mymodule' => NULL),
      'template' => 'mymodule',
    ),
   'mymodule_subpanel' => array(
     'variables' => array('subpanel' => NULL),
     'template' => 'mymodule-subpanel',
   ),
 );
}

function mymodule_preprocess_mymodule(&$variables) {
  $items = array();
  $users_online = mymoduleController::f2();
  $render_items = mymoduleController::_mymodule_f1($users_online);
  $render_items['#attributes'] = array('id' => 'some_id'); //not working; unable to add id='some_id' in the <li> tag.
  //print_r($render_items);

  $items[] = $render_items;
  //print_r($items);

  $item_list = array(
    '#theme' => 'item_list',
    '#items' => $items, // array of render arrays.
    '#title' => NULL,
    '#list_type' => 'ul',
    '#attributes' => array('id' => 'mainpanel')
  );
  $variables['subpanels'] = $item_list;
}

```

# Answer
Render arrays can contain render elements or theme templates.

Example for a render element:

```
'#type' => 'link'

```

and a theme template:

```
'#theme' => 'item_list'

```

Render elements have the parameter `#attributes`. This is defined in the base class `Drupal\Core\Render\Element\RenderElement` that all render and form elements are extended from.

That is not the case for templates in general.

The template `links` for example has `#attributes` and handles this in `template_preprocess_links()` in /core/includes/theme.inc.

The example from the question is `item-list`. This template has a variable `#wrapper_attributes`. You can see in the first line of the preprocess function how `wrapper-attributes` is transformed in an attributes object, which is then passed on to the twig template where it is placed in the list wrapper:

```
/**
 * Prepares variables for item list templates.
 *
 * Default template: item-list.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - items: An array of items to be displayed in the list. Each item can be
 *     either a string or a render array. If #type, #theme, or #markup
 *     properties are not specified for child render arrays, they will be
 *     inherited from the parent list, allowing callers to specify larger
 *     nested lists without having to explicitly specify and repeat the
 *     render properties for all nested child lists.
 *   - title: A title to be prepended to the list.
 *   - list_type: The type of list to return (e.g. "ul", "ol").
 *   - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 *
 * @see https://www.drupal.org/node/1842756
 */
function template_preprocess_item_list(&$variables) {
  $variables['wrapper_attributes'] = new Attribute($variables['wrapper_attributes']);
    foreach ($variables['items'] as &$item) {
    $attributes = array();
    // If the item value is an array, then it is a render array.
    if (is_array($item)) {
      // List items support attributes via the '#wrapper_attributes' property.
      if (isset($item['#wrapper_attributes'])) {
        $attributes = $item['#wrapper_attributes'];
      }

```

The template `item_list` has also the variable `attributes`, which is passed on to the twig template. Here you can see how this all ends up in the html markup, including the attributes of the items, which are collected for each item from wrapper-attributes in preprocess:

**item-list.html.twig**

```
{#
/**
 * @file
 * Theme override for an item list.
 *
 * Available variables:
 * - items: A list of items. Each item contains:
 *   - attributes: HTML attributes to be applied to each list item.
 *   - value: The content of the list element.
 * - title: The title of the list.
 * - list_type: The tag for list element ("ul" or "ol").
 * - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 * - attributes: HTML attributes to be applied to the list.
 * - empty: A message to display when there are no items. Allowed value is a
 *   string or render array.
 * - context: A list of contextual data associated with the list. May contain:
 *   - list_style: The custom list style.
 *
 * @see template_preprocess_item_list()
 */
#}
{% if context.list_style %}
  {%- set wrapper_attributes = wrapper_attributes.addClass('item-list--' ~ context.list_style) %}
  {%- set attributes = attributes.addClass('item-list__' ~ context.list_style) %}
{% endif %}
{% if items or empty -%}
  <div{{ wrapper_attributes.addClass('item-list') }}>
    {%- if title is not empty -%}
      <h3>{{ title }}</h3>
    {%- endif -%}
    {%- if items -%}
      <{{ list_type }}{{ attributes }}>
        {%- for item in items -%}
          <li{{ item.attributes }}>{{ item.value }}</li>
        {%- endfor -%}
      </{{ list_type }}>
    {%- else -%}
      {{- empty -}}
    {%- endif -%}
  </div>
{%- endif %}

```

Btw. the wrapper is only placed in the classy theme, the base theme doesn't use this.

**Conclusion:**

Templates don't have attributes by default. As the examples show, they can handle them like render elements, under a different variable name or not at all.
> 5 votes

# Answer
I hope this example may help you.

Step 1. Create your module and Block (http://www.drupal8.ovh/tutoriels/107/create-a-simple-block-programmatically)

Step 2. Add your template usin hook\_theme() (here module name = clock)

Example:

```
function clock_theme($existing, $type, $theme, $path) {
  return array(
    'clock' => array(
      'variables' => array(
        'icon' => NULL,
        'title' => NULL,
        'time' => NULL,
      ),
    ),
  );
}

```

You cal also use template\_preprocess to handle your template Example:

```
function template_preprocess_clock(&$variables) {
  //Add global classes
  $variables['attributes']['class'][] = 'my_clock';
}

```

Step 3. Create the twig template in clock/templates/clock.html.twig Example:

```
<div {{ attributes }}>
  {% if icon %}
    <img class='clock_block_icon' src='{{ icon }}' alt='{{ title }}'/>
  {% endif %}
  <div class="clock_block_title" >{{ title }}</div>
  <div class="clock_block" data-time="{{ time }}"></div>
</div>

```

Step 4. Add the template to your block or page, using the render array Example :

```
return array(
      '#theme' => 'clock',
      '#icon' => $icon,
      '#title' => 'The Title',
      '#time' => "The Time is : ".date('H:i:s'),
    );

```

http://www.drupal8.ovh/en/tutoriels/140/add-twig-template-to-a-custom-module-block-or-page

And also this one

```
$output[] = array(
  '#type' => 'inline_template',
  '#template' => '{{ yourvar }}',
  '#context' => array(
    'yourvar' => 'The Value',
  ),
);
return $output;

```

http://www.drupal8.ovh/en/tutoriels/154/inline-template-drupal-8-and-twig
> -1 votes

---
Tags: theming, 8
---


# Question
Title: How to apply authentication to rest endpoint URL?
I can access the rest endpoint URL for a node in JSON format (e.g. https://192.168.1.235/rest\_endpoint/node/1142?\_format=json) even if we are not logged-in to the sever.

Is there any way to apply authentication to access this URL?

# Answer
> 1 votes
Since rest callbacks run through Drupal's normal roles/permissions layer, you can just disable the `View published content` permission for anonymous users, then they won't be able to fetch the JSON for the View.

If you need finer grained control, you'll have to use hook\_node\_grants().

---
Tags: 8
---


title: hook_page_alter called once

text:
# Question
Title: hook_page_alter called once
I have a Drupal 7 theme which is a Bootstrap child theme.

In my version of page.vars.php, I have a `THEME_page_alter()` call which runs only once until I do a clear cache. Other hooks such as `THEME_process_page` or `THEME_preprocess_page` are called each time I reload the page.

A second theme, with the same page\_alter hook works just fine and is called each page-reload without the need for a clear-cache first.

What could be causing this?

# Answer
Theme settings are specific to each theme. Go to /admin/appearance/settings/yourtheme and check for any theme-specific caching options. I can't tell you exactly what the options would be because that depends on your theme.
> 0 votes

---
Tags: 7, hooks, theming
---


# Question
Title: how to change alphabetic order to descending order in drupal 7
I have a accordion menu in left side and the menu list come as alphabet order but i want newest come first. how can i change the sorting of that list.

# Answer
Drupal menu items are manually ordered. You can drag and drop into the correct order here: /admin/structure/menu/manage/navigation
> 1 votes

---
Tags: 7, views
---


title: hook_entity_presave() doesn't work

text:
# Question
Title: hook_entity_presave() doesn't work
I want to save some details before saving the node, and I tried with `hook_node_presave()`.

```
function hook_node_presave(Drupal Core Entity EntityInterface $node) {
  if ($node->id() && $node->moderate) {
    // Reset votes when node is updated:
    $node->score = 0;
    $node->users = '';
    $node->votes = 0;
  }
}

```

Then with `hook_entity_presave()`.

```
function hook_entity_presave(Drupal Core Entity EntityInterface $entity) {
  $entity->changed = REQUEST_TIME;
}

```

Both hooks don't work. Why?

# Answer
> 4 votes
You can do it like this.

```
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

```

http://drupal8.ovh/en/tutoriels/65/update-a-node-entity-programmatically-drupal-8

# Answer
> 4 votes
Your function should be named according to your module's name. If your module is called "foo", then:

```
function foo_node_presave(Drupal\Core\Entity\EntityInterface $node) {

```

Note also the use of backslashes, not spaces, to separate namespaces.

---
Tags: 8, hooks
---


# Question
Title: How to hook into "visiting the website"?
My main problem is very similar to How to grant userpoints to users who perform a login 5 days consecutively?. As Mike correctly notices in his answer on that question, his solution will not work for users who leave their browser logged in. Therefore, I do not want to hook into a login, but into "visiting the website" (i.e. accessing *any* page).

I am fine with both Rules and custom code. In the first case, which Rules event can I use? For performance reasons, it is in both cases desirable that the hooking takes place as few times as possible (in the best case once a day per visiting user). Is restricting the visited page to a particular one, say, the homepage the only way to achieve that?

# Answer
> 1 votes
Using Rules Event "***Drupal is initializing***" (within "System") for sure will do the job:

* It doesn't depend on login (can be used for any role).
* It applies to any path (a node, a view, etc).

Should you want to do so, you can also add any desired Rules Conditions (eg to only consider selected paths, eventually using RegEx expression also).

### Make it right before you make it better

I'm not sure this is the *only* way your question can be answered, but I do know that this Rules Event (*Drupal is initializing*) *will* do what you're asking for, which is to **hook into "visiting the website" (i.e. visiting *any* page)** (as in your question).

But, using this Rules Event also comes with a price: it will case this rule to be triggered on every page request (which is a pretty similar to your *visiting any page*). However, if this price is too high, maybe you want to consider any (or all?) of these compromises:

* Add Rules Conditions such as "only for users with selected roles" (eg: authenticated, so that for Anonymous users the Rules Actions are not triggered).
* Instead of **any** page, you only take into consideration something like "viewing content" (for which you know there are less expensive Rules Events available).

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


# Question
Title: When can I use a custom field type instead of a custom entity?
I come from an SQL background and I'm still navigating fields/entities. I have a custom entity (analysis) to record information about a laboratory sample (what it is, when and where it was taken, and what analysis method was applied to it). The analysis will return many independent results. I was thinking of making a second entity (results) with an entity reference to the analysis entity, the name of the chemical that was measured, and the concentration that was measured.

However, could I instead make a custom field\_type that is combination of the chemical name and its concentration? Then I could include this chemical\_result as a field in my analysis entity with

```
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)

```

to include multiple chemical results in one analysis, right? When is it appropriate to use a custom field versus an entity?

I also have an entity called "chemical" that has information on chemicals of interest. If I use an entity for my results, I know I can make an entity\_reference to the chemical entity, which would allow some more complex queries down the road. Can I do the same with a custom field? If not directly, I'm assuming I could program the add\_analysis form to only allow certain values for chemical name when adding data to the result field, correct?

# Answer
> 2 votes
Custom entities and custom fields are not mutually exclusive, you can use them together.

You can build a custom field type with more than one property. See for example the Password field which defines three properties:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21PasswordItem.php/function/PasswordItem%3A%3ApropertyDefinitions/8.2.x

You can also extend the entity references field. See for example the File field:

https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Plugin%21Field%21FieldType%21FileItem.php/function/FileItem%3A%3ApropertyDefinitions/8.2.x

The File field adds two properties to the reference field. In your case you would add the properties chemical name and concentration to a reference field which points at the analysis entity.

---
Tags: 8, entities
---


# Question
Title: Add title and alternate text to image automatically?
In my site users can upload content and also images.

My goal is that when a user is uploading content to the site, and also an image - the title of the content will be also the image title and the alternate text of the image. Currently I am using the core image field.

Is there a way or a module that can achieve all that?

# Answer
The most direct way might be to do something along these lines in hook\_node\_presave() in a custom module:

```
function YOURMODULE_node_presave($node) {

  if(isset($node->field_image)) {
    $node->field_image[LANGUAGE_NONE][0]['alt']=$node->title;
    $node->field_image[LANGUAGE_NONE][0]['title']=$node->title;
  }

}

```

where `field_image` is the actual name of the image field you have in your node.

If you don't want your users to be see or to attempt to change this, just make sure the `alt` and `title` boxes aren't checked in the field setup, eg:

as this is just for the field add/edit widget in the form; the above code will still work even if these attributes aren't "enabled."
> 11 votes

# Answer
You can use ImageField Tokens:

> The ImageField Tokens module extends the default functionality of Image fields adding the ability to specify default values and use node tokens in the Alt and Title text.
> 8 votes

# Answer
Here's a D7 rule I created to do that very thing. Just go to **Rules \> Import and Save**. Will automatically add the `[node:title]` and `[site:name]` tokens to the alt text field when content is saved or updated:

```
{ "rules_alt_text_default" : {
    "LABEL" : "Alt Text Default",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Custom" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_image" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-image:alt" ],
          "value" : "[node:title] - Available at [site:name]"
        }
      }
    ]
  }
}

```
> 1 votes

# Answer
There are 2 easy Methods to achieve this:

**Method 1** is more straightforward; Configure your File Entity Module and in the alt and title attribute fields, replace the token with `[current-page:title]` which is also one of the available tokens

> Please note: for this method above, the title and attribute fields are replaced if the fields are empty, if any text is input in them at any time, that text will be used instead.

**Method 2** uses Rules to achieve this and this is how:

1. Create Rules with the following events:

a. after saving new content

b. after updating existing content
2. `Add condition: "content is of type: (add your content type(s) here.....)" Note: without this condition, rules does not seem to pull out the alt and title attributes from your image field.` You may also add other conditions to check if the fields are empty or not (" using data value is empty....") so that you do not alter existing text in the fields. This gives better control than Method 1 above.
3. Add 2 actions to set your data values for both alt and title fields here using the node title.

For even finer control, you may install the "Conditional Rules" module to check if both or one of alt and title attributes were filled up (example scenario is "if alt is NOT empty and title is empty, update title attribute" or "if alt is empty and title is NOT empty, update alt attribute... etc).

If you do not want to install the conditional rules module but still want better control in checking empty fields, then just create 2 different rules to independently check both fields.

4. Save Your rule. that's it.

You may also simply import this rule i created which does the simple steps above. Note that my field is named "field\_image" and my content type is "article":

```
{ "rules_update_image_alt_and_title_automatically" : {
    "LABEL" : "Update image alt and title automatically",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [], "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-image:alt" ], "value" : "[node:title]" } },
      { "data_set" : { "data" : [ "node:field-image:title" ], "value" : "[node:title]" } }
    ]
  }
}

```
> 0 votes

---
Tags: 7, media
---


title: t() function - get specific language

text:
# Question
Title: t() function - get specific language
As twig does render templates in the UI language instead of the content language, all the `t()` functions deliver the default language. In my case this is wrong as the ui language is german but the content language can vary.

Can I tell the `t()` function to deliver the translation for Spanish for example?

# Answer
You can choose the target language, see more information in the API.

In code it would look like this.

```
$variables['string_in_spanish'] = t(
  'Hello World',
  [], // (The args in the string)
  ['langcode' => 'es'] //  The options
);

```

note that when using the `t()` function, the source language has to be English.
> 2 votes

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


title: Turn off Twig cache in general

text:
# Question
Title: Turn off Twig cache in general
Drupal does cache Twig templates. Normally, it is a good thing, as long as you don't have a multilingual site.

In my case every `t()`is not working as the template is cached in the wrong in English, giving German no chance to ever be outputted.

Is this the proper way to deal with `t()` calls?

```
 $settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

It seems a bit wrong. As I understand these settings are more for the development process, not for production. Also there really should be a setting to use caching in a language specific way.

# Answer
In Drupal cache content is language specific. Default is a cache context for the language. Sometimes you need to clear the cache one more time, but then this should work.

You can check this in the database table `cache_render`. All cid's should contain `[languages:language_interface]=langcode` and if you visit the same page in different languages you should see multiple cache entries.

Disabling the cache with a null backend is only for development. For production you need to find a solution for the language specific caching issue.
> 1 votes

# Answer
You can pass options to t, specifically the langcode. I believe that would look something like this:

```
{{ 'Your text here'|t({}, {'langcode' => node.language().getId()} }}

```

Untested, so the syntax might be slightly different. Also not sure what woud happen if you pass in a node that has a language like "not specified", it would probably fail.
> 1 votes

---
Tags: theming, 8, caching
---


# Question
Title: Can an embedded video be made responsive?
I currently use the Video filter module to embed Youtube videos in my posts, but on mobile devices the videos are not responsive. They still maintain their width no matter how narrow the screen is.

I am open to another method of embedding videos even raw HTML and Javascript if the video displays will be responsive

# Answer
We use Fitvids in combo with Video filter to make youtube videos responsive. You can either add the JS yourself or use the Drupal module version, it works either way.

In the case of using the Drupal module, you'll add the video filter HTML selector to the UI for fitvids and then your video will be responsive.

For example, on my site, I have a video using video filter:

```
[VIDEO::https://www.youtube.com/watch?v=y0bA_KH-D-I]

```

... and then in the video filter UI, I have added the slector for the video here:

`/admin/config/media/fitvids`

In my case video filter is using `embedded-video` as its wrapper HTML element so I added `.embedded-video` to the fitvids UI in Drupal.

**For more info see:**
> 4 votes

# Answer
You can simply use CSS to apply responsiveness (I believe the correct term here is "fluid-width"), given that the Aspect Ratio of your videos are uniform (16:9 OR 4:3). The trick is a simple "Padding" trick using percentages. I've made a demo here with a youtube iframe embed which is made responsive: https://jsfiddle.net/scg6n55h/

Try moving the window borders to resize the preview window. The video should resize along with the window. Hopefully the fiddle is enough?

If you'd like to read more about it, here's the article where I originally got this idea from: https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php
> 4 votes

# Answer
While I haven't used the Video Filter module (I prefer to use a separate media field), by far the easiest tool that I've used for responsive videos is Bootstrap's Responsive Embed. Here are details on how it works: http://getbootstrap.com/components/#responsive-embed

If your theme is based on Bootstrap, the core of what you need is already built-in. If not, you can generate a customized Bootstrap download that includes just the Responsive Embed styles and add it to your theme. You would then add the appropriate classes to your template.

The other option is to add some CSS (and possibly a little JS) to your theme. Here's my favorite tutorial on doing that: https://css-tricks.com/rundown-of-handling-flexible-media/
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Theme video-embed-iframe.html.twig by content type
I am using Drupal 8 and trying to theme video-embed-iframe.html.twig by content type. with the current naming suggestions this is not possible.

I am using Media with video embed field containing in a field called video

This is what I did so far. in the fields template named above in the templates folder of my theme

```
{% if logged_in %}
 <iframe{{ attributes }}{% if url is not empty %} src="{{ url }}{% if
 query is not empty %}?{{ query | url_encode }}{% endif %}"{% endif
 %}></iframe>
{% else %}

 <div id="promotion">
 <div id="promotion-image">
   <div id ="promotion-bg">
 <div id ="promotion-text">
 <H1>Eine brilliante Überschrift</H1>
 </div>
 </div>
 </div>
 <span id="promotion-attribution">
 <a href="http://somesite.com">Credit author of the background image</a></span>
</div>
{% endif %}

```

I have no clue how to access the field by content type to separate the code deepening if you have a content type eg page and article Any Ideas?

Is there a way to populate a global var like logged in containing the mashine name of the content type without needing a custom module. I other words is there a way to populate a var like

contenttype=anycotenttypehere in the mytheme.theme file by writing a function? to be able to display the video depending on with contetnt type has been used and if the user is logged in or not

# Answer
> 0 votes
That's not easily possible, not directly.

By default a media entity is going to be render cached on its own, that means the same media could be used in two different nodes with a different type and as long as they use the same view mode, it is only going to be built once. While you can get the current node easily on the detail page in preprocess and you could vary the rendered media by path, that will possibly result in a lot of variations and won't really work on views and other pages that display teasers of many nodes.

The easist way to achieve something like this would be to define two different view modes, use one from one node type and the second from the other.

---
Tags: theming, 8
---


# Question
Title: How to add CSS classes to a Views-generated block? (NOT to its generated content, the block itself!)
I don't know why, but Views doesn't add "human-readable" CSS class names (like e.g. the machine name of the view) to the blocks it creates (**it only adds its classes to the *generated "content" part*** when adding classes to the "*CSS class*" part in the view editor (see the screenshots below!)).
It only adds the usual `block block-views`, and possibly `contextual-links-region` CSS classes to the block(s), and generates a unique id (not class) like this: `block-views-3d8f7966168beeec655c8ead69336789` (because its delta is this generated hash code).
It doesn't make sense to write CSS rules for these classes and ids (like `.block-views-3d8f7966168beeec655c8ead69336789 { /* ... */ }`), because these classes/ids might change when altering the Views block.

How can I add some custom CSS classes in an implementation of `hook_block_view_alter()`, if I cannot even identify these blocks because of their generated hash delta?

---

**I do not want to use Block Class**, because I feel it's like an overkill for just adding some classes to one or two Views-generated blocks (BTW I checked the module, and I feel `SELECT css_class, module, delta FROM {block_class}` query in `block_class_preprocess_block()` like an overkill, because it checks ALL the added classes, even if the block is hidden...).

So I would like to solve it from my own module.

---

EDIT

An example:

My view with the machine name and the added CSS classes:

The generated block's HTML code in the inspector:

# Answer
> 7 votes
First. You have "hash" - because you view machine name is too long.

Second - you can add your own classes to view

# Answer
> 2 votes
That's a old question, but there is no proper answer. I came across the same problem. The solutions I could think of was CSS parent selector (which doesn't exists yet) OR some Drupal manipulation.

I added a hook\_preprocess\_block to add a wrapper CSS class to all view blocks that define a CSS class. That's not trivial so I will put my code here. It may not work with all view blocks, if you have an issue with this code, feel free to update it and post your own version.

Example: View with CSS class "test" will be contained in a block with the CSS class "test-wrapper".

```
function <MY_THEME>_preprocess_block(&$variables) {
    $default_display_id = 'default';
    // Trying to access the field:
    //     $display_id =      $variables['elements']['#views_contextual_links_info']['views_ui']['view_display_id']
    //     $default_display = $variables['elements']['#views_contextual_links_info']['views_ui']['view']->display['default']->display_options['css_class']
    //     $display =         $variables['elements']['#views_contextual_links_info']['views_ui']['view']->display[$display_id]->display_options['css_class']
    if (isset($variables['elements']['#views_contextual_links_info']['views_ui'])) {
        $view_ui = $variables['elements']['#views_contextual_links_info']['views_ui'];
        if (isset($view_ui['view_display_id'])) {
            $display_id = $view_ui['view_display_id'];
            if (isset($view_ui['view']) && property_exists($view_ui['view'], 'display') && isset($view_ui['view']->display[$display_id])) {

                $default_css_class = NULL;
                if (isset($view_ui['view']->display[$default_display_id])) {
                    $default_display = $view_ui['view']->display[$default_display_id];
                    if (property_exists($default_display, 'display_options') && isset($default_display->display_options['css_class'])) {
                        $default_css_class = $default_display->display_options['css_class'];
                    }
                }

                $view_css_class = NULL;
                $display = $view_ui['view']->display[$display_id];
                if (property_exists($display, 'display_options') && isset($display->display_options['css_class'])) {
                    $view_css_class = $display->display_options['css_class'];
                }

                $css_class = $view_css_class ? $view_css_class : $default_css_class;
                if ($css_class) {
                    $variables['classes_array'][] = "$css_class-wrapper";
                }
            }
        }
    }
}

```

# Answer
> 1 votes
There is a module for this purpose.

View block top class

# Answer
> 1 votes
For me `hook_preprocess_block()` didn't work. (Maybe because I had to add the block directly from a template file via `views_embed_view()`.)

However, `hook_preprocess_views_view()` with a simple check for `$vars['view']->current_display` did work:

```
function MYMODULE_preprocess_views_view(&$vars) {
  // 'MYBLOCK' usually comes as 'block' if this view only has one
  if ($vars['view']->name == 'MYVIEW' && $vars['view']->current_display == 'MYBLOCK') {
    // here I add a class that contains the current theme's name
    global $theme;
    $theme_name = array_pop(explode('/', (drupal_get_path('theme', $theme))));
    $vars['classes_array'][] = $theme_name.'-theme';
    // but you can simply do the following as well
    $vars['classes_array'][] = 'MYSTRING';
  }
}

```

# Answer
> 0 votes
The easiest way for me was to duplicate the file block.tpl.php, rename it to `block--myregion.tpl.php` and then add my classes inside it.

See: Theming blocks page.

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


# Question
Title: Required contexts without a value: node when editing menu
I'm running into this error whenever trying to edit a menu item

> Drupal\Component\Plugin\Exception\ContextException: Required contexts without a value: node. in Drupal\Core\Plugin\Context\ContextHandler-\>applyContextMapping() (line 112 of /var/www/aaep.org/http/web/core/lib/Drupal/Core/Plugin/Context/ContextHandler.php).

When I add new menu items to replace the ones that weren't working using the same links and titles it works, but then another random menu link breaks. I'm having trouble isolating what is unique about the ones that break but I can't seem to find a pattern. The ones that break can have whitespace in their titles, be linking to nodes, external links, or custom internal links. They could be newly created or old. I can create a new menu item with the exact same link and title, all settings exactly the same, using the same parent in the same menu, and one will work and one will receive that error. I'm using panel pages and linking to some of those, and I'm using aliases instead of node ids, but I don't think that would be an issue. It hasn't been one before.

What could possibly cause 'Required contexts without a value: node' when editing a menu item? Is there something I can check to attempt to debug the issue? Does the error message point to specific problem area?

UPDATE: After turning on verbose error logging I got this error

The website encountered an unexpected error. Please try again later.

> Drupal\Component\Plugin\Exception\ContextException: Required contexts without a value: node. in Drupal\Core\Plugin\Context\ContextHandler-\>applyContextMapping() (line 112 of core/lib/Drupal/Core/Plugin/Context/ContextHandler.php). Drupal\page\_manager\Entity\PageAccess-\>checkAccess(Object, 'view', Object) (Line: 93) Drupal\Core\Entity\EntityAccessControlHandler-\>access(Object, 'view', Object, 1) (Line: 340) Drupal\Core\Entity\Entity-\>access('view', Object, 1) (Line: 61) Drupal\Core\Entity\EntityAccessCheck-\>access(Object, Object, Object) (Line: 29) Drupal\page\_manager\Entity\PageAccessCheck-\>access(Object, Object, Object) call\_user\_func\_array(Array, Array) (Line: 163) Drupal\Core\Access\AccessManager-\>performCheck('page\_manager.page\_access\_check', Object) (Line: 139) Drupal\Core\Access\AccessManager-\>check(Object, Object, NULL, 1) (Line: 92) Drupal\Core\Access\AccessManager-\>checkNamedRoute('entity.node.canonical', Array, Object, 1) (Line: 67) Drupal\menu\_link\_content\MenuLinkContentAccessControlHandler-\>checkAccess(Object, 'update', Object) (Line: 93) Drupal\Core\Entity\EntityAccessControlHandler-\>access(Object, 'update', Object, 1) (Line: 593) Drupal\Core\Entity\ContentEntityBase-\>access('update', Object, 1) (Line: 61) Drupal\Core\Entity\EntityAccessCheck-\>access(Object, Object, Object) call\_user\_func\_array(Array, Array) (Line: 163) Drupal\Core\Access\AccessManager-\>performCheck('access\_check.entity', Object) (Line: 139) Drupal\Core\Access\AccessManager-\>check(Object, Object, Object, 1) (Line: 112) Drupal\Core\Access\AccessManager-\>checkRequest(Object, Object, 1) (Line: 102) Drupal\Core\Routing\AccessAwareRouter-\>checkAccess(Object) (Line: 87) Drupal\Core\Routing\AccessAwareRouter-\>matchRequest(Object) (Line: 154) Symfony\Component\HttpKernel\EventListener\RouterListener-\>onKernelRequest(Object, 'kernel.request', Object) (Line: 111) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.request', Object) (Line: 125) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 64) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 652) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

UPDATE: I have opened up a bug report for Page Manager with the information found by Berdir here https://www.drupal.org/node/2837833

# Answer
According to that backtrace, it looks like you have a link to a page\_manager page and there you probably have access conditions to limit access to a certain node type or so.

That's a page\_manager bug that you need to report there. The exception can be fixed pretty easily, but it is also possible that you then simply don't have access to edit that menu link, as page\_manager things that access is denied as the node type isn't matching as there is no node. That might be a bit harder to fix.

Part of that might be because the core permission to see and edit all menu links (link to any page or so) isn't fully working either.
> 2 votes

---
Tags: 8, debugging, navigation
---


# Question
Title: Using a module controller to create a page that is more than just a div from the twig template?
I am using a custom module to create a new page on my Drupal 8 site.

My `routing.yml` file is configured like this:

```
mymodule.print:
  path: '/print-mymodule'
  defaults:
    _controller: \Drupal\mymodule\Controller\MymodulePrintController::content
  requirements:
    _permission: 'view mymodule entity'
  options:
    _auth: ['basic_auth']

```

`MymodulePrintController::content` is as follows:

```
public function content() {
    return array(
        '#type' => 'page',
        '#theme' => 'mytheme'
    );
}

```

`mytheme` is used everywhere else on my site.

In `mytheme.theme`, I also have a `mytheme_preprocess()` function which is adding some blocks to the page. I am guessing the theme is being detected properly because this function is executing just fine. The template I am using is named according to twig's suggestions and is loading fine.

The problem is that the `content()` function is not really outputting a "page". Using Postman, I see that the entire contents of the response is just a div, there is no `<html>` tag, no `<head>`, no `<body>`, nothing else except what is defined in the one twig file and `mytheme_preprocess`. I need this page to be using this theme's css styles like the rest of my pages are.

How can I accomplish this? Every guide/question I've seen on the topic so far either is just returning a render array in the `content()` function like I already am doing, or is suggesting to use `Response` classes without enough detail for me to really understand.

# Answer
> 0 votes
When you generate an entity with drupal console you get a twig template for the content of the entity. This is not a page and not a theme. If you want to use a page template, that is specific to the entity, then you use a template name suggestion, for exampe `page--myentity.html.twig`. The content from the entity controller will end up like any other content inside of this page in the region `content` if you use the standard block layout, where the block "Main page content" is placed in this region.

You can remove anything else from the page template what you don't need and replace this with static html.

---
Tags: theming, 8
---


# Question
Title: How change views exposed filter drop down format?
I'm working on a D7 site where I am trying to implement a simple view of a custom content type. I want to have a drop-down select list of taxonomy terms to be able to filter the content by. At the moment, I just seem to have a box with the taxonomy terms in it. They filter the content appropriately when selected, but the UI seems bad to me and I'm not sure how to change it. It has the same UI implementation whether or use Better Exposed Filters or not.

What I'd like to implement is just a scrollable drop down select list but I'm not sure how to go about this.

# Answer
It appears currently that you have the select box as multi-select. Do you want the user to choose 1+ values or only 1 value? If you want it as a dropdown in the more classic sense, then limit that to one value. BEF would allow you to modify some of the aspects of the select box, as well as allow you choose to use checkboxes instead of a dropdown.
> 0 votes

# Answer
Make set a height on your select list and set `overflow-y` to the height you want it at.

Something along these lines:

```
select.form-select {
  overflow-y: scroll;
  height: 20px;
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Create node upon form submit rendered by block plugin
I'm attempting to create a block plugin that displays a form that allows users to enter information and create a node with that information. I understand I can easily create a form plugin that accomplishes this task but I'd like this to be inside a block plugin so that I can place it on existing pages instead of it being on it's own dedicated page. I'm building the form like so

```
<?php

/**
 * @file
 * Contains \Drupal\my_plugin\Plugin\Block\EquipmentEntry.
 */

namespace Drupal\my_plugin\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @Block(
 * id = "equipmententry",
 * admin_label = @Translation("Equipment Entry"),
 *  )
 */

class EquipmentEntry extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        return $form;
    }
    public function blockSubmit($form, FormStateInterface $form_state) {

    }
    public function build(){
                $content = [
            'container'    => [
                '#type'       => 'container',
                '#attributes' => [
                    'class'      => ['equipment-entry'],
                ],
                'form'         => [
                    '#type'       => 'form',
                    '#attributes' => [
                        'name'       => 'equipment-entry',
                        'id'         => 'test',
                    ],
                    'title'   => [
                        '#type'  => 'html_tag',
                        '#tag'   => 'h1',
                        '#value' => $title,
                    ],
                    'contact'      => [
                        '#type'       => 'textfield',
                        '#title'      => t('Contact Person'),
                        '#attributes' => [
                            'name'       => 'contact',
                        ],
                    ],
                    'Telephone'    => [
                        '#type'       => 'textfield',
                        '#title'      => t('Telephone'),
                        '#attributes' => [
                            'name'       => 'phone',
                        ],
                    ],
                ],
             ];
          return $content;
    }
}

```

However I'm not sure how to perform any action upon submitting the form. I understand there's a blockSubmit() function but I believe that's only when you save a block.

I tried intercepting the form with a form\_alter hook like so

```
function my_plugin_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
        die($form_id);
}

```

but the function never fired. Is there a way to programmatically create a node when someone submits a form that was created to be displayed inside a block plugin? Or is there a way to create a form plugin and embed it inside a block?

# Answer
> 2 votes
You are right, the blockSubmit() method is used when you configure the block. The config form is in blockForm(), not in build().

If you put form elements in build() they get rendered like any other render element, but they are not part of the form api and can't be submitted.

If you want to build a form, use a form class. Then you can put the form class in build() by using the formBuilder():

```
public function build() {

  $content = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

  return $content;
}

```

**Better solution:**

Instead of building your own form use the entity form for nodes, which you can place in a block with this module: https://www.drupal.org/project/entityform\_block

# Answer
> 1 votes
That is not a form, that's just a render array that's made to look like a form. But it's just output, not actually doing any form processing.

See for \Drupal\search\Plugin\Block\SearchBlock for an example how a block that displays a form needs to look like. You need a second form class that you call from the block.

---
Tags: forms, 8, blocks
---


title: Updating author name in preprocessnode

text:
# Question
Title: Updating author name in preprocessnode
The `kpr` line in the function works – It outputs the author of the node's full name. But setting the `author_name` variable **does not**. Why isn't that replacing the `author_name` variable in my template? (It's just blank.)

If i remove this, it will display the username.

```
function theme_preprocess_node(&$variables) {
  // die(kpr($variables['node']->getOwner()->get('field_full_name')->getValue()));
  $variables['author_name'] = $variables['node']->getOwner()->get('field_full_name')->getValue();
}

```

# Answer
getValue() is probably returning an array, which cannot be interpreted by twig. try:

```
$variables['author_name'] = $variables['node']->getOwner()->get('field_full_name')->getValue()['value'];

```

Or search for the right key in there ..
> 3 votes

---
Tags: theming, nodes, 8
---


title: Check if user is logged in first time

text:
# Question
Title: Check if user is logged in first time
How can i check if user is logged in for the first time on site?

If it is, i want to show him a message...

Can someone help me?

Thank you!

# Answer
> 5 votes
In both Drupal 7 and 8, there is hook\_user\_login, where you can can check whether the current user has accessed the site before, but the parameters are slightly different.

Drupal 7 version:

```
function mymodule_user_login(&$edit, $account) {
  if ($account->access == 0) {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

```

Drupal 8 version:

```
function mymodule_user_login($account) {
  if (!$account->getLastAccessedTime()) {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

```

hook\_user\_login in Drupal 8.

# Answer
> 4 votes
\** UPDATE \**

As suggested by oknate, using hook\_user\_login:

```
function hook_user_login(&$edit, $account)
{
  if(!$account->access)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

```

\** Original less optimal method \**

You can use hook\_init() in D7, and check if they have a value for last access:

```
function hook_init()
{
  global $user;

  $first_login = db_query('SELECT 1 FROM {users} WHERE uid = :uid AND access = 0', array(':uid' => $user->uid))->fetchField();

  if($first_login)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

```

# Answer
> 1 votes
For D7 you can use rules to achieve the same,

Here is the sample rule,

```
{ "rules_first_login_test" : {
    "LABEL" : "First login test",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [ { "data_is_empty" : { "data" : [ "user:last-access" ] } } ],
    "DO" : [ { "drupal_message" : { "message" : "True" } } ]
  }
}

```

Import this rule and modify according to your need.

You can check the more information here.

---
Tags: users
---


title: Multiple Submit in a Drupal Form

text:
# Question
Title: Multiple Submit in a Drupal Form
I want a list of the input of my saved database table with buttons to delete or view the content and want to redirect it in the submit function.

With this code snipped i get only the submitted input value of the buttons, but every time is the `$form_state['values']` array filled with the 1st form values. Is that the right way or need I another solution?

```
function myform_block_view($delta = '') {
    $block = array();

    global $user;
    $uid = $user->uid;
    $utime = $user->timezone;

    $query = db_select('mytable', 'm');
    $query->condition('m.uid', $uid, '=');
    $query->fields('m', array('fid', 'uid', 'name', 'created'));
    $query->range(0, 50);

    $results = $query->execute()->fetchAll();

    if($uid) {
        switch ($delta) {
            case 'myblock':
                $block['subject'] = '<none>';
                $block['content'] = _block_content($results);
            break;
        };
    };
    return $block;
}

function _block_content($items) {
    $output = array();

    foreach($items as $item => $item_value) {
        $output[$item] = drupal_get_form('mymodule_form', $item_value);
    };
    return $output;
}

function mymodule_form($form, &$form_state, $i) {

    global $user;
    $uid = $user->uid;
    $utime = $user->timezone;

        $form['value-'.$i->fid] = array( //EDIT
            '#type' => 'value',
            '#value' => $i->fid,
        );
        $form['view-'.$i->fid] = array ( //EDIT
            '#type' => 'submit',
            '#value' => t('view'),
            '#name' => 'view-'.$i->fid,
        );
        $form['delete-'.$i->fid] = array ( //EDIT
            '#type' => 'submit',
            '#value' => t('delete'),
            '#name' => 'delete-'.$i->fid,
        );

    return $form;
}

function mymodule_form_submit($form, &$form_state) {
   dpm($form_state);
   $form_state['rebuild'] = TRUE; //EDIT
}

```

The dpm output without 'form\_build\_id' 'form\_token' 'form\_id' in both, 1st example:

```
input =>
    view-3 => view
    value3 (NULL)

values =>
    value2
    view-2 => view
    delete-2 => delete

```

2nd example:

```
input =>
    view-3 => view
    value3 (NULL)

values =>
    value3
    view-3 => view
    delete-3 => delete

```

# Answer
It should be because the way you're generating the form is wrong, form element should be as below:

```
<?php
function mymodule_form($form, &$form_state, $i) {
  $form['value_' . $i->fid] = array(
    '#type' => 'value',
    '#value' => $i->fid,
  );
  $form['view_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('view'),
    '#name' => 'view_' . $i->fid,
  );
  $form['delete_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('delete'),
    '#name' => 'delete_' . $i->fid,
  );

  return $form;
}
?>

```

Each element name in `$form` array should be unique. Check Drupal Form API reference guide for more details. The `value`, `view` and `delete` doesn't contain any form element data like `#type`, etc. Please check the value of `$form_state['values']['op']` in your form submit handler to understand which one is called.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to avoid Drush command not found after switching to aegir or other user?
I installed Drush like this:

It works fine when I am `centos` user, when I switch user to `aegir` it doesn't work.

When I do `which drush` I get:

How can allow user `aegir` to use Drush?

# Answer
Try to create a symlink to let all user access drush.

```
sudo ln -s /usr/local/bin/drush /usr/bin/

```

if not worked try

```
sudo ln -s /usr/local/bin/drush /usr/share/bin/

```
> 3 votes

---
Tags: drush, aegir
---


# Question
Title: Upload and get images in custom module with custom block form
I need some help I need create slider on the front page with custom block. I create custom module, create custom block and form. How i can get images after upload in form for use in twig-template??

For example i create some block with input\[type\]=textfield, and use this values in twig-template. How can i use images??

its my code for 'textfield'

```
<?php

namespace Drupal\dot\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'SocialLinksBlock' block.
 *
 * @Block(
 *   id = "social_links_block",
 *   admin_label = @Translation("Social Links Block"),
 * )
 */

class SocialLinksBlock extends BlockBase implements BlockPluginInterface {
    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state) {
        $form = parent::blockForm($form, $form_state);
        // Retrieve existing configuration for this block.
        $config = $this->getConfiguration();
        // Add a form field to the existing block configuration form.
        $form['youtube'] = array(
            '#type' => 'textfield',
            '#title' => t('Youtube link:'),
        );
        $form['google'] = array(
            '#type' => 'textfield',
            '#title' => t('Google link:'),
        );
        $form['twitter'] = array(
            '#type' => 'textfield',
            '#title'=> t('Twitter link:'),
        );
        $form['facebook'] = array(
            '#type' => 'textfield',
            '#title'=> t('Facebook link:'),
        );
        return $form;
    }

    public function blockSubmit($form, FormStateInterface $form_state) {
        // Save our custom settings when the form is submitted.
        $this->setConfigurationValue('youtube', $form_state->getValue('youtube'));
        $this->setConfigurationValue('google', $form_state->getValue('google'));
        $this->setConfigurationValue('twitter', $form_state->getValue('twitter'));
        $this->setConfigurationValue('facebook', $form_state->getValue('facebook'));
    }
    /**
     * {@inheritdoc}
     */
    public function build() {
        $config = $this->getConfiguration();
        $youtube = isset($config['youtube']) ? $config['youtube'] : '';
        $google = isset($config['google']) ? $config['google'] : '';
        $twitter = isset($config['twitter']) ? $config['twitter'] : '';
        $facebook = isset($config['facebook']) ? $config['facebook'] : '';

        return array(
            '#theme' => 'block--sociallinksblock',
            '#youtube' => $youtube,
            '#google' => $google,
            '#twitter' => $twitter,
            '#facebook' => $facebook,
        );
    }
}

```

# Answer
In Drupal there is not much help available to store images in configuration. You would need to do most things yourself, like build the form fields, submit and store the images and take care how they should be rendered.

But Drupal has a great infrastructure to store images in content. So the better approach is probably not to use a block plugin, but to create a custom block type, which is content like a node. Here you can add the image fields and configure how they should be rendered in ui.
> 1 votes

---
Tags: forms, 8, media
---


title: Verify source of url call

text:
# Question
Title: Verify source of url call
In hook menu, there is a url that is used to be called by some gps device to register its lcoation in the database. Let say the url is sitename.com/gps/location/123.123/456.456

But I want to make this url, so only authenticated devices/sources can call this.

How should we achieve this. May be we can use hash token, but I am not sure how to use this to verify the source which is calling the url.

Here is the code inside the hook\_menu

```
$items['gps/location/%/%'] = array(
  'title' => '',
  'page callback' => 'gps_lcoation_store',
  'page arguments' => array(2,3),
  'access arguments' => array('access content'),
);

```

Any help?

# Answer
Using the idea given by @khoomy and @Yogesh, here is what I have done.

```
$items['gps/location/%/%'] = array(
  'title' => '',
  'page callback' => 'gps_lcoation_store',
  'page arguments' => array(2,3),
  'access callback' => 'custom_is_allowed_location',
);

function custom_is_allowed_location($arg1, $arg2) {
  // Ip address of the accessing machine/device.
  $varrified_ip = '12.34.56.78';
  if (ip_address() == $varrified_ip) {
    return TRUE;
  }
  return FALSE;
}

```

Since it will be access by a specific device, having an IP address, so checking the IP address of the source.
> 1 votes

# Answer
```
$items['gps/location/%/%'] = array(
  'title' => '',
  'page callback' => 'gps_lcoation_store',
  'page arguments' => array(2,3),
  'access callback' => 'custom_is_allowed_location',
  'access arguments' => array(2, 3),
);

function custom_is_allowed_location($arg1, $arg2) {
   //IF LOCATION IS XXXXX THEN ALLOWED
   if($arg1 == xxxx && $arg2 == xxxx) {
       return TRUE;
   }
   return FALSE;
}

```
> 2 votes

# Answer
I agreed with Yogesh, use can use access callback and/or to use hook\_menu\_alter to override if it is in contributed module. So in later case you can have full control over that menu

In both cases access callback will be the good option.
> 0 votes

---
Tags: routes
---


# Question
Title: How do I get the router name from the internal path?
If I know the internal path of my page (e.g. 'node/1') how do I get the router name?

I need it it to generate an internal url:

```
$url = Url::fromRoute($router_name);

```

I found Url::getRouteName, but I'm not sure if this is what I need?

Thanks.

# Answer
Have a look at `PathValidatorInterface::getUrlIfValid()` or the version that does not check access. That is provided by the path.validator service:

```
\Drupal::service('path.validator')->getUrlIfValid('node/1')

```
> 7 votes

# Answer
You can also do like this

```
$route_name = Url::fromUserInput($internal_path)->getRouteName();

```

More details : http://www.drupal8.ovh/en/tutoriels/275/drupal-8-url-tips-get-name-path-args
> 4 votes

---
Tags: 8, routes
---


# Question
Title: How to set 'INSERT IGNORE' in db_insert without db_merge
Is anyone know how to set 'INSERT IGNORE' in db\_insert?

I cannot use db\_merge because I'm going to insert many rows.

```
$query = db_insert('table')->fields(array('foo', 'bar'));
foreach ($rows as $row) {
  $query->values(array(
    'foo' => $row->foo,
    'bar' => $row->bar,
  ));
}
$query->execute();

```

# Answer
You've got two options:

1. Subclass `InsertQuery` and add that functionality in yourself (it's currently not implemented)
2. Use `db_query()` to run a raw SQL string instead.

The only mention of `INSERT IGNORE` in the Drupal 7 codebase is in `DatabaseConnection_mysql:nextId`; it's not actually used, but in its place is a raw query string containing `ON DUPLICATE KEY UPDATE`, that gets passed directly to `db_query()`.

I may be wrong, but I'd assume that's as good an indication as any that a raw SQL string along with `db_query()` is the way to go.
> 5 votes

# Answer
Although it's not possible to use "INSERT IGNORE", there is a way you can get around this in PHP. Something like this:

```
try {
    $insertID = db_insert('crawl_data')->fields(array(
        'url' => $url,
    ))->execute();
} catch (Exception $ex) {

}

```

In this example I have a database of "urls". But i dont want to first do a check if the item is in the database. I want it to happen in one go. So this is sort of the same behaviour as "insert ignore".

However, it's generally bad to have this:

```
catch (Exception $ex) {
    // open space
}

```

So it might be better to do this:

```
catch (Exception $ex) {
    $error = $ex->getMessage();
    if (strpos($error, 'SQLSTATE[23000]: Integrity constraint violation') !== false) {
        // then we know it's an error we can ignore
    }
    else {
        // just throw the error again
        throw $e;
    }
}

```

It's either this or doing two database queries.
> 4 votes

---
Tags: database
---


# Question
Title: How to Uninstall/Reinstall a custom module whithout losing the content?
As we know : it's impossible to unsintall a module whithout being forced to remove all the data that's belongs to it. The problem is, if we want to update a module we are obliged to uninstall it and then reinstall to get the changes work.

At developpement phase, it's ok , but what about being in a production site and having a big amount of data we don't want to loose, by just adding a field , or changing a type ....

Is there any best practises? Is there a process that could be advised? Is there any feedbacks of your own experience?

For example, I would guess : export data and then import data after the reinstall?

Thank you so much!

# Answer
In order to make my changes take effect without removing all data -\> uninstall -\> reinstall the module .

Here the steps :

1. Make the changes (in my code , for exemple add a field in my entity class)
2. Add a hook\_update\_N() in yourmodule.install (yourmodule is your module name) yourmodule.install is in the root od your module, if not exist create it
3. Here the content of yourmodule.install

`<?php
 /**
 * Document your changes
 */
 function yourmodule_update_8001() {
 \Drupal::entityDefinitionUpdateManager()->applyUpdates();
 }`
4. Execute update.php et the change take effect in the database !

NB: I made my changes in my custom module code using BaseFieldDefinition, ...
> 0 votes

# Answer
You can update your database with

> hook\_update\_xx

if your module define hook\_shema

https://www.drupal.org/docs/8/api/update-api/updating-database-schema-andor-data-in-drupal-8
> 1 votes

---
Tags: 8
---


# Question
Title: Remove the URL aliases that don't have a node
I have been importing a lot of data using feeds, then deleting all imported items again when there were problems with the import. Unfortunately, the URL aliases for the pages do not seem to be deleted, so they are related to nodes that no longer exist. Is there any way to remove them, other than going through by hand?

# Answer
> 2 votes
A core bug causing this error was fixed for Drupal 8.2 and 8.3:

PathItem::delete() never runs because the path field type is a computed field in disguise

The fix for this problem, then, should simply be updating Drupal (...after having waited several months for this fix to be made and 8.2 released— but a satisfying answer now, i hope!)

---
Tags: 8, feeds, path-aliases
---


# Question
Title: Cron job to transfer files to remote server
How would I go about scheduling a monthly file transfer (via FTP) to send files in a specific directory on my remote VPS to a server on my internal Corporate network? Once files are transferred, I'd also like to job to delete the files on the VPS?

# Answer
If you absolutely need it, Drupal has `hook_cron()` for regular task running:

```
function MYMODULE_cron() {
  // Copy your files here using standard php FTP functions
}

```

But it would be considerably more efficient to leave Drupal out of this altogether, and set it up with a basic rsync/FTP cron job executed on the server.

Alternatively, Backup and Migrate can both take a dump of the public/private file system and transfer it to an FTP target. Again, a solution outside Drupal will always be more efficient as it won't bootstrap the application.
> 2 votes

---
Tags: 7, files
---


# Question
Title: How to render HTML into a variable programmatically
Let's assume you have a "product" node `$node`, and for some reason you want to render HTML from $node into a variable $html using a Twig template. I'm a bit desperate yet, what would you do?

Additional info 1: We are not in a controller, but in a simple class that is registered as a service.

Additional info 2: 4k4 's answer does work if I call my class from a controller. But as soon I call it from a Drupal Console command I get an Exception "The theme implementations may not be rendered until all modules are loaded."

**Edit: The complete solution**

Obviously not all modules are loaded if we call the service inside a Drupal Console command. The Theme Manager will honor this with the aforementioned exception, so we have to force load the modules:

```
\Drupal::moduleHandler()->loadAll(); // Load all modules if not loaded already

```

Now it's safe to call the renderPlain() method as suggested below:

```
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build = $view_builder->view($node, $view_mode, $langcode);
$html = \Drupal::service('renderer')->renderPlain($build);

```

**Edit: But what about a full page?**

If you intend to render not only the node content but a full page (from `<html>` to `</html>`) you have to have the kernel handle an appropriate sub-request .

# Answer
To render a plain node view, for example for emails, use this code:

```
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build = $view_builder->view($node, $view_mode, $langcode);
$html = \Drupal::service('renderer')->renderPlain($build);

```

If you want to customize the output, use a special view mode and a template `node--[view-mode].html.twig`.

**Edit: Full page**

You can build more complex render arrays:

```
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $content = $view_builder->view($node, $view_mode, $langcode);
  $build = [
    '#type' => 'html',
    'page' => [
      '#type' => 'page',
      '#theme' => 'page',
      '#title' => 'Title',
      'content' => $content,
    ],
  ];

  $html = \Drupal::service('renderer')->renderPlain($build);

```

This is only a basic version of a page, if you want the full version with all features like attachments and libraries you need a request on Drupal.
> 6 votes

---
Tags: theming, 8
---


# Question
Title: How to resolve conflict between zen theme breadcrumb function and Path Breadcrumbs?
Apparently there Path Breadcrumbs module and the Zen theme's breadcrumb append title option have a conflict where the Path Breadcrumbs module overrides the theme's implementation of the breadcrumbs. Such that when the PB module is enabled, the theme's breadcrumb trail doesn't append the title to the breadcrumb trail. This leaves me with three options: 1) hack the theme breadcrumb implementation to re-add the titles, 2) implement views page breadcrumbs in code; 3) implement path bread crumbs for all of my pages. None of these options seems particularly pleasant, but I think approaching the theme breadcrumbs will be the least work. Any ideas? or simple workarounds?

# Answer
So, more obvious than I'd like to admit: there is a Path Breadcrumbs settings tab where you can configure the theme settings as well as per theme breadcrumb settings. Enabling the theme breadcrumbs for my custom theme solved the problem!.
> 0 votes

---
Tags: 7, breadcrumbs, theming
---


# Question
Title: How to set a Rules Condition "Does this node with date field use repeating functionality"?
I want to set a condition based on whether a calendar item (node that uses a date field) has *repeating* values set.

I can't find anything relevant in the data selector. The rule event includes "content of type" so it's not an issue related to "entity has field." The relevant field is showing up in the data selector.

Also, in addition to wanting to determine "is this a repeating date", I'd want to get access to the repeat rule (by this "rule" I mean the rule created by the date module, not the Rules module). I see no data selector for that either.

# Answer
> 2 votes
I'm not aware of any Rules Condition to check for repeating attributes. However you may possibly get it to work by using a ***loop*** within your Rules Actions, to actually check how many repeating values you actually have.

To do so, have a look at the rule included in the answer to "How to add up all items of a field collection field using Rules?". You could use a similar set of Rules Actions (combined with whatever Rules Events/Conditions you want) to simply calculate how many values you have.

For that, all you need to do is to initialize some counter to zero (before the loop starts), and then add "`1`" to that counter for each list item. And after the Rules Loop is finished, you invoke a separate Rules Component to which you pass the counter (= result of your calculation) as a parameter. Within that Rules Component, you can add any Rules Conditions you'd want. And in its Rules Actions you perform the actual Rules Actions you want.

It might be worth to pass your date field also as an extra parameter to the Rules Component, so that possibly you can get access (whatever you mean by that) to that "repeat rule" also.

Note (about your comment): Using `node:field-time:1:value` might also work, but you'd first have to do some testing with that "data field is empty". I doubt a bit what happens in the case where you only have 1 value (= `node:field-time:0:value`), while you would be referring to `node:field-time:1:value` ... In that case it might cause some type of data exception or so (not sure though, to be verified). How about some data comparison related to `node:field-time:1:value`, or (more "safe") using a text comparison with an appropriate RegEx?

---
Tags: rules
---


# Question
Title: Should one avoid lots of use statements in a custom modules .module file?
Should one avoid lots of use statements in a custom modules .module file? Or does it not matter? To quanity "lots", let's say, using 7 to 10 "use" statements.

```
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\views\Views;
use Drupal\views\ViewExecutable;
use Drupal\Component\Utility\Html;
use Drupal\node\NodeInterface;
use Drupal\Core\Cache\Cache;

```

I suppose for organizing code, it may be more elegant to create a service to hold custom functionality, rather than to put it directly in a custom module's .module file, but are there any performance implications for many use statements in a .module file?

# Answer
> 4 votes
The use statements alone are definitely not going to be a performance concern. I doubt that we're even talking about nanoseconds here. So that really doesn't matter. I'm guessing that this is resolved at compile time anyway.

Especially in a .module file, use statements usually grow, the more code you have, the more use statements, as a .module file is often doing many different things, implementing various hooks and so on.

If you want to optimize something, look at your actual code, forget about the use statements. Some hooks can be moved into include files, especially those that are only needed when rebuilding caches, like hook\_views\_data(). Other things can be done in services. But also here, the argument is most likely not going to be runtime performance, parsing code is really, really fast. It's your performance in understand the code, finding bugs, writing test and so on. Optimize for that.

---
Tags: 8, performance
---


title: setup multisite into multi server

text:
# Question
Title: setup multisite into multi server
I developed multi site using Drupal 7.

1. example.com
2. site1.example.com
3. site2.example.com

All subdomains are using the same codebase in /sites/site1 and /sites/site2.

Is it possible to host SITE1 in a different hosting server with the same codebase?

# Answer
> 0 votes
You need to read this article: **Multi-site - Sharing the same code base** https://www.drupal.org/docs/7/multisite-drupal/multi-site-sharing-the-same-code-base

1. Create directories for your each site
2. Copy config files to each directory
3. Create a database for each site
4. Make a symbolic link for each site:

$ ln -s . site1 $ ln -s . site2

---
Tags: multi-sites
---


# Question
Title: Site not responding while flushing cache
I have a Drupal 7 site which requires flushing the cache from time to time. The problem is that whenever I flush the cache (~30 seconds) the site is non-responsive until the flush is over.

What could be the cause and how do I debug this? Thanks

# Answer
> 0 votes
Using a MySQL frontend like phpMyAdmin run `SHOW PROCESSLIST` while your site is locked from the cache clear. That should show what is causing the issues for you. My guess is it will be a metadata lock. https://www.drupal.org/project/apdqc was built to prevent db locks in database caused by the cache.

---
Tags: 7, caching
---


# Question
Title: Unable to add list items in item-list.html.twig
I need to display some links in a list and I'm using **item\_list** theme for this:

```
$ii = array(
  'id-1' => array('name' => 'name1', 'class' => 'class-1'),
  'id-2' => array('name' => 'name2', 'class' => 'class-2'),
);
$iii = array();
foreach ($ii as $key => $value) {
  $iii[] = array('#value' => '<a class="'.$key.'" href="http://test.com">'.$value['name'].'</a>', '#wrapper_attributes' => array('class' => 'class-id'));
}

$aa = array(
  '#theme' => 'item_list',
  '#items' => $iii, //list of items to be displayed
  '#list_type' => 'ul',
);
print_r(drupal_render($aa)->__toString());

```

But on running this, I got an output of:

```
<div class="item-list"><ul><li class="class-id"></li><li class="class-id"></li></ul></div>

```

where `<li>` tags are empty and 2 empty bullets are displayed on the front-end.

What I'm doing wrong?

# Answer
There is no such thing as #value, you want #markup instead, There are also better ways to create links, although I'm not 100% sure right now if you can provide #wrapper\_attributes then, but you can call getRenderable() on the link, then you get a render array and should be able to it on that.:

```
\Drupal\Core\Link::fromTextAndUrl($value['name'], \Drupal\Core\Url::fromUri('http://test.com'))

```
> 1 votes

---
Tags: 8
---


# Question
Title: Force redirect in submit handler even though destination parameter set
I add a custom submit handler and now I want Redirect to custom route after form submitted.

This is what I used

```
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;
use \Drupal\Core\Url;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {

        foreach (array_keys($form['actions']) as $action) {
            if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
                $form['actions'][$action]['#submit'][] = 'zyetondev_sync_trends_submit';
            }
        }
    }
}

function zyetondev_sync_trends_submit(array $form, FormStateInterface $form_state) {
    $url = Url::fromRoute('view.trends.page_1');
//    die(Url::fromRoute('view.trends.page_1')->toString());
    drupal_set_message("Done");
    $form_state->setRedirect($url);
}

```

Submit Handler getting run and redirect redirection work correctly, **Problem is when** we have `?destination=` on Url, **How can I force redirect even though `?destination=` is on Url?**

# Answer
The only correct way to do this is to alter the Request object and drop the destination.

In your submit callback:

```
\Drupal::request()->query->remove('destination');

```

Depending on the context, you might want to store it somewhere, for example pass it along to the URL you are redirecting to, so that it is respected again later.

See https://www.drupal.org/node/2325463 for a core issue that is doing exactly this to fix the preview button if a destination is given.
> 18 votes

# Answer
This code will help you.

```
 $url = \Drupal\Core\Url::fromRoute(
        'node.add',
         array('node_type' => $type->id()),
         array(
           'query' => array('destination' => $destination),
           'absolute' => TRUE,
         )
    );
   $form_state->setRedirect($url);

```
> 1 votes

---
Tags: 8, redirection
---


title: How to set cache settings for Block

text:
# Question
Title: How to set cache settings for Block
I want to set the cache settings for a block that I build by module. I know how to set the cache settings for the build array, but I am not able to find a possibility to modify the cache of the block itself. (label / twig)

The theme of the block does output a form by receiving an array. This array is language specific. I need to set the cache to "language specific" or turn if off completely. But how?

Thanks.

# Answer
Everything that is render cached in Drupal is by default varied by interface language specific.

If that's not enough and you have different interface and content language for example, you need to use cache contexts. Which works exactly like anywhere else, with $form\['#cache'\]\['contexts'\], see https://www.drupal.org/docs/8/api/cache-api/cache-contexts for more information.
> 1 votes

---
Tags: 8, blocks, caching
---


# Question
Title: What causes my error "Illegal choice in Sorted by element"?
Drupal 7.50 commons

The following error shows dozens per minute when I run `drush ws --tail`, but there are no reports of users encountering errors or features that are non-operational. Does anyone know what could be causing this? Reporting for anonymous user.

```
error     form  Illegal choice  in Sorted by element.

```

Below is a screenshot of one of the errors, for detail.

Below is a screenshot of part of the page content that might be generating the problem, from admin/reports/dblog.

The error seems to be affecting more than one group or all of our groups. Here is an example URL from another entry: http://example.com/groups/oregon?sort\_by=&sort\_order=DESC&page=0,0,1

Here is the Commons Browsing Widget View Sorting Criteria:

# Answer
> 1 votes
I was able to figure out what view was being used on group pages (The Commons Browsing Widget) and see that there were three sorting criteria. One of them is the Radioactivity module.

I checked the general status report (admin/reports/status) to see that there was an issue with RadioActivity module.

I removed this sorting feature for now, but it should work now that I cleared up the issues with the module. I guess no one could have known that this was the cause. I'm keeping this up in case anyone else finds it helpful.

---
Tags: 7, forms, debugging
---


# Question
Title: How do you edit content of a Drupal\Core\Render\Markup instance via a preprocess function in Drupal 8?
From doing some experimentation, the only way I've been able to find to get the `string` property out of an instance of `Drupal\Core\Render\Markup` is to use the `__toString()` method:

```
$variables['fields']['title']->content->__toString();

```

But I'm guessing those initial underscores indicate that this is a private function, not to be used on the outside. Is there some better method to get at the content? My ultimate goal is modifying that content in some way.

# Answer
You can't edit the content. There is no public method to change it.

Usually you simply override it with a new instance:

```
$variables['fields']['title'] = Drupal\Core\Render\Markup::create('New content');

```

The double underscore indicates a magic function, which would be called automatically if you use the object in a string context. This is readonly.

If you want to add a string to the old markup, that would be an example how the magic function `__toString()` works:

```
$variables['fields']['title'] = Drupal\Core\Render\Markup::create($variables['fields']['title'] . '!!!');

```
> 11 votes

# Answer
You can invoke the magic function `__toString()` by casting to a string: `$markup = $variables['fields']['title']->content;
(string) $markup === $markup->__toString();`
> 3 votes

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


title: Generically get path to any entity

text:
# Question
Title: Generically get path to any entity
How can I get the path to an entity whether it's a user, term, node, etc? Of course, I can just figure out the type of the entity and then go through a switch for the proper URL, but that doesn't seem to be the best solution.

# Answer
> 3 votes
`entity_uri()` is an option, e.g.

```
$uri = entity_uri('node', $node);
$path = $uri['path']; // $path is e.g. node/1

$uri = entity_uri('taxonomy_term', $term);
$path = $uri['path']; // $path is e.g. taxonomy/term/1

```

It's best to use the API for this, even if hardcoding is an option. It's possible for the URI template for any entity type to be changed using `hook_entity_info_alter`, so you can't always guarantee it's going to be what came out of the box.

---
Tags: 7, entities
---


# Question
Title: Should a form only be users to collect input and not display it?
I'm using the Form API in a custom module to collect a large amount of user data, which is then collated and assessed to provide an output.

Currently I'm using ajax to refresh the form and display the output when the user submits the form. Should I be displaying the results in a different manner, or is it perfectly reasonable to do it in this manner?

Say for example I have a Myers-Briggs type survey. The user would answer a long string of questions, which on submission, I then collate and redisplay the form with results, links to other content, relevant articles etc (not just a simple result).

Is this too heavy use of the Form API to provide content, or is it reasonable for a performance and development standpoint to do it this way?

i.e.

```
$form['results']['#markup] = '<my markup>'

```

# Answer
> 0 votes
I think its totally fine to do what you want with Form API. I once did something similar for a personality test module. On the final submit the node gets reloaded but this time in a different view mode to provide the results. If I remember it right I got inspired by Drupal's poll module which uses/used this view mode approach. By that you have both parts divided a little bit better - logically and performance related. Could that work for you?

---
Tags: forms, performance
---


# Question
Title: How to add prefix (label) and postfix to commerce price field
I am trying to implement Drupal Commerce in an existing site with existing nodes. In this process I need to replace the existing price field with the commerce price field. Since this field is locked, I cannot change the label.

So I thought I could use the raw price format and just add a prefix as a label in template.php or possibly in a hook in \*.tpl.php file. But after spending hours googling without finding how to do this, I give up and post this question here. Anybody got an idea?

# Answer
> 1 votes
I'm not 100% that I understand your question correctly but I assume you need to add prefix & suffix to your commerce product prices. In that case, Drupal Commerce Extra Price Formatters does exactly that, have you tried using this module?

# Answer
> 0 votes
In case you are using Display suite, you always can use a prefix/suffix using the expert options available in Display.

---
Tags: 7, theming, commerce
---