# Question
Title: Where and why are style tags removed in the render process?
I have a block (in Drupal 8) that renders a field of a node. This is my build function:

```
public function build() {
  $node = $this->getNode();
  $build = array();
  $markup = array();
  $current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

  if ($node && $node->hasTranslation($current_lang)) {
    $node = $node->getTranslation($current_lang);
  }
  else {
    $node = false;
  }

  if ($node) {
    $fieldsToRender = array(
      'field_slider',
    );

    $viewmode = 'default';
    $entityType = 'node';
    $display = $this->getEntityViewDisplay();
    $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder($entityType);

    foreach ($fieldsToRender as $field_name) {
      if (isset($node->{$field_name}) && $field = $node->{$field_name}) {

        $displayComponentSettings = $display->getComponent($field_name);

        if (!is_array($displayComponentSettings)) {
          $displayComponentSettings = array();
        }

        $fieldRenderable = $viewBuilder->viewField($field, $displayComponentSettings);
        if (count($fieldRenderable) &&! empty($fieldRenderable)) {
          $rendered = render($fieldRenderable);

          if ('' !== $rendered) {
            $markup[] = $rendered;
          }
        }
      }
    }

    if (count($markup)) {
      $build = array(
        '#type' => 'markup',
        '#markup' => implode("", $markup),
      );
    }
  }

  return $build;
}

```

When I `dpm($rendered)` after `$rendered = render($fieldRenderable);` it gives me the wanted markup, in which at some point **is an inline style tag** that comes from inside a paragraph's template.

For some reason though, the inline style tag is removed in the final block output. I thought it was maybe due to the filters in the `page.html.twig` but just rendering the region using `{{ page.regionname }}` makes no difference.

So, where (and why) does Drupal strip that style tag?

PS: I also noticed in the block version of the field strips the twig debug comments, while the above mentioned dpm output still contains them. So I guess it has something to do with how the block handles the build function's returned markup...

# Answer
To complete Clive answer, you could directly use your `$fieldRenderable` variable into a new renderable array that you will return from your `build()` function.

Example (not tested) :

```
$build = [];
foreach ($fieldsToRender as $field_name) {
  // Do your stuff
  $build[] = $fieldRenderable; // you can put whatever you want for the key
}
return $build;

```

The render process is done when you return the `$build` variable.
> 3 votes

---
Tags: theming, blocks
---


title: Advanced menu theming in Drupal 7

text:
# Question
Title: Advanced menu theming in Drupal 7
I've cruised around the web and it is not at all obvious how to theme custom menus. I've looked for hours and have not found one single post that illustrates the process, from start to finish, of creating a menu and customizing its output. It seems like this is a multi-stage process:

1. Create the menu through the Drupal interface.
2. Create a theme function in your `template.php` file to theme the output.
3. Expose this menu to a template file (somehow) by adding it as a variable.
4. Call the `theme` function on the menu in the template file.

1 is easy enough to do, the problems I run into are with 2, 3, and 4. Looking at the default page template, I see that it exposes the main menu in the variable `$main_menu`. Later down the page you can see the function `theme('links__system_main_menu', array('links' => $main_menu...`, which means it's looking for an appropriately named theme function somewhere and using it to generate the output.

I know if I place `function theme_links__system_main_menu(&$variables) {...}` in my template.php file Drupal will use that function as opposed to `function theme_menu_links(&$variables) {...}`.

What I don't know is how Drupal links the custom menu I created with that function. Let's say for example that I created a menu called `My Menu`. Could I create the following function in my `template.php` file and theme the output for that menu? `function theme_links__system_my_menu(&$variables) {...}`

Also, how does one make that custom menu available to a template file? How does Drupal expose the `$main_menu` variable to page.tpl.php?

I *think* the key I'm missing here is how to embed the variable that represents my custom menu into a template page. For the most part though I'm completely lost with what to do after having created the menu.

Thanks for the help.

**EDIT:** Probably should post what I'm doing. Per my comment to BetaRide below, I need to inject customized HTML into the `<li>` elements of the menu items. Specifically, I'm adding Twitter Bootstrap icons.

# Answer
> 13 votes
Drupal's implementation of menus is a bit special, It doesn't always work the way it seems it should.

You can take a look at the core implementation of template\_preprocess\_page() to how the Main Menu links are added as a variable to the page template. You have to drill down a bit in the API docs, but the function you want to call in your implementation of theme\_preprocess\_page() is menu\_navigation\_links(), which will return an array of links in the menu.

Looking at line 106 of Drupal core's page.tpl.php file, you can see how the main menu links are themed in the template by calling the theme() function with a hook of 'links\__system\_main\_menu'.

Theoretically, this implementation should be able to be duplicated with a custom menu by following the standard naming conventions. So, in template.php, you could have:

```
function THEMENAME_preprocess_page(&$variables){
  $variables['custom_menu'] = menu_navigation_links('menu-custom-menu');
}

function THEMENAME_links__menu_custom_menu(&$variables){
 //custom theme function here
}

```

and in page.tpl.php, you would add something like this:

```
<?php print theme('links__menu_custom_menu', array('links' => $custom_menu, 'attributes' => array('id' => 'custom-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Custom menu'))); ?>

```

However, adding the custom menu as a variable on your page template is not necessary. You could easily place the custom menu's block into a desired region via the Drupal admin interface. Also, you could change the site's settings for the Main Menu source, effectively replacing the default $main\_menu variable in page.tpl.php with your custom menu.

**EDIT:** I am just seeing your addition about your end goal being to just add some custom html to the menu items for icons. Depending on how you are adding these icons, there are a couple different Drupal module options.

Menu Icons \- allows you to upload an image via the Menu item's settings and automatically generates CSS (customizable via a template) that adds the image as a background on the menu item.

Menu Attributes \- allows you to add a custom class to each menu item via its settings in the admin. Once a unique class is added to each menu item, you could use CSS to add an icon to the menu item or use javascript to inject the additional HTML into the menu item.

# Answer
> 1 votes
You may want to look into the Nice Menus module. Here is a quote about it (from the module's project page):

> ... enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)
>
> Three styles/types of menus are currently possible: horizontal, menus drop down; vertical, menus fly to the left; vertical, menus fly to the right. There is a handbook page that provides a list of sites that use Nice menus.
>
> Nice Menus creates blocks that may be associated with any existing site menu which can be placed wherever normal blocks can be placed in a theme. For themers, it is also possible to theme a menu as a Nice Menu directly by using the provided theme functions so a block is not necessary. A specific theme function for the Primary Links menu is available. The theme functions also allow a developer to pass in a custom menu tree of their making (i.e. not using a Drupal menu.) There is more information on how to use theme functions in the documentation.
>
> The module comes with a simple, generic color scheme which can be fully overridden either by adding the override CSS to the theme's normal stylesheet or by creating a Nice Menus CSS file and telling Nice Menus to use that rather than its own default one through the global theme configuration. Several CSS override examples are provided in the included README.txt file and in the handbook.

# Answer
> 0 votes
Depending on what you want to customize, your approach is much to havy. Usually I create the menu through the Drupal interface as you sugested. The I take the theme developer module and Firebug to find out whicht templates, hooks and CSS directives I have to overwrite to tweak it to my needs.

It's worth considering creating a sub theme of the base theme you are using befor you start tweaking. This makes it much easier to update your base theme.

# Answer
> 0 votes
**here is a smart code that can access to all menu items for any level 2 or 3 or more**

**place this code inside your tpl file don't forget to call boostrap js and css last versions :**

```
<!-- menu -->

        <?php

          # get menu with all levels
          menu_tree_all_data('main-menu');
          $menu = menu_build_tree('main-menu');

          # help function for listing submenus for each link
          function sub_menu_links($var){
           $submenu ='<ul class="dropdown-menu">';

              foreach ($var as $sub) {

                $path = str_replace("<front>",'' ,$sub["link"]["link_path"]);

                 if(count($sub["below"]) > 0 ){
                      $submenu .= '<li class="dropdown-submenu" ><a href="javascript:void(0);" >'.$sub["link"]["link_title"].'</a>';
                      $submenu .=  sub_menu_links($sub["below"]);
                      $submenu .= '</li>';
                  }else{
                      $submenu .= '<li><a href="'.$path.'">'.$sub["link"]["link_title"].'</a>';
                      $submenu .= '</li>';
                   }

              }
            $submenu .= ' </ul>';

            return $submenu;

          }

          # help function for more than 2 levels
          function menu_links($menu){

             $links = '<ul class="nav navbar-nav">';
             foreach ($menu as $link) {

              if(count($link["below"]) > 0 ){

                $path = str_replace("<front>",'' ,$link["link"]["link_path"]);

                $links .=  '<li class="dropdown ">';
                $links .= '<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">'.$link["link"]["link_title"].'</a>';
                      /* print "<pre>";
                      var_dump( $link["below"]);
                       print "</pre>";*/
                $links .= sub_menu_links($link["below"]);

                $links .= '</li>' ;

              }else{
                  $links .= '<li>';
                  $links .= '<a href="'.$path.'">'.$link["link"]["link_title"].'</a>';
                  $links .= '</li>' ;
              }

              }
              $links .= '</ul>';
              return  $links ;
          }

          print menu_links($menu);

           ?>

```

*this code will return the menu for css classes you can use your own i'm using bootstrap with some custom css*

> this code is after a hard work it can save your time and it's tested on drupal 7.x and works fine for main-menu you can change the menu as you like

---
Tags: 7, routes, theming
---


# Question
Title: How to get all nodes referencing a particular node?
I have two node types, which I'll call *A* and *B*. Type A is a fairly straightforward content type, the only thing special is that it has a field (field\_appearances) that references B nodes (tag-style, so each A may have one or more B tagged).

I am using Views to create a nice listing of all my B nodes, and I would like to have each B in this view list the A nodes that are referencing it (basically, so that users can easily see a list of A's that reference that particular B).

Effectively, this should look something like this:

> **B.1**
>
> * Used in: A.1, A.2, A.3
>
> **B.2**
>
> * Used in: A.2, A.4

## What I've tried

First, I tried setting a relationship *Content using field\_appearances*, then added a Title field to the view that used that relationship. This created a row for each B+A like so:

> **B.1**
>
> * Used in: A.1
>
> **B.1**
>
> * Used in: A.2
>
> **B.1**
>
> * Used in: A.3
>
> *(...and so on for each B)*

Next, I enabled aggregation and tried using various setups to get this right. The closest I got was setting the (referenced) Title field to aggregate on COUNT, which got me the following:

> **B.1**
>
> * Used in: 3
>
> **B.2**
>
> * Used in: 2

Any suggestions? I tried dinking around with Contextual filters but didn't get anything close to being right.

# Answer
> 0 votes
The Relationships and Aggregation features are fairly limited as they directly work on the database query, so you can only aggregate using very simple functions like COUNT, AVG, MAX etc.

What you are trying to do (load multiple related values for each row, and render them together) can be done with a sub-view, for example with this module: https://www.drupal.org/project/views\_field\_view

That would allow you to create a separate view ("Nodes referencing a particular node") with a contextual filter, then add this view as a field to the main view. It slightly impacts performance, as each row in the parent view executes a new sub-view, but should be okay with caching.

---
Tags: views, 8
---


# Question
Title: How to programmatically change a Views page's html <title> separately to its on-page
title
?
Similar to Views: how to programmatically change Views title?, I want to update the title of a Views page using logic/data only possible in PHP.

However, I want this to update **only the appropriate part of the `<title>` of the HTML `<head>`** without mirroring the change in the displayed title in the `<body>`'s `<h1 class="page-header">`.

To illustrate, imagine a view with some exposed filters that are used for navigating a product catalogue. Currently, every filtering of this page has the same titles:

```
<title>Products | My site name</title>
...
<h1 class="page-header">Products</h1>

```

I've written some code requiring access to `$view->exposed_input` that generates an appropriate string based on exposed filter choices (for example, "red, low cost, good condition"), similar to Using exposed filters as part of the rendered page's title. I want these in the html head title, so each navigable URL has a unique title with appropriate keywords for the content. I don't want them in the `<h1>`, however, because they're already clearly visible in the exposed filter page UI and I don't want to duplicate the information. I want it to look like this:

```
<title>Products: red, low cost, good condition | My site name</title>
...
<h1 class="page-header">Products</h1>

```

Things I've tried:

* Everything on that linked question applies to both the `head` and `body` titles

> ```
> <title>Products: red, low cost, good condition | My site name</title>
> ...
> <h1 class="page-header">Products: red, low cost, good condition</h1>
>
> ```
* `drupal_set_title()` doesn't work at all from any of the Views hooks I've tried, presumably because the view overrides this further down the line. I've tried:

+ `hook_preprocess_views_view`
    + `hook_views_pre_render`
    + `hook_views_post_render`
* Setting `$vars['head_title']` in `hook_preprocess_views_view` also doesn't work, presumably for the same reason: Views overrides this.

+ Someone commenting on the hook\_views\_post\_render API page with the exact same problem as me 3 years ago reports that it still doesn't work if you pass the variable to through to `hook_preprocess_html` and apply it to `$vars['head_title']` from there

# Answer
I think what you're looking for is `hook_preprocess_HOOK` where `HOOK` is either `html`, `page` or both.
> 1 votes

# Answer
It *might* be possible to do this through tokens and the Views UI if you have the Metatag module and its Metatag Views sub-module installed; one of the options in the Metatag box it adds to the Views interface is a title builder that applies only to the `<head>` `<title>`.

Unfortunately this isn't an option in this example because exposed filter selections aren't currently available as tokens. There is one module to allow this, but it's an unsupported experimental sandbox.

---

If it's *not* possible or practical to use tokens, after a lot of experimenting I found something that works on the PHP side:

Example code which can all go in the theme's `template.php`:

```
// variable getter and setter function, modified slightly from Clive's
function _something_var($var_name, $new_val = NULL) {
  $vars = &drupal_static(__FUNCTION__, array());

  if ($new_val != NULL) {
    $vars[$var_name] = $new_val;
  }
  return isset($vars[$var_name]) ? $vars[$var_name] : NULL;
}

// set the variable using data from the view object
function something_preprocess_views_view(&$vars) {
  $view = $vars['view'];

  if ( $view->name == 'something' ){
    $title_override = '...'; // do stuff with $view to generate title
    _something_var( 'title_override', $title_override );
  }
}

// get the variable after Views has finished setting its title
function something_preprocess_html(&$variables) {
  $title_override = _something_var( 'title_override' );

  if( $title_override ){
    $variables['head_title'] = $title_override . ' | ' . variable_get('site_name');
  }
}

```
> 0 votes

---
Tags: 7, views
---


title: Spambot creates 4000 orders a day

text:
# Question
Title: Spambot creates 4000 orders a day
Our webshop (built in Drupal 7 and Drupal Commerce) gets bullied by a SPAMBOT which creates about 4000 orders a day. These orders are getting registered as created by 'Anonymous' (unchecked) and stay stuck in the 'Shopping Cart' Apparently, the Spambot creates these orders by adding a product to the shopping cart on the product overview page (a custom built view with all products and for every product item an Add to cart button). Under each 'Add to cart' button, there's a hyperlink. We've already attributed a 'NOFOLLOW' link to those hyperlinks, but the issue still persists.

Our initial set-up for the 'add to cart' button for each product on the Product Overview Page was that people could instantly add a product to the shopping cart without first having to visit the product page. On the other hand, we chose to offer customers the opportunity to pay as a guest. This, as well, to rule out as many stumbling blocks as possible during the ordering process, which may discourage customers.

Does anyone have a possible solution, preferably a solution that does not compromise the user experience (or has as little impact as possible on the UX?).

# Answer
Blocking is hard. Honeypot is a good deterrent, but if you allow anonymous users to click links that add products, then having spam orders might be your new reality. Removing useless, old carts is easy.

We use Commerce Cart Expiration on a number of stores. Also, sometimes its preferable to delete orders outright based on some criteria. For that, you can use Commerce Order Cleanup utility module.
> 2 votes

# Answer
First off you should block the IP off the spam bot to stop all the orders coming through. This can be done in standard Drupal interface in D7.

Then install some or all of these modules. https://www.drupal.org/project/recaptcha is very good and may solve your problems. This is by Google and blocks known threats from your site, which probably include your daily visitor.

In the past I have had great results from using the Botcha module. This also uses a honeypot field to trick the spam bots. This will solve your UX issues as it works in the background and will reduce your spam considerably.

Maybe later, if you are going to create user accounts to your store, verify the users email using a verify, for example with the Email Verify module.
> 0 votes

---
Tags: commerce, advertising
---


title: Get all the nodes in the system

text:
# Question
Title: Get all the nodes in the system
I've found node\_load\_multiple() which allows me to get all the nodes, but I need to specify some parameters, e.g. the type of node that I'd like to fetch.

I'd like to get all the nodes in the system without the criteria. How can I do that?

# Answer
> 4 votes
The easiest way would be to use `entity_load()`

```
$nodes = entity_load('node');

```

If you don't provide the second argument (`$ids`) it will load up all entities of the given type:

> $ids: An array of entity IDs, or FALSE to load all entities.

Just for the sake of completeness `node_load_multiple()` doesn't require the `$conditions` parameter so you could also grab all of the node ids from the database

```
$nids = db_query('SELECT nid FROM {node}')->fetchCol();

```

And then use `$nids` to load the nodes:

```
$nodes = node_load_multiple($nids);

```

# Answer
> 1 votes
Just use `node_load_multiple(FALSE)`, and you will get all the nodes present in the site.

Keep in mind that it returns all the nodes, and this would be a problem when there are many nodes: The function takes time to be executed, and each node uses memory to be stored. With enough nodes, you would exhaust all the available memory.

Using the EntityFieldQuery class, you can limit the number of returned nodes.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', 1)
  // It returns the first 10 nodes.
  // Use range(10, 10) to get the next 10 nodes.
  ->range(0, 10);

$result = $query->execute();

if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
}

```

I added `propertyCondition('status', 1)` because you are normally interested on published nodes; if you want to get all the nodes, remove that line.

Notice that the `$conditions` parameter for node\_load\_multiple() is not anymore used in Drupal 8. If you need to get some nodes basing on some conditions, you should use the `EntityFieldQuery` class.

### References

# Answer
> 0 votes
Here is another way to find all node ids in your website.

```
$nids = array_values(\Drupal::entityQuery('node')->execute());

```

---
Tags: nodes
---


# Question
Title: Finding out version, and updating to latest stable core version
I have inherited a site that uses Drupal, but I've not had any experience with it before. I'm trying to move it over to a server that has *PHP 7* on, but I get all kinds of errors:

> warning: Declaration of cck\_facet::build\_root\_categories\_query(&$query) should be compatible with faceted\_search\_facet::build\_root\_categories\_query() in /home/user/web/foo.org/public\_html/sites/all/modules/cck\_facets/cck\_facets.inc on line 16. warning: Declaration of author\_facet::build\_root\_categories\_query(&$query) should be compatible with faceted\_search\_facet::build\_root\_categories\_query() in /home/user/web/foo.org/public\_html/sites/all/modules/faceted\_search/author\_facet.module on line 0. warning: Declaration of content\_type\_facet::build\_root\_categories\_query(&$query) should be compatible with faceted\_search\_facet::build\_root\_categories\_query() in /home/user/web/foo.org/public\_html/sites/all/modules/faceted\_search/content\_type\_facet.module on line 0. warning: Declaration of date\_authored\_facet::build\_root\_categories\_query(&$query) should be compatible with faceted\_search\_facet::build\_root\_categories\_query() in /home/user/web/foo.org/public\_html/sites/all/modules/faceted\_search/date\_authored\_facet.module on line 0. warning: Declaration of taxonomy\_facet::build\_root\_categories\_query(&$query) should be compatible with faceted\_search\_facet::build\_root\_categories\_query() in /home/user/web/foo.org/public\_html/sites/all/modules/faceted\_search/taxonomy\_facets.module on line 0. warning: Creating default object from empty value in /home/user/web/foo.org/public\_html/sites/all/modules/panels/panels.module on line 1093. user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IN ('hebergement')) AND (.status = '1') AND (node\_data\_field\_photographie.field\_' at line 1 query: SELECT DISTINCT(node.nid), changed FROM node node LEFT JOIN content\_field\_photographie node\_data\_field\_photographie ON node.vid = node\_data\_field\_photographie.vid INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'og\_public'))) AND ( (.type IN ('hebergement')) AND (.status = '1') AND (node\_data\_field\_photographie.field\_photographie\_fid \> 0) AND ((.uid NOT IN ('1','45','42') OR .uid IS NULL)) ) ORDER BY DESC LIMIT 0, 12 in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 154. user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IN ('promotion')) AND (.status = '1') AND (DATE\_FORMAT(STR\_TO\_DATE(node\_data\_fie' at line 1 query: SELECT DISTINCT(node.nid), node\_data\_field\_date\_de\_dbut.field\_date\_de\_dbut\_value AS node\_data\_field\_date\_de\_dbut\_field\_date\_de\_dbut\_value, node.title AS node\_title, node\_data\_field\_date\_de\_dbut.field\_date\_de\_dbut\_value2 AS node\_data\_field\_date\_de\_dbut\_field\_date\_de\_dbut\_value2, v9node.nid AS v9node\_nid, v9node.title AS v9node\_title FROM node node LEFT JOIN content\_field\_date\_de\_dbut node\_data\_field\_date\_de\_dbut ON node.vid = node\_data\_field\_date\_de\_dbut.vid INNER JOIN nodefamily nodefamily\_child ON node.nid = nodefamily\_child.child\_nid LEFT JOIN node v9node ON nodefamily\_child.parent\_nid = v9node.nid INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'og\_public'))) AND ( (.type IN ('promotion')) AND (.status = '1') AND (DATE\_FORMAT(STR\_TO\_DATE(node\_data\_field\_date\_de\_dbut.field\_date\_de\_dbut\_value2, '%Y-%m-%dT%T'), '%Y-%m-%d') \> '2017-06-16') ) ORDER BY node\_data\_field\_date\_de\_dbut\_field\_date\_de\_dbut\_value ASC LIMIT 0, 10 in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 154. warning: mysqli\_real\_escape\_string() expects parameter 2 to be string, array given in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 383. warning: mysqli\_real\_escape\_string() expects parameter 2 to be string, array given in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 383. user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '1') AND (.type IN ('bon\_plan')) AND (.tid AND '') AND (. \> 0) ) ORDER BY DE' at line 1 query: SELECT DISTINCT(node.nid), changed, node.title AS node\_title, users.name AS users\_name FROM node node LEFT JOIN content\_field\_photographie node\_data\_field\_photographie ON node.vid = node\_data\_field\_photographie.vid INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'og\_public'))) AND ( (.status = '1') AND (.type IN ('bon\_plan')) AND (.tid AND '') AND (. \> 0) ) ORDER BY DESC LIMIT 0, 20 in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 154. user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '1') AND (.type IN ('hebergement')) AND (node\_data\_field\_photographie.field\_ph' at line 1 query: SELECT DISTINCT(node.nid), random, node.title AS node\_title, location.city AS location\_city, location.postal\_code AS location\_postal\_code FROM node node LEFT JOIN content\_field\_photographie node\_data\_field\_photographie ON node.vid = node\_data\_field\_photographie.vid LEFT JOIN userpoints userpoints ON node.uid = userpoints.uid LEFT JOIN location\_instance location\_instance\_node ON node.vid = location\_instance\_node.vid LEFT JOIN location location ON location\_instance\_node.lid = location.lid INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'og\_public'))) AND ( (.status = '1') AND (.type IN ('hebergement')) AND (node\_data\_field\_photographie.field\_photographie\_fid \> 0) AND (userpoints.points \> '40') ) ORDER BY ASC LIMIT 0, 1 in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 154. user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '1') AND (.type IN ('hebergement')) AND (votingapi\_cache\_vote\_percent\_average.' at line 1 query: SELECT DISTINCT(node.nid), votingapi\_cache\_vote\_percent\_average.value AS votingapi\_cache\_vote\_percent\_average\_value, votingapi\_cache\_vote\_percent\_count.value AS votingapi\_cache\_vote\_percent\_count\_value, votingapi\_vote\_vote\_percent.value AS votingapi\_vote\_vote\_percent\_value, node.title AS node\_title FROM node node LEFT JOIN votingapi\_cache votingapi\_cache\_vote\_percent\_average ON node.nid = votingapi\_cache\_vote\_percent\_average.content\_id AND votingapi\_cache\_vote\_percent\_average.content\_type = 'node' AND votingapi\_cache\_vote\_percent\_average.value\_type = 'percent' AND votingapi\_cache\_vote\_percent\_average.tag = 'vote' AND votingapi\_cache\_vote\_percent\_average.function = 'average' LEFT JOIN votingapi\_cache votingapi\_cache\_vote\_percent\_count ON node.nid = votingapi\_cache\_vote\_percent\_count.content\_id AND votingapi\_cache\_vote\_percent\_count.content\_type = 'node' AND votingapi\_cache\_vote\_percent\_count.value\_type = 'percent' AND votingapi\_cache\_vote\_percent\_count.tag = 'vote' AND votingapi\_cache\_vote\_percent\_count.function = 'count' LEFT JOIN votingapi\_vote votingapi\_vote\_vote\_percent ON node.nid = votingapi\_vote\_vote\_percent.content\_id AND votingapi\_vote\_vote\_percent.content\_type = 'node' AND votingapi\_vote\_vote\_percent.value\_type = 'percent' AND votingapi\_vote\_vote\_percent.tag = 'vote' INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'og\_public'))) AND ( (.status = '1') AND (.type IN ('hebergement')) AND (votingapi\_cache\_vote\_percent\_average.value \> 20) ) ORDER BY votingapi\_cache\_vote\_percent\_average\_value DESC, votingapi\_cache\_vote\_percent\_count\_value DESC LIMIT 0, 10 in /home/user/web/foo.org/public\_html/includes/database.mysqli.inc on line 154.

I've already done a search and replace of &$ to just $, as I read that this method was depreciated in PHP 5.4 onwards.

```
perl -p -i -e 's|\&\$|\$|g' `grep  --include \*.inc -rl '&$' .`
perl -p -i -e 's|\&\$|\$|g' `grep  --include \*.module -rl '&$' .`
perl -p -i -e 's|\&\$|\$|g' `grep  --include \*.php -rl '&$' .`

```

So now I'm trying to figure out how I update all of the modules / apply all the Drupal 7 patches. I'm used to Wordpress, where it just does it all for you. To me, it seems like everything has to be done manually here. Is that correct?

Any ideas / suggestions would be much appreciated - I'm drowing a bit here!

# Answer
> 1 votes
You can update your site as follows:

* Via Drush: run `drush rf && drush ups` to check for updates. To update a module run `drush up [module-name]` or `drush up drupal` to update core.
* Via the interface: visit `/admin/modules`. Note that this is not recommended. Also core updates cannot be done through the interface. If possible use Drush.
* Manual: download the new module packages individually from Drupal.org and replace them in your modules folder. Note that this is not recommended, use Drush.

You can check your site's status via `/admin/reports/status`. A lot of information is deplayed here, including the core version.

More information about installing Drush: http://docs.drush.org/en/master/install/

---
Tags: updating
---


title: How can I output a field as link?

text:
# Question
Title: How can I output a field as link?
I have a title field and some date fields in my view in the following order

1.title

2.from\_date

3.to\_date

Since the title is long, I have trimmed and it is a known bug that the links don't work after trimming.

So how can I add a link to the title so that when I click on it, gets redirected? Please help somebody.

# Answer
> 3 votes
I have found a solution for the problem. Follow the steps.

1. Add a field 'Path' above the 'Title' field.
2. Exclude 'Path' field from display.
3. Uncheck the link to content from 'Title'
4. In Title-\>Rewrite Results check output this field to custom link and set path as {{ path }}.

OR

1. Add a field 'ID' above the 'Title' field.
2. Exclude 'ID' field from display.
3. Uncheck the link to content from 'Title'
4. In Title-\>Rewrite Results check output this field to custom link and set path as /node/{{ nid }}.

It both works.

---
Tags: views, 8
---


# Question
Title: How can I translate the name of a vocabulary?
I am looking for a solution through which **Vocabulary name** can be translated. I'm using the i18n module with latest D7.

Currently I have chosen the option like so:

> Translate. Different terms will be allowed for each language and they can be translated.

Here is a screenshot to illustrate that option:

I am able to translate terms of this vocabulary as shown in the screenshot below:

**Problem Statement:** How can I translate the vocabulary name, i.e. "Test Vocabulary English" in my example above.

# Answer
# Typical taxonomy translation issues

My best guess is that you are experiencing the typical taxonomy translation issues, as described in the community documentation about Taxonomy translation also. While digesting that, you may want to verify one of its comments, which is about using the Title module also.

The closest I have come so far with translated terms (and without using the Title module), is similar to the setup you have done so far. The result of it being that when you want to select a term from a taxonomy on a language specific node, you get a list of all terms to select from (with all terms from all languages). Not the ideal solution, but similar to what is written in the URL I mentioned, and probably "as good as it gets in D7".

# Translate vocabulary name

If however you're only looking for a way to translate the vocabulary name (as the title of your question indicates), then be aware that that is simply not possible today, and is actually a known issue: Vocabulary Name value doesn't get translated. It dates from 2005 (!), related to D6, status "won't fix". However comment # 2 in that issue states:

> I have used the locale module to translate the name of the vocabulary, and display it with t($vocabulary-\>name). If all modules would display the name this way (e.g. taxonomy\_menu does it), then there is no need for a new database table i18n\_vocabulary.

The **t($vocabulary-\>name)** seems like a possible/partial work around to consider, i.e. from within a (custom) module.

There is a more recent similar issue, i.e. Vocabulary names are not translated. That one is for D7, with status "needs work".

Another potential work around could be to have a separate taxonomy for each language (and with a "name" corresponding to that language). Of course, you'd have to think how to best use these separated taxonomies for each content type (a kind of "solution to the problem, changes the problem) ...
> 2 votes

# Answer
```
global $language;
$vid = 1; //sample
$vocabulary = taxonomy_vocabulary_load_multiple(array($vid));
$vname = i18n_taxonomy_vocabulary_name($vocabulary[$vid], $language->language);

```

You need to have Taxonomy translation (i18n\_taxonomy) installed.
> 0 votes

---
Tags: 7, taxonomy-terms, i18n-l10n
---


# Question
Title: Let the user set the target of the link in a link field
Link module has been added to core in Drupal 8, but it doesn't seem that all its features has been ported.

For example, letting the user choose the target of the menu. In Drupal 7, the module would let me create a field and in its configuration set an option to let the user choose the target. In Drupal 8, I don't see that option.

Is that option present in Drupal 8?

# Answer
You can use https://www.drupal.org/project/link\_attributes for that. No, it is not in core.
> 6 votes

---
Tags: navigation
---


# Question
Title: Change user role programmatically using cron according to Webservice
On my site I want to set cron job that will check if user already submited form that allow them to browse website freely. I tried to catch user id (and assign a new role id) in `\core\lib\Drupal\Core\Cron.php` using

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
      error_log($user->get('uid')->value);

```

but it seems like it doesn't know context of user and prints just `0`. Is there anyway to do this? Is this even possible in drupal?

# Answer
Ok I managed to do it by using

```
$user = user_load_by_name('user');
$user->addRole('administrator');
$user->save();

```

that way i got user and i could assign it a designated role.

Unfortunatelly I can't show you webservices handling code due to company policy.
> 0 votes

# Answer
In order to load the user, your are passing the UID of the current user, is it not what you want ?

```
\Drupal::currentUser()->id()

```

I don't have a full vision of what you want, but it should return the current user UID.
> 0 votes

---
Tags: 8, cron
---


# Question
Title: Drush not working on a docker based enviroment on ubuntu 16.04
I have set up a local dev docker environment with the Drupal social distribution. My issue is that Drush commands do not work and whenever I run a Drush command, it takes approximately 45 seconds to get a response. Generally, the output is always the same or similar to the following.

> \[warning\] proc\_open(): unable to dup File-Handle for descriptor 2 - Too many open files exec.inc:243
> \[warning\] proc\_get\_status() expects parameter 1 to be resource, boolean given exec.inc:244
> \[warning\] proc\_close() expects parameter 1 to be resource, boolean given exec.inc:245

I am unsure what the reason for this response is or what I may have done wrong to get to this point. I tried googling the warning errors but without getting a usable answer. If someone has had similar problems and managed to solve it, some directions on what to do would be appreciated.

I also want to state that outside the docker environment I have setup multiple Drush setups; Drush commands work normally without any delay outside of it.

My environment is Ubuntu 16.04 with 15.5 GB RAM, i7-6500U CPU 2.5 GHz x4 Processor, 200GB DDR disk.

I googled some more and found out that for running Drush inside a docker environment you need `docker-compose run drush "drush command here"` since Drush container gets run only for one specific command and then shuts back down, but now I am getting different errors.

`docker-compose run drush cache-rebuild --verbose --debug` gives this as output.

> Phar detected. Proceeding to drush\_main().Drush preflight prepare loaded autoloader at \[0 sec, 2.92 MB\] \[preflight\]
> Starting Drush preflight. \[0 sec, 2.92 MB\] \[preflight\]
> Cache HIT cid: 8.1.2-commandfiles-0-9c75c37463d39480ab97163ab2be3712 \[0.01 sec, 2.96 MB\] \[debug\]
> Scanning into /etc/drush for /.\*aliases.drush(8|)rc.php$/ \[0.02 sec, 5.02 MB\] \[debug\]
> Scanning into /etc/drush for /self.alias.drush(8|)rc.php$/ \[0.02 sec, 5.02 MB\] \[debug\]
> Scanning into phar:///usr/local/bin/drush/includes/.. for /.\*aliases.drush(8|)rc.php$/ \[debug\] \[0.02 sec, 5.02 MB\]
> Scanning into phar:///usr/local/bin/drush/includes/.. for /self.alias.drush(8|)rc.php$/ \[debug\] \[0.03 sec, 5.03 MB\]
> Scanning into /root/.drush for /.\*aliases.drush(8|)rc.php$/ \[0.04 sec, 5.03 MB\] \[debug\]
> Scanning into /root/.drush for /self.alias.drush(8|)rc.php$/ \[0.04 sec, 5.03 MB\] \[debug\]
> Bootstrap to phase 0. \[0.05 sec, 6.01 MB\] \[bootstrap\]
> Bootstrap to phase 2. \[0.05 sec, 6.01 MB\] \[bootstrap\]
> Command cache-rebuild needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. \[error\] \[0.05 sec, 6.01 MB\]
> Command cache-rebuild requires Drupal core version 8+ to run. \[0.05 sec, 6.01 MB\] \[error\]
> The drush command 'cache-rebuild' could not be executed. \[0.05 sec, 6.01 MB\]

Hope that gives you a clue of what is the matter here.

# Answer
When you run `docker run ...` or `docker-compose run`, Drush is running in the context of the container, not your host machine. So when it needs stuff like DB credentials, aliases, ssh keys, it looks for them in the container. If Drush cannot find such things in the container, Drupal cannot fully connect to Drupal and you get an error, usually the bootstrapping one.

I have a feeling your code isn't mounted to the Drush container, based on the fact that the alias scanning isn't picking up anything custom, only the usual alias paths. If the code is mounted, then probably the Drush container does not have the DB credentials. Do a `drush status` to check if everything is fine.
> 1 votes

---
Tags: drush
---


# Question
Title: How can I rebuild my installation after attempting to manually update D8 core using D7 instructions?
After following the manual update instructions linked from the download page for Drupal 8.3.4, I got a "The website encountered an unexpected error. Please try again later." This is when I noticed that the breadcrumb for the update instructions said "Drupal 7".

As per the erroneusly linked instructions, I have deleted every file and folder in my drupal 8.3.2 installation except /sites, and I'm wondering what I need to do to restore them. Is there a reliable way to find out exactly which modules I had installed (e.g. translation files, or database tables?), and can I fix the problem by manually uploading the modules to /modules, or could the failed update.php job have damaged my installation?

(My server doesn't support automatic updates, and I only have FTP/MySQL access.)

# Answer
> 0 votes
Manually uploading the 3rd party modules to /modules (atleast the modules i found translation files for in my /sites folder) and restoring my database from backup, allowed me to restart the update process; so far everything seems to be working again.

---
Tags: 8, updating
---


title: Share data from view

text:
# Question
Title: Share data from view
How can I share data from a view to an excel file. I just need a report.

Or can anyone suggest a solution from which I can extract the data from a view?

# Answer
> 1 votes
I think Views data export module is what you need.

---
Tags: views, 8
---


title: How do I import using features?

text:
# Question
Title: How do I import using features?
I have a drupal site and I exported a Drupal feature and got a download file. Now I want to import that file to another drupal site, but there is no import function, so how do I add it?

# Answer
You just need to copy this folder generated by Features into your /sites/all/modules/features directory. A feature is a module, you'll need to enable this feature on your new site to retrieve all the functionnalities.

You'll probably need to take a close look at the documentation for Drupal 7 https://www.drupal.org/docs/7/modules/features to achieve this correctly.
> 3 votes

---
Tags: 7, features
---


# Question
Title: Correct image path to use in template files of custom themes
I'm creating a custom theme. Under my theme's folder, there is an `images` folder where I've put some pictures. I want to use these images in my various template (`.tpl.php`) files using HTML `<img>` tag... but the problem is how do i get correct path for these images (the `src` attribute)?

I've searched for a while but didn't get any solutions. Please help.

**EDIT:** I'm using nice urls (http://mydrupalsite.com/a/b/c/d) - type URLs. So, if the image `src` begins with `/` (or any relative path) it would break.

# Answer
> 14 votes
I think these functions could be useful in your templates:

```
print base_path() . path_to_theme();

```

path\_to\_theme() Return the path to the current themed element. base\_path() The base path of the Drupal installation.

for example, I have an image called `bg-bar.png` inside `images` directory in my template directory called `garland`. then I can use `base_path()` and `path_to_theme()` to get the path to the image, for example inside node.tpl.php:

```
print '<img src="'.base_path() . path_to_theme() .'/images/bg-bar.png">';

```

**Update:** if you want to use the current domain, you can use `global $base_root`:

```
  $address = ''.base_path() . path_to_theme() .'/images/bg-bar.png';
  global $base_root;
  echo '<img src="' . $base_root . $address . '">';

```

I hope information be useful.

# Answer
> 0 votes
Since my image was in a conditional block, the above syntax posed some problems and the following worked for me. However, I am not sure if it is advisable from a maintenance perspective:

```
src='<?php print base_path().path_to_theme().'/images/iphone.png' ?>'

```

---
Tags: 7, theming
---


# Question
Title: Print Entity Reference Value from Entity Meta Wrapper
I have this code to get entity meta wrapper and print text fields. But I can't see how to print entity reference values.

```
$wrapper = entity_metadata_wrapper('my_entity', $entity);
print $wrapper->field_my_field->value();

```

# Answer
You can access entity reference values by calling entity metadata wrapper API on the reference field.

For instance, if you have a node with a field which references a `profile2` entity,

```
$wrapper = entity_metadata_wrapper('node', node_load(1));
$profile_wrapper = entity_metadata_wrapper('profile2', $wrapper->field_profile->value());
print $profile_wrapper->field_about->value();

```

or if you prefer rendering the entity,

```
print render($profile_wrapper->view());

```
> 3 votes

# Answer
You can access entity reference values without creating a new wrapper. Entity metadata wrappers can be chained easily.

If a field is a reference field or a taxonomy term etc, the value will be the ID of the referenced entity. If you want to get the title/name of the entity, you can use the `label()` method.

A sample code:

```
$wrapper = entity_metadata_wrapper('my_entity', $entity_id);
// To print the title/name of the referenced entity
print $wrapper->field_my_reference_field->label();
// To print the value of a field on the referenced entity
print $wrapper->field_my_reference_field->field_on_referenced_entity->value();

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to use the Features API to enable a feature?
So I looked at the features API, and in order to enable a feature, they use this code:

```
function hook_pre_features_enable_feature($component){
};

```

So I go in and add this:

```
function mysite_pre_features_enable_feature($component){
    $component = 'roles';
};

```

My Feature is already there, but it never gets enabled. Why is this?

# Answer
> in order to enable a feature, they use this code

That's not accurate. The hook function is actually:

> Invoked on a Feature module before that module is enabled.

It's not involved with the action of enabling the feature, it's just a listener to enable it to run some code just before something else enables it.

Features are just modules, and to enable one you use the same method as if you were just enabling a module:

```
module_enable(['foo']);

```
> 1 votes

---
Tags: 7, features
---


# Question
Title: How to apply a Field Formatter to a node field programmatically?
I have the following code to get the value that is stored in a field

```
$nid = 76;
$node = \Drupal::service('entity.manager')->getStorage('node')->load($nid);
foreach ($node->field_aaaa as $delta) {
  dpm($delta->value);
}

```

With this I can get the correct value let says:

```
 * id_string1
 * id_string2
 * id_string3

```

But my field has a Field Formatter named `title_formatter` that will take the string `id_string1` and will show something like this:

```
String 1

```

In the UI this works fine if I chose my Title Formatter (title\_formatter) for the field I can see the `'String'` when I viewing my node.

But how to apply the Field Formatter programmatically to the field values?

# Answer
The entity view builder provides a method to build a render array for a single field using a field formatter:

`Drupal\Core\Entity\EntityViewBuilderInterface::viewField()`

```
  /**
   * Builds a renderable array for the value of a single field in an entity.
   *
   * The resulting output is a fully themed field with label and multiple
   * values.
   *
   * This function can be used by third-party modules that need to output an
   * isolated field.
   * - Do not use inside node (or any other entity) templates; use
   *   render($content[FIELD_NAME]) instead.
   * - The FieldItemInterface::view() method can be used to output a single
   *   formatted field value, without label or wrapping field markup.
   *
   * The function takes care of invoking the prepare_view steps. It also
   * respects field access permissions.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   FieldItemList containing the values to be displayed.
   * @param string|array $display_options
   *   Can be either:
   *   - The name of a view mode. The field will be displayed according to the
   *     display settings specified for this view mode in the $field
   *     definition for the field in the entity's bundle. If no display settings
   *     are found for the view mode, the settings for the 'default' view mode
   *     will be used.
   *   - An array of display options. The following key/value pairs are allowed:
   *     - label: (string) Position of the label. The default 'field' theme
   *       implementation supports the values 'inline', 'above' and 'hidden'.
   *       Defaults to 'above'.
   *     - type: (string) The formatter to use. Defaults to the
   *       'default_formatter' for the field type. The default formatter will
   *       also be used if the requested formatter is not available.
   *     - settings: (array) Settings specific to the formatter. Defaults to the
   *       formatter's default settings.
   *     - weight: (float) The weight to assign to the renderable element.
   *       Defaults to 0.
   *
   * @return array
   *   A renderable array for the field values.
   *
   * @see \Drupal\Core\Entity\EntityViewBuilderInterface::viewFieldItem()
   */
  public function viewField(FieldItemListInterface $items, $display_options = []);

```

To apply this method on a field object you can use `$field->view()` or if you only want a single value from a multivalue field without the wrapper and label you can also use it on a field item (delta).

**EDIT:** With this code you can find the values that you need.

```
$nid = 76;
$node = \Drupal::service('entity.manager')->getStorage('node')->load($nid);
foreach ($node->field_aaaa as $i => $delta) {
  dpm($delta->value);
  dpm((string) \Drupal::service('renderer')->render($delta->view(array('type' => 'title_formatter'))));
}

```
> 8 votes

# Answer
I'm sure that this is not the best option but at least it works.

Go to admin/structure/types/manage/YOUR\_CONTENT\_TYPE/display and select the `Title Formatter` for your field, and then use this code:

```
$nid = 76;
$node = \Drupal::service('entity.manager')->getStorage('node')->load($nid);
foreach ($node->field_aaaa as $i => $delta) {
  dpm($delta->value);
  dpm($node->field_aaaa->view('full')[$i]['#markup']);
}

```

You will see this:

```
* id_string1
* String 1
* id_string2
* String 2
* id_string3
* String 3

```

**EDIT:** The correct way using the @4k4 answer is:

```
$nid = 76;
$node = \Drupal::service('entity.manager')->getStorage('node')->load($nid);
foreach ($node->field_aaaa as $i => $delta) {
  dpm($delta->value);
  dpm((string) \Drupal::service('renderer')->render($delta->view(array('type' => 'title_formatter'))));
}

```
> 3 votes

---
Tags: 8, entities
---


title: REST Serialization escapes URLs

text:
# Question
Title: REST Serialization escapes URLs
Since updating to 8.3 we've noticed that some URL's in our REST responses are being escaped (this may have been happening before but I don't think so as it is now causing issues with the Android parser).

The URL's are escaped like this;

```
{"_links":
    {"self":
        {"href":"http:\/\/example.com\/api\/resource\/80?_format=hal_json"}

```

Those w's (//) and v's (/) are killing things and I'd like to remove this escaping.

BTW, this API is password protected and used by a controlled app only. While removing this escaping may introduce issues with public API's and security/stabiliy, we don't need this level of control.

Can I just override the `Serialize` class and use that?

# Answer
> 1 votes
Actually, I can't see how this could have been different prior to 8.3 - PHP's `json_encode` seems to have been escaping `/` by default forever, and neither Drupal nor Symfony seem to have overridden that in the past.

The service ID and class you would need to override is `serializer.encoder.json` (`Drupal\serialization\Encoder\JsonEncoder`), adding a `JSON_UNESCAPED_SLASHES` to the options bitmask in the constructor. (Confusingly, there's a separate service named `serialization.json`, which isn't the one that's used here.)

However, note that `\/` is a valid escape sequence in JSON (if not strictly required), and a JSON parser must interpret this as a literal forward slash character to be working correctly. There should be no backslashed URLs in the parsed values. Is it possible that your client's parser library has a bug?

---
Tags: 8
---


# Question
Title: Better exposed filters - collapse all filters after submit
I'm using BEF (Better Exposed Filters) and I want to this simple thing:

Whenever the button Submit (from the views exposed form) is clicked, all filter must be collapsed (must close).

What is the best way to achieve this?

# Answer
The default BEF behavior reloads the entire page after clicking the "Submit" button (at least on D8 - it's been a while since I've worked with BEF on D7). This means you can just add styles + js to have the form collapsed when the page loads; they can expand the form, choose their options, click "Submit", and the form will be closed again when the page re-loads.

If you have a different behavior on your site - i.e. filters that upload the view live, without having to refresh the page - use JS with an .on(click) function to add a "collapsed" class to your form, and use the same styles + js mentioned above to collapse the form.
> 0 votes

---
Tags: views
---


# Question
Title: How can I send private message to Facebook?
I tried to build next feature using Drupal 7. When my site has new content, users get message about it into e-mail and Facebook private message. As for e-mail I not see any problem, but about FB private message I have not any idea. I know about username@facebook.com way. But how it works for users, who not have username (only ID)? Any other idea?

How can I do it? Can you give me right direction?

Thx for any answer. Best.

# Answer
For users who don't have a set username through Facebook, there is no way to email them. Facebook does not allow messages to be sent via email using a user's ID - only their set username.

However, with a bit of quick research regarding these IDs, it looks like Facebook has completely discontinued this e-mail service. As multiple articles turned up, it sounds like the email-to-Facebook-message service ended in 2014, though Facebook would still forward emails to username@facebook.com to that user's set primary email address (so if someone emailed username@facebook.com, the message would appear in that user's primary email address, i.e. myFakeEmail@gmail.com). That message-forwarding service appears to have ended in ~May 2016.

If you still want to test this for yourself, you can; but even if it somehow still works, Facebook has never supported email-to-ID, so that unfortunately won't be possible.
> 0 votes

---
Tags: 7, rules, social-network
---


# Question
Title: How to Auto-save a custom entity to database in response to a new user account using Rules?
I have defined new custom entity through `hook_entity_info`:

```
function mymodule_entity_info(){
  return array(
    'mymodule_account' => array(
      'label' => 'MyModule Account',
      'entity class' => 'MymoduleAccount',
      'controller class' => 'EntityAPIController',
      'views controller class' => 'EntityDefaultViewsController',
      'base table' => 'mymodule_accounts',
      'entity keys' => array(
        'id' => 'aid',
      ),
      'fieldable' => TRUE,
      'load hook' => 'mymodule_account_load',
      'view modes' => array(
        'full' => array('label' => 'Full', 'custom settings' => FALSE),
        'teaser' => array('label' => 'Teaser', 'custom settings' => FALSE),
      ),
    ),

  );
}

```

I have extended the `Entity` class, overriding the constructor:

```
class MymoduleAccount extends Entity{

  public function __construct(array $values = array(), $entityType =
  'mymodule_account'){

    global $user;
    if(empty($values)){
      $values['created'] = REQUEST_TIME;
      $values['title'] = '';
      $values['balance'] = 0.00;
      $values['uid'] = $user->uid;
    }

    $this->entityType = $entityType;
    $this->setUp();
    // Set initial values.
    foreach ($values as $key => $value) {
      $this->$key = $value;
    }
  }
}

```

I have defined a reaction-rule as follows:

On `events` segment: I selected

```
After saving a new user account

```

On `actions` segment: I defined two elements:

```
Create a new entity
Parameter: Entity type: Mymodule Account
Provides variables: Created entity (entity_created)

```

And:

```
Save entity
Parameter: Entity: [entity-created], Force saving immediately: true

```

I have tested these codes by creating new `user` account, but no `mymodule_account` has been created in it's database table. What am I missing?

# Answer
Your issue (about "*no account has been created in DB table*") might possibly be because of the event (= "*after saving new user account*") you are using, which might simply not be the right event.

Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).

Not sure if this is "the" reason for your issue, but I'd definitely give it a try to see if it helps (debugging is the art of taking away all possible causes for an issue ...).
> 0 votes

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


# Question
Title: Disable caching (for theme develoment) doesn't work
I'm quite desperate. I have disabled it in the admin backend (Administration -\> Configuration -\> Development -\> "Page cache maximum age" = "\<no caching\>"). In `sites/default/services.yml` I have:

```
parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

```

I even tried to disable the *opcache* (wich makes not much sense, of course). The templates get translated (or rendered?) only once after I manually clear the cache.

I'm using Drupal 8.3.4, PHP 7.1 with php-fpm, postgresql and lighttpd on CentOS.

To always clear the cache – by clicking in the interface or `drush cr` – feels like compiling a c++ application. And doing a `delete from cache_render; delete from cache_dynamic_page_cache; delete from cache_entity;` in the `psql` console feels 500 times faster but also isn't really convenient.

# Answer
You need to follow the procedure in */sites/example.settings.local.php*:

```
/**
 * @file
 * Local development override configuration feature.
 *
 * To activate this feature, copy and rename it such that its path plus
 * filename is 'sites/default/settings.local.php'. Then, go to the bottom of
 * 'sites/default/settings.php' and uncomment the commented lines that mention
 * 'settings.local.php'.
 *
 * If you are using a site name in the path, such as 'sites/example.com', copy
 * this file to 'sites/example.com/settings.local.php', and uncomment the lines
 * at the bottom of 'sites/example.com/settings.php'.
 */

```

This will enable the service for a null cache backend in *development.services.yml*, which you then can assign to cache bins of your choice by uncommenting these lines:

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

```

Then you no longer need to truncate the cache tables.
> 1 votes

---
Tags: caching
---


# Question
Title: Using Feeds to import multiple languages
I've already imported a data set of about 1500 articles, all in English. I have another set of the data with matching node ids but in different languages. Can I import a second file into Drupal 7 and have the localized content mesh up with the existing data?

Currently when I try to import the data it overwrites the existing content, I need them to co-exist with the only difference being a language code.

# Answer
> 7 votes
Import from two xml files (on for each language), my empiric solution :

1. I created two feed imports.
2. I forced the language field for each one.
3. Two separated nodes were created for each content (one in each language) but it didn't links the translations.
4. So I used a SQL query to finish the job, it's based on the feeds uuid

**Note:** In order for this to work your GUID must match between the two sources. If you have set that to the node title it is important that you turn off the option to replace content as it will update the previous import :/

```
UPDATE
    node n,
    feeds_item lng1,
    feeds_item lng2
SET
    n.tnid = lng1.entity_id
WHERE
    (
        n.nid = lng1.entity_id
        OR
        n.nid = lng2.entity_id
    )
    AND lng1.id='feeds_importname_for_lng1'
    AND lng2.guid=lng1.guid
    AND lng2.id='feeds_importname_for_lng2'

```

# Answer
> 1 votes
It is possible to achieve this with needing SQL queries.

Also if you want to do anything with field translation in feeds, make sure you have a current version. Newer than a year ago, because of https://www.drupal.org/node/1183440 This version supports entity translation, which you'll need of course. It allows for fields to be translated. So you'll have 1 entity which several fields. These fields can be translated independently.

You will have to set a Unique identifier setting on both feeds importers to be imported and these should of course be the same (ypur matching node ids). You can then set in the processors' mapping settings that an input record should a into a particular fields' translation.

So,

1. create two importers, one for each language.
2. in both, set your 'matching node ids' as 'Used as Unique' In the feeds processor mapping settings.
3. set the language setting in the mapping.

If you can see the language setting, doublecheck the Entity Translations and field settings.

---
Tags: feeds, importing-exporting, i18n-l10n
---


# Question
Title: Set active trail in hook_preprocess_node
For some content type, I need to attach my node to a parent menu item. I don't want to do that with UI (because too many nodes). I saw something like that for Drupal 7 (works in a preprocess):

```
menu_tree_set_path('main-menu', 'my/parent/path');

```

Do you know a way to do that with Drupal 8 (menu\_tree\_set\_path seems undefined) ?

# Answer
The menu active trail is defined by the menu.active\_trail service. Unfortunately it doesn't use a tag based extension like breadcrumbs.

You can replace that service and in case you detect that you're on a patch displaying a certain content type, return your desired structure.

You could also try out the https://www.drupal.org/project/menu\_trail\_by\_path module, which defines the active trail based on the aliased path, like breadcrumbs do by default.
> 2 votes

---
Tags: 8, navigation
---


# Question
Title: How do I create an invoice without product?
Am working a project that required generating invoice for customer service payment, 'rent' to be specific. Am still a newbie to drupal environment (I do Wordpress Stuff).

Since the Payment is going to be recurrent I choose Drupal Commerce, but am confuse as to how to configure the module(s) needed.

Features that I need \- Admin created invoice for Client (registered user) with invoice status UNPAID \- Invoice sent to Client via email (PDF format) \- Client Pay at Bank and upload Prove of payment \- Admin change the invoice status to PAID upon Validation.

I could Create Content type for the invoice, but I may not be able to create PDF and mail it to user in which Drupal Commerce would handled well with other Contributed Module.

I should be able to handle it if I can get a kind of guide.

# Answer
> 0 votes
I would take a look at the Commerce Billy module

Features

```
Thread safe invoice number generation
Three invoice number generation methods: monthly, yearly, infinite
Configurable pre- an suffix values for invoice numbers
Arbitrary start value for invoice number
"invoiced" status on order entity (thus avoiding separate invoice entity)
Automatic or manual invoicing:
    Automatic: order moved to status "invoiced" on order completion
    Manual: admin moves order to status "invoiced" (VBO possible, Rules components already included)
PDF Generation (commerce_billy_pdf module)
Customizable PDF template
Views integration for PDF download link
Handling of credit memos (canceled orders)

```

---
Tags: 7, commerce
---


# Question
Title: How to set width to Media entity image in CKEditor
I have installed Media entity image Module with Lightning Distribution. I can embed image through CKEditor. But how can I select image-styles for Image witch has embed.

Embedded code in CKEditor

```
<drupal-entity data-embed-button="media_browser" data-entity-embed-display="view_mode:media.embedded" data-entity-type="media" data-entity-uuid="869dbc6e-de17-4051-8945-e7acd3237c73"></drupal-entity>

```

Rendered in html

```
<article class="embedded-entity">
  <article data-quickedit-entity-id="media/36" class="media media-image view-mode-embedded" data-quickedit-entity-instance-id="0">
    <div data-quickedit-field-id="media/36/image/ja/embedded" class="field field--name-image field--type-image field--label-hidden field--item">
      <img src="/sites/default/files/images/soap-bubble-1958841_1920.jpg" width="1920" height="1280" alt="" typeof="foaf:Image" class="img-responsive">
    </div>
  </article>
</article>

```

# Answer
I found solution for my self.

1. Move to `/admin/config/content/embed/button/manage/media_browser`
2. Check to **Thumbnail** in Allowed Entity Embed Display plugins section.
3. In node editing select '**Display as Thumbnail**' and you could select Image style.
> 3 votes

# Answer
As of 2.1.6 (8.x-2.1.6) Lightning provides an additional embed plugin for images embedded via CKEditor that allows editors to select an **image style**, alt text, and other settings each time an image is embedded.

By default, the option to select which plugin is used is hidden and the Media image plugin is automatically selected if the media is an image. You can allow editors to override the default via config.

More information available on the Lightning Blog and in the 2.1.6 Release Notes.

**New embed plugin, used by default for image media:**

**Compare to standard embed plugin - still used by other media types:**
> 2 votes

# Answer
Check out the Responsive Image module, as recommend here

Similar question with a well-accepted answer is: How to set Media Styles in Media 7.1.2 / Media 7.2.X?

Hope that is able to help you!
> 1 votes

---
Tags: 8, wysiwyg, media
---


# Question
Title: Seven subtheme not inheriting correct block structure
I am using Drupal 8.

I have subthemed the Seven theme so we can add some minor customisation to the admin theme.

The new theme however is getting all the active theme's blocks thrown into - seemingly - random blocks inside its regions.

I want to create a subtheme which initially is identical to seven and can be activated across several sites with predictable block placement.

I don't want users to be put in a position were they have to go through and manually move/disable blocks after turning on the new admin theme. This is especially true given the clunky nature of adjusting block placement on the admin theme; every time you disable/delete a block and save the change it takes you back to the ACTIVE theme block page rather than the admin one...

Is there a way to do this?

# Answer
You can provide custom block configurations in config/install as with a module. As soon as there is at least one block, Drupal will not add any additional blocks, if there are none, it will copy those from the default theme.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Get current user password before it is overwritten in user form?
I know this is probably unlikely, but I am doing the diligence anyway.

Is there any way to get the current user password from Drupal *before* updating it with a new one on the user form (user editing account info)?

When it is updated, I would like to trigger an API call to a remote system and update the account password there, too (authentication happens on an external system). However, the API call requires the *old* password as well as the new one before it will update it.

Otherwise, I need to lock off any way of updating a password in Drupal from privileged users.

# Answer
> 0 votes
Yes you can. The password only gets hashed when the user entity is saved as part of PasswordItem::preSave().

So you can add a submit handler to the user form, fetch both the old password and the new password (as users are required to enter both usually\*) and do what you want with it.

There are discussions about that being insecure, so it is possible that this will change in the future.

* There are exceptions to this, for example after using a one time login link, users are allowed to change their password without providing the current one.

---
Tags: 8, users
---


# Question
Title: How to Upload images and show in html tables?
Programers. I have some question to ask: (1)I have create a form to upload image file, the files is located in "public://images".This is my buildForm.

```
public function buildForm(array $form, FormStateInterface $form_state) {$form['add_toDb']['foto'] = array(
  '#type' => 'managed_file',
  '#title' => t('foto'),
  '#required'=>TRUE,
  '#upload_location'=>'public://images/',
  '#progress_indicator'=>'throbber',
  '#status'=>FILE_STATUS_PERMANENT,
  '#progress_message'=>'uploading......'
  );
}
public function submitToDbForm(array &$form, FormStateInterface $form_state) {
 $foto = $form_state->getValue('foto');
 //$file= file_load($form_state['value']['foto']);
 $foto_url= file_create_url($foto->uri);
 //$foto_url=$foto->getFileUri();
 $entry = array(
 ...
 'foto' => $foto_url,
 ...
 )
 $return = UpMeetingDbQuery::insert($entry);
 if ($return) {
  drupal_set_message(t('Created entry @entry', array('@entry' => print_r($entry, TRUE))));}}

```

The Question is :$foto\_url is website name,not the path of images;

(2)I want put the files located infomation into database(PostgreSQL).

```
class UpMeetingDbQuery{public static function insert($entry) {
$return_value = NULL;
try {
  $return_value = db_insert('orgwork_upmeeting')
    ->fields($entry)
    ->execute();
}
catch (\Exception $e) {
  drupal_set_message(t('db_insert failed. Message = %message, query= %query', array(
    '%message' => $e->getMessage(),
    '%query' => $e->query_string,
  )
  ), 'error');
}
return $return_value;}}

```

(3)Then, I want the images display in a html table.

```
$headers = UpMeetingFunction::headerTable($header_line);
$results = UpMeetingDbQuery::tableList();

$rows = array();
foreach ($results as $row) {
$rows[] = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $row);
  $options[$row['pid']]=
    array(
    'order_id'            =>  $row['order_id'],
    'name'                =>  $row['name'],
    'foto'                =>  $row['foto'],

```

... Can you help me?

# Answer
> 0 votes
Unless you're building a custom admin form or module, "Upload images and show in html tables" can easily be done using Webform (custom, public forms), File Entity (fieldable files) and Views (custom entity displays).

---
Tags: forms, media, files
---


title: Optgroup in drupal 7 list field

text:
# Question
Title: Optgroup in drupal 7 list field
Now I'm having like

1|City name
2|Another city name
3|Little town name

in values field when creating content type field

How can I wrap some of them in a group that will appear as “optgroup” in html generated?

# Answer
you can use a hook\_FORM\_ID\_alter and then add code like this:

```
$form['FIELDNAME']['#options'] = array (

   'parent1' => array(
      3 => 'child1',
      4 => 'child2',
      5 => 'child3',
    ),
    'parent2' => array(
      8 => 'child1',
      9 => 'child2',
    ),
);

```
> 13 votes

# Answer
using forms api inside hook\_form-alter function you can generate parent-child array then drupal\_render will render dropdown.

```
    <?
function mymodule_form_alter(&$form, &$form_state, $form_id) {

    if ($form['#form_id'] == 'my_nodetype_node_form') {
    $parents = taxonomy_get_tree($vid = 2 /*vocaulary ID*/, $parent = 0, $max_depth = 1);

    foreach ($parents as $term) {
      $options[$term->name] = array();
      $children = taxonomy_get_tree($term->vid, $term->tid);

      foreach ($children as $child) {
        $options[$term->name][$child->tid] = $child->name;
      }
    }
    //echo '<pre>';print_r($options);die;
    $form['the_taxonomy_terms_field']['und']['#options'] = $options;
    }
}
?>

```
> 5 votes

# Answer
There is module for that called as optgroup select. You can try that module.

PS: I am the module maintainer.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to create optgroups from taxonomy terms?
I have taxonomy terms with parent/child hierarchies (1 level deep). On a node edit page the terms are shown in a select box where I can select multiple terms.

What I'm trying to do is convert the parent terms into optgroups so they cannot get selected and the children are nicely grouped. This post shows how to structure the form array.

Basically, the array needs to get arranged like this:

```
$form['field_disc_topic']['und']['#options'] = array (

   'parent1' => array(
    3 => 'child1',
    4 => 'child2',
    5 => 'child3',
    ),
    26 => 'parent2' => array(
    8 => 'child1',
    9 => 'child2',
    ),
);

```

This is the code I started with. A parent term has depth=0, children have depth=1. I can't figure out to how build the array:

```
$tax = taxonomy_get_tree(2);
for ($i = 0; $i < count($tax); ++$i) {
    debug( $tax[$i]->tid);
    debug($tax[$i]->name);
    debug($tax[$i]->depth);
}

```

Can anyone solve this? Or is there an easier way to do this?

# Answer
> 2 votes
Is this what you are looking for: http://drupal.org/node/76500#comment-2193734

I posted the code used in the comment. All props go to Nate Anderson from drupal.org

```
<?php
if (isset($form['taxonomy'][$vid])) {
  $tree = taxonomy_get_tree($vid);
  $parent = "";
  $options = array();
  foreach ($tree as $term) {
    if ($term->depth == 0) {
      $parent = $term->name;
    }
    else {
      if ($term->depth > 1) {
        $options[$parent][$term->tid] = _modulename_spaces($term->depth, '-') . ' ' . $term->name;
      }
      else {
        $options[$parent][$term->tid] = $term->name;
      }
    }
  }
  $form['taxonomy'][$vid]['#options'] = $options;
}

function _modulename_spaces($number, $char = ' ') {
  $output = '';
  for ($i = 0; $i < $number; $i++) {
    $output .= $char;
  }

  return $output;
}
?>

```

# Answer
> 0 votes
There is module for that called as optgroup select. You can try that module.

PS: I am the module maintainer.

---
Tags: 7, forms
---


# Question
Title: How do I stop View/Edit tabs appearing on Taxonomy driven Pages when I am not logged in?
I have a View and Edit button appearing on pages that are Taxonomy driven, even when I am not logged in (and in Incognito Mode).

These pages use the URL `/taxonomy/term/%taxonomy_term` and Views, using info from the URL, are used to display certain data on these pages. For example, with `/cars/honda/civic` 'cars', 'honda' and 'civic' would be used in the Views to show relevant information about Honda Civics.

The issue is that whilst there is no View and Edit buttons appearing on the base `/cars` page, they are appearing on every sub page (`/cars/honda`, `/cars/toyota/camry`, etc).

I can't find anything out of the ordinary in Permissions.

Would any one know what I could do to stop this?

(PS clicking the Edit button whilst not logged in does nothing - just takes you to 403 page).

# Answer
> 0 votes
This was due to someone not surrounding this code with a permissions checker, eg:

```
 if (!user_access('administer nodes')) {
    return;
  }

```

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


# Question
Title: $user-> removeRole('administrator') doesn't remove role
I got php code that is suppouse to remove one role and add a new one to all users in given array. But unfortunatelly it just add new role but doesn't remove one. I tried alphanumeric values as `$rid` and straightforward numeric `$id` but still no effect. I tried putting error\_logs inside loops and it's executed and printed to error\_log.php.

**Here's my code**

```
foreach($users as $usr){
            $user = user_load_by_name($usr);
            $user->addRole('roleToAdd');
            $user->save();
        }
        foreach($users as $usr){
            $user = user_load_by_name($usr);
            $user->removeRole('roleToRemove');
            $user->save();
        }
}

```

**Array**

```
[0] => client1
[1] => client4

```

***#edit***
I think it is worth to mention that `roleToRemove` is assigned to every new user that is registered using registration role module

# FIXED check answers

# Answer
Ok i found an answer. The code is proper and it works. The problem was that I got module installed that assigned a role to new created users. I found out that it not only assign role when someone create new user but also when you was updating any of them. I've patched this bug and i got this hosted on my repo so if anybody needs it. repo
> 3 votes

# Answer
Looking at the Drupal code, it's absolutely clear that `removeRole` requires not the name but the id of the role:

https://github.com/drupal/drupal/blob/8.4.x/core/modules/user/src/Entity/User.php#L188

To test if the error happens in your own code or somewhere else, you could dump `$usr->getRoles()` immediately before and after executing it.
> 1 votes

---
Tags: 8, users
---


# Question
Title: Allow different users to upload pdf to nodes privately
I am trying to build a question answer site in drupal 7. User with teacher role will create a question node, after that users with student role can upload answers in PDF. Different students can upload/attach their respective answers pdf for that question node.

Teacher after evaluating uploaded answer pdf will upload evaluated/corrected pdf for each student. Students can not view other students answers pdf or corrected pdf.

I am thinking to create a question content type and answer content type. Each answer will be linked to specific question node. Answer content type will have two file fields, one to upload answer pdf and another for corrected pdf.

Is my approach correct? Is there any better approach or any module which can help?

# Answer
> 0 votes
Creating two content types "Question" and "Answer" seems to be the right approach per me. These two could be related via entity reference fields. And the storage of the file fields should be "private" for the implementing the access control. I have recently written about private files in my answer you might check out.

---
Tags: files
---


title: Incorrect Drupal 8 Breadcrumbs

text:
# Question
Title: Incorrect Drupal 8 Breadcrumbs
I'm trying to add the page title to the breadcrumbs for each page, unfortunately my breadcrumbs are not updating with current page title. All sibling pages in the menu show the same breadcrumbs.

For example, all these pages will show the same breadcrumbs:

```
Home > About Us > Our Team
Home > About Us > Our Mission
Home > About Us > Another Page

```

Whatever page you visit first, you will get the breadcrumbs for that page on all of the above pages. So if you visit the "Our Team" page first, you will get the "Our Team" breadcrumbs on the "Our Mission" and "Another Page" pages as well. The same happens for 2nd level pages.

So if you visit

```
Home > About Us

```

You will get the About Us breadcrumbs on

```
Home > Services

```

However, you will not get the Home \> About Us\> Our Team breadcrumbs on

```
Home > Services > Service A

```

I have this code in my .theme file:

```
function themename_preprocess_breadcrumb(&$variables){
   if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
       $variables['breadcrumb'][] = array(
                 'text' => $node->getTitle(),
                     'url' => $node->URL()
                   );
   }
}

```

And this for my breadcrumbs template:

```
{% if breadcrumb %}
  <nav class="breadcrumb" role="navigation" aria-labelledby="system-breadcrumb">
    <h2 id="system-breadcrumb" class="visually-hidden">{{ 'Breadcrumb'|t }}</h2>
    <ol>
    {% for item in breadcrumb %}
      <li>
        {% if item.url %}
          <a href="{{ item.url }}">{{ item.text }}</a>
        {% else %}
          {{ item.text }}
        {% endif %}
      </li>
    {% endfor %}
    </ol>
  </nav>
{% endif %}

```

I'm guessing it's some sort of caching issue, as it seems to happen per-session (different users will get stuck with different breadcrumbs depending on which pages they visit first).

Anyone know why this may be happening?

# Answer
I ran into the same issue

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

```
function my_theme_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    /** @var \Drupal\node\NodeInterface $node */
    $variables['breadcrumb'][] = [
      'text' => $node->getTitle(),
      'url' => $node->toUrl(),
    ];
    $variables['#cache']['contexts'][] = 'url';
    $variables['#cache']['contexts'][] = 'session';
    $variables['#cache']['contexts'][] = 'user';
  }
}

```

So:

```
$variables['#cache']['contexts'][] = 'session';
$variables['#cache']['contexts'][] = 'user';
$variables['#cache']['contexts'][] = 'url';

```

did the trick for me.
> 1 votes

---
Tags: breadcrumbs
---


title: Drupal 8 user_filter_form

text:
# Question
Title: Drupal 8 user_filter_form
In drupal 7 i used this hook to implement user filter form (People-\>Filter). This hook doesn't work in drupal 8. Any suggestions?

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function cl_form_user_filter_form_alter(&$form, &$form_state, $form_id) {
  //code here
}

```

Well, i added this function to my module, but no results at all. Am i doing something wrong?

```
function cl_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
{
  $form['actions']['find_users']  = array(
          '#type' => 'submit',
          '#value' => t('Check for users'),
          '#submit' => array('cl_find_users'),
        );
}

```

# Answer
> 2 votes
The form "user\_filter\_form" you are trying to alter doesn't exist. In D8 */admin/people* is a view. You can configure the view including the exposed filter here:

*/admin/structure/views/view/user\_admin\_people*

You can still list peoples without Views. When you disable `user_admin people` the user module displays a basic entity list, but this doesn't contain a filter form anymore like it did in D7. Probably not many will notice, because D8 enables the admin views for content and people by default.

# Answer
> 1 votes
This hook still works check the documentation.

Use \Drupal\Core\Form\FormStateInterface $form\_state instead of &$form\_state, make sure your module is enabled and clear your cache.

---
Tags: forms, hooks
---


title: How can I add security questions?

text:
# Question
Title: How can I add security questions?
I need to add security questions while user creating his account in Drupal 8. I need to use those security questions to retrieve his password, when user forgets his password.

Any suggestions ?

# Answer
> 0 votes
Well at this time you have 2 modules but only for Drupal 7:

Security Questions

> Security Questions provides administrator configurable challenge questions for use during the log in and password reset processes. Think of it like most bank website logins.

Password reset

> The password\_reset module allows for passwords to be reset without involving e-mail addresses through the use of security questions.

There is not a 8.x branch at this time, so your best option is study the code and migrate one of them.

---
Tags: 8
---


title: How to add a second title to a view?

text:
# Question
Title: How to add a second title to a view?
I have a list ordered on a specific field. The value of this field contains yes/no.

So the list first displays all rows with yes. After that all rows with no are displayed.

I would like to display a second title before all rows with no. How to do this?

# Answer
make 2 views, first view (main view) with "yes" filter. second with "no" filter, then in first view add a footer (Global: View area), place there your second view, on each view set your title as needed. you can also pass parameters in view settings.
> 1 votes

# Answer
It depends a bit on how you have defined the yes/no field. If it is a boolean field, you can use the grouping function of views. This grouping functionality allows you group content with a shared value, which will be displayed as a header.

So you add your field to the view (optionally exclude it from display to hide it from each row), then under format settings (top left of the views config page) enable grouping for this field. You now have 2 sub-headings in your view showing something like ON and OFF.

For boolean fields you can override these values with custom values (not sure about other option fields):

Resulting in the following view:
> 0 votes

---
Tags: 7, views
---


# Question
Title: Eliminate access to specific user based on url, uid and role
I'm using D8 and I have a panel page which has as parameter in the URL the uid (mysite/uid). In this page, are loaded different nodes and forms. What I want to do is to eliminate the access only to this user and the admin. It is not a node of a content type so as I can use the existing permissions (edit your own page).

Any idea how to implement this?

I was thinking to use something, maybe hook(?), triggered every time the user tries to access that page and doing some checks like the url and the uid and if the user is not admin or doesn't have the correct uid, throw an AccessDeniedHttpException();

# Answer
> 1 votes
I don't understand what you want to do specific to the panels page. In general you are looking for some kind of hook triggered every time a user visits a page. In D8 every page is connected to a route. You have to implement an access check on this route, see the documentation Access checking on routes. You can define the access check when you create a route or if you have an existing route from another module you can alter the route definition, see for this the next chapter in the documentation Altering existing routes

# Answer
> 0 votes
add a variant, not panel variant, make it with a http response, do a permanent 301 redirect to whatever you want, in conditions set user role, user id, and/or some url, it's simple, straight and easy. no code is needed.

---
Tags: 8, users
---


title: Alter message status per content type

text:
# Question
Title: Alter message status per content type
After hours trying to figure it out, no way ! What am I doing wrong ?

```
function alter_appointment_message_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="appointment_request")
     {
       drupal_get_messages('status'); // Flush default simplenews status message
       drupal_set_message(t('An appointment has been requested'), 'status');
     }
}

```

# Answer
I suppose you want to show a message after submitting the form. (But as Pierre commented, please be clear in what you want and do not make us assume things.) `hook_form_alter()` works during the building of the form. Your code probably works, but there is no message generated yet.

Instead, use `hook_form_alter` to add a new submit callback and place your code in there. Somewhat like this:

```
function alter_appointment_message_form_node_form_alter(&$form,&$form_state,$form_id)
{
  $form['#submit'][] = 'alter_appointment_message_post_submit';
}

/**
 * Custom submit callback.
 */
function alter_appointment_message_post_submit($form, &$form_state) {
 if($form['#node']->type == "appointment_request") {
   drupal_get_messages('status'); // Flush default simplenews status message
   drupal_set_message(t('An appointment has been requested'), 'status');
 }
}

```
> 0 votes

# Answer
In fact, I am adding another answer which is probably easier and closer to what you want.

Use hook\_node\_insert() instead. That only runs after saving a new node, and also runs after the node has been created and the creation message is defined. You only need:

```
/**
 * Implements hook_node_insert().
 */
function alter_appointment_message_node_insert($node) {
 if($node->type == "appointment_request") {
   drupal_get_messages('status'); // Flush default simplenews status message
   drupal_set_message(t('An appointment has been requested'), 'status');
 }
}

```
> 0 votes

# Answer
there is a module (D7) for that Custom Submit Messages module, from module page:

> Allows users to set custom submit messages for different node types via the Drupal UI. So, rather than being stuck with "Page title has been saved", "Page title has been updated" and "Page title has been deleted" the user can set custom submit messages. In addition to this, CSM allows you to change the title of the node creation page. CSM allows both of these things to be set separately for each language your Drupal site is running in, and for whatever user roles are defined on your site.
> 0 votes

---
Tags: 7, status-messages
---


title: Unresolved dependency File Entity error

text:
# Question
Title: Unresolved dependency File Entity error
I'm trying to run a serious of updates on Drupal.

However, I'm seeing to be running into the following error:

Unresolved dependency File Entity (Version \>7.x-2.0 required) Media requires this module and version. Currently using File Entity version 2.0-beta2

Where would the directory structure be so I can update the file entity and do the updates.

# Answer
Modules are typically found in sites/site\_name/module. That's often sites/default/modules.

If your site was installed by a non-standard installation profile, they could also be at /profiles/profile\_name/modules, or somewhere else under the profile folder, instead.

To find it quickly, run this from your web root:

```
find . -name file_entity.info

```
> 0 votes

---
Tags: 7, files, media
---


title: Preview is not showing after upload

text:
# Question
Title: Preview is not showing after upload
When i am trying to upload image as a Authenticate user, After upload i am not able to see preview. fields got disappear fully.

If i try to do as a admin, i am able to see that.

Any suggestions?

# Answer
Could be that you have private file setting turned on and have not given permission to authenticated users to see an uploaded field.

But the commenters above are correct, there are literally a dozen or more ways a field may not display an image. A few that come to mind:

* Images styles aren't writeable
* A preprocess function has a weird permission it's checking
* .htaccess or server settings is screwing up the image headers
* the path is getting rewritten because of a path alias
* Some access module is being wonky
* The access permissions are out of date and need to be flushed
* You have a field-level access module preventing authenticated users from seeing the image field
* You are using some display module that is tweaking your template or display mode based on permissions
* The views module is tweaking your field availability
* etc
> 0 votes

---
Tags: 7, views, theming, media, files
---


title: Entity select Dropdown

text:
# Question
Title: Entity select Dropdown
I'm working on a Drupal 8 view that is going to be a page.

How can I make an exposed entity filter a dropdown? The entity is not a content type, but rather a custom entity with it's own module.

I can't seem to find any documentation about it.

# Answer
Views on Drupal 8 are slightly different, but you might consider this answer (given for Exposed filters with dropdown selections), which gives you a quick module way of creating a custom node-based exposed filter drop down for a Drupal 7 view. This is essentially what I would suggest for your use case.
> 0 votes

---
Tags: entities, views
---


# Question
Title: Change / Set Node Reference field in hook_form_alter
I am trying to set the value for an existing Node Reference drop-down field in a content type via hook\_form\_alter as part of an AJAX call. The form needs to set values based on a selection, which is does correctly for dozens of fields, but I can't get or find the array structure to change/set the value for a Node Reference field. I've looked around and tried every permutation I can find, including dozens of guesses at what the array structure should look like without any success. Any help would be appreciated.

# Answer
> 0 votes
With Clive's help, I was able to figure out the array structure I needed. To set the node ID for a Node Reference field (References Module) in hook\_form\_alter, this structure worked for me:

```
$form['field_name'][LANGUAGE_NONE]['#value'][0] = {node id}

```

---
Tags: 7, hooks
---


# Question
Title: Make a field state change depending on the moderation state field
I am trying to use the states to change another field depending on the moderation state, I tried this, but didn't catch it.

```
$form['schedule_publish_date'] ['#states'] =  array(
 'invisible' => array(
  ':input[name="moderation_state"]' => array('value' =>"published"),
 ),

```

I'm not sure what the correct field name of the moderation state is, this is the source code `

 Moderation state
 <select data-drupal-selector="edit-moderation-state-0" aria-describedby="edit-moderation-state-0--description" id="edit-moderation-state-0" name="moderation_state[0]" class="form-select"><option value="draft" selected="selected">Draft</option><option value="needs_review">Needs Review</option><option value="approved_to_be_published">Approved to be published</option><option value="published">Published</option></select>

 The moderation state of this piece of content.

`

# Answer
Drupal API: function drupal\_process\_states

Example A where the source fieldtype is a textfield

```
$form['moderation_state'] = [
  '#type'  => 'textfield',
  '#title' => ('Some title'),
];

$form['schedule_publish_date'] = [
  '#type'   => 'textfield',
  '#title'  => ('Invisible if ...'),
  '#states' => ['invisible' => [':input[name="moderation_state"]' => ['value' => "published"],],],
];

```

Example B where the source fieldtype is a select-field

```
$form['moderation_state'] = array(
  '#type'          => 'select',
  '#title'         => t('Some title'),
  '#options'       => array('unpublished'=>'unpublished', 'published'=>'published'),
  '#default_value' => 0,
);

$form['schedule_publish_date'] = [
  '#type'   => 'textfield',
  '#title'  => ('Invisible if ...'),
  '#states' => ['invisible' => [':input[name="moderation_state"]' => ['value' => "published"],],],
];

```
> 1 votes

---
Tags: 8
---


title: DUAL table query

text:
# Question
Title: DUAL table query
How do I construct the following query with DB API (so it's database engine independent):

```
SELECT 1 FROM DUAL

```

This example is for MySQL. I believe the Postgres version is

```
SELECT 1

```

# Answer
You can try setting dual as the alias instead of the table.

```
$query = db_select(NULL, 'dual');
$query->addExpression('1');

```
> 0 votes

---
Tags: database
---


# Question
Title: Is there a way to serve a specific node for certain paths?
I'm using Pantheon and there doesn't seem to be a way to update nginx/apache config.

One of my templates is actually a single page app, and I'd like to tell Drupal to serve /node/1 for a couple of URIs.

Get the current path alias or path? shows how I am able to get the current path in the .theme file.

Is there a way to serve a specific node for certain paths?

# Answer
> 1 votes
Core has URL aliasing built in, and having multiple aliases for a single path is supported.

You can manage these at /admin/config/search/path (assuming you have the core Path module enabled).

---
Tags: 8
---