# Question
Title: How do I actually change the site name on a localized site?
Even after changing the settings in `/admin/config/system/site-information`, the page title still contains "Drupal".

All external examinations of the site configuration (config table and exported files) show the new name.

I examined the function `template_preprocess_html()` in `theme.inc` (where the configuration value is supposed to be loaded and entered in the theme variables), and inserted the following var\_dumps:

```
var_dump(\Drupal::config('system.site')->getRawData()['name']);
var_dump(\Drupal::config('system.site')->get('name'));
var_dump(\Drupal::config('system.site')->getOriginal('name'));

```

The resulting output is `string(12) "My Site Name" string(6) "Drupal" string(6) "Drupal"`.

The configuration value isn't overridden anywhere in the site's settings files either. All caches are cleared.

Why is `->get('name')` returning the wrong value even though `->getRawData()` contains the correct one?

Edit: I should probably add that this is a site with a non-English default language. That seems to be the cause of nearly all the configuration-related core bugs. However, the langcode of the `sytem.site` configuration entity is correctly set.

Edit: More digging reveals that the language module is indeed responsible for overriding the configured name with the default name.

Edit3: There doesn't appear to be a way to set the localized site information without editing the configuration externally. I exported it, deleted the file `language/de/system.site.yml` and re-imported, which fixed it. (In the production site, importing didn't remove the deleted configuration entity; I had to delete the language.de/system.site record from the config table directly.)

# Answer
The key to translating the configuration entities and objects is the core module `config_translation` (Configuration Translation).

This provides extra routes for every form that edits site settings or config entities, which allow editing the translations of translation-enabled config strings.
> 0 votes

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


# Question
Title: Node ID and node title in panels page URL
I would like to set up Panels page URL with this pattern: `my-site/[node:nid]/[node:title]` (i.e. `my-site/34/node-34-title`).

I don't exactly understand how the Panels page URL setting works with arguments. I can set up the path to `my-site/%nid/%title` but how can I set it up so that `%nid = [node:nid]` and `%title = [node:title]`?

**My questions:**

1. How do I configure Panels page to do that?
2. Panels panes are populated with Views field. Is there anything to do in views to get these arguments?
3. How can I get transliterated node titles, using Pathauto or Transliterate?

Thanks!

# Answer
Don't try to change the url with panel page manager:

The path pattern is a way to target some page by there route.

1 - If you want to modify the url pattern, use instead the Pathauto pattern tool with Token. ex: /\[node:title\].

Once you build your pattern, it will create some alias every time you create a node, but the internal url is still /node/%node, so you have to use this one to target the nodes pages in the panel configuration.

2- Then, if you need to use the node title in a panel region, you can create a block view with title, and add a the contextual filter on the ID field, by taking is value frome the url. https://duckduckgo.com/?q=drupal+8+add+contextual+filter&ia=web

3- If you build a pattern like in 1 - with pathauto and token - the resulting alias will be a transliteration of the node title.
> 2 votes

---
Tags: panels
---


# Question
Title: How do I get Drupal to 'discover' a new layout .tpl?
I wanted to make a slight variation of a .tpl layout a plugin uses. To do that I simply when into the plugins file structure and duplicated one of its layout folders and renamed the files within (.css, .tpl and .inc). I then made the changes to the .tpl file.

In the .inc file I find:

```
$plugin = [
  'title' => t('Two Col 50/50'),
  'category' => t('Foundation'),
  'icon' => 'icon.png',
  'theme' => 'foundation_twocol_50_50',
  'admin css' => 'foundation-twocol-50-50.css',
  'regions' => [
    'left' => t('Left'),
    'right' => t('Right'),
  ],
];

```

All I did here was alter these names slightly to:

```
   $plugin = [
      'title' => t('Two Col 70/30'),
      'category' => t('Foundation'),
      'icon' => 'icon.png',
      'theme' => 'foundation_twocol_70_30',
      'admin css' => 'foundation-twocol-70-30.css',
      'regions' => [
        'left' => t('Left'),
        'right' => t('Right'),
      ],
    ];

```

I then refreshed my cache and theme registry, but the new 70/30 option does not appear when I go to swap layout for the mini-panel I'm working on.

Is there something I must do to 'tell' drupal this new layout exists?

# Answer
> 0 votes
I assume this is a Panels layout and Drupal won't discover it. You have to manually add it to the theme's .info file like this:

plugins\[panels\]\[layouts\] = your\_new\_layout\_name

---
Tags: 7, theming
---


# Question
Title: Should we use Drupal Commerce for a real estate site?
we are about to build a real estate website for a property agency. The site allows visitors to look for apartment for rent/sale.

Property search is actually the first main functionality. Users can search real estate with its attributes such as: price, land area, building area, number of room, facilities, etc. Second main functionality is they can also filter the property list (search result), sort or paginate it.

The visitors can make a contact too, just a simple form with anonymous user information and an ID of real\_estate content type maybe. Users don't have to login to contact.

The following features is not needed: User authentication, Checkout Progress, Payment, Cart, Order, Comment, Discount, Shipping, Taxing.

**We wonder if we can use Drupal Commerce to get quickly some out-of-the-box features (advanced search, filterable/sortable list) or it's better to build things from scratch.**

PS: We've found "A Real Estate Website Using Drupal" but we still wonder if the Drupal RETS Real Estate Framework (dRealty) module can fulfill our requirements and if the first answer is still consistent as it has 6 years old.

# Answer
I would go from scratch, it's so easy to to make the advanced search and filter/sortable lists .. commerce without distribution needs the same work anyway .. if you go with kickstart, you'll will have a massive overhead.

> dRealty seems very active and up to date for me - i would give this a try !

I found this real estate distribution, maybe check it out -- there's not much information about it .. https://www.drupal.org/project/property
> 1 votes

# Answer
I think you should definitely consider Drupal Commerce or Commerce Kickstart for this, because it seems to have everything you're looking for.

About the facilities you don't need, like "*Checkout, Payment, Discount, Shipping, Taxing, etc*": that's a matter of NOT enabling the corresponding modules you get with it.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Custom module not showing up in module list
I have been following this tutorial http://www.wdtutorials.com/drupal/module-development/how-to-create-module-1-basics-drupal-tutorial to create a custom module.

I created 2 files in my sites\all\modules\own\custom\_module directory

1. irish\_rail.info with the following:

name = Custom

description = Irish Rail API

core = 7.x

2. irish\_rail.module with just an opening php tag

\< ?php

I have been searching for the answer for a long time and nothing.

I cleared the cache. I checked if there is another .module file.

And the module still won't show up in my module list.

Is there anything else I can try. Is there something I'm doing wrong?

# Answer
> 0 votes
I fixed the problem.

It turned out that when I was naming the files I was naming them custom.info and custom.module but wasn't giving them the proper extensions. They were still .txt extensions.

Something very small!

Thanks for the help though.

---
Tags: 7
---


title: How can I render my form?

text:
# Question
Title: How can I render my form?
I create a module and I create a template for that .

I use this code in mymodule.module :

```
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'moduletheme' => [
      'render element' => 'form',
      'variables' => array('test_var' => NULL),
    ],
  ];
}

```

And I use this code in mymodule/src/Form/MymoduleForm.php :

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $forms['#theme'] = [
        '#theme' => 'moduletheme',
        '#test_var' => $this->t('Test Value'),
    ];
    return $forms;
}

```

And I use this code in mymodule/templates/moduletheme.html.twig :

```
<p>Test twig template!</p>
<p>test_var: {{ test_var }}</p>

```

But when I clear cache and refresh my module page , I just see :

```
Test twig template!
test_var:

```

How can I fix this problem in drupal 8 ?

# Answer
Remove the '#' from the form field key and clear cache. *$forms\['theme'\]* instead of *$forms\['#theme'\]*.

```
$forms['theme'] = [
    '#theme' => 'moduletheme',
    '#test_var' => $this->t('Test Value'),
];

```
> 0 votes

---
Tags: 8
---


# Question
Title: How to add classes to menu items in navigation twig template
I'd like to add classes to `<a>`-tags for menu items that have a submenu.

Currently this is my code, I can only add classes to `<li>` elements:

```
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('nav navbar-nav navbar-right') }}>
    {% else %}
      <ul class="dropdown-menu panel-collapse collapse">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded dropdown panel simple-dropdown',
          item.is_collapsed ? 'collapsed',
          item.in_active_trail ? 'active',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

# Answer
There are two ways to add attributes to the `<a>` tag of a link, in the options of the url object or in `#attributes` of a link render element.

As I don't know how you can achieve the first in twig and to avoid an extra preprocess hook to do this in php, here is how you can replace the link function with a link render element in twig:

```
{% for item in items %}
  <li{{ item.attributes }}>

    {% set link = {
      '#type':       'link',
      '#url':        item.url,
      '#title':      item.title,
      '#attributes': { class: ['link-class1', 'link-class2'] },
    } %}

    {{ link }}

    {% if item.below %}
      {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}

  </li>
{% endfor %}

```

**Edit:**

I just found out, that in contrast to the php function `l()` the twig function `link()` does provide a 3rd parameter to add attributes, so this is a much easier solution:

```
{% for item in items %}
  <li{{ item.attributes }}>

    {{ link(item.title, item.url, { class: ['link-class1', 'link-class2'] }) }}

    {% if item.below %}
      {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}

  </li>
{% endfor %}

```
> 4 votes

---
Tags: theming, 8, navigation
---


# Question
Title: How can I place an entity content field value in header markup?
I need to put an image field url into the header meta tag (open graph image). The obvious ways to put things in the header are in html.html.twig, hook\_preprocess\_html, and hook\_page\_attachments. But in any of these, how do I access the content to be rendered in order to see what the image url is?

And this is complicated by the fact that the rendered entity is a commerce product, while the desired image field is on the product\_variation entity, with drupal commerce rendering the desired variation using a query string and an EntityViewBulder::alterBuild.

This means I can't use e.g. $product = \Drupal::routeMatch()-\>getParameter('commerce\_product') because we wouldn't know what variation is being shown.

Once the variation is to be had, it would be fine to get the delta 0 image from the image field on the variation.

# Answer
The essence of the problem is how to move a value from the field template preprocess to the html theme preprocess. I did this by using a one-off static variable function, provided by a helper module:

```
/*
 * Generates a static variable in the scope of the page request
 * to set instantiate like
 *  $var = &p2p_helpers_ogimage_function(); $var = 'my value';
 *    to read the var,
 *   instantiate without.
 */
function &p2p_helpers_ogimage_function() {
  $var = &drupal_static(__FUNCTION__);
 if (!isset($var)) {
    // generate contents of static variable
    $var = NULL;
  }
  return $var;
}

```

Then I can do the rest in the THEME.theme file.

In the field template preprocess hook I can do this:

```
/**
 * Prepares variables for blazy.html.twig templates.
 */
function p2p_bootstrap_preprocess_blazy(&$variables) {
  $url = p2p_helpers_ogimage_function();
  if (!$url) {
    $url = &p2p_helpers_ogimage_function();
    $url = $variables['url'];
  }
  ...

```

This will fill check if the variable is already set, so it only sets it once for the first image in the field.

Then in hook\_preprocess\_html:

```
$url = p2p_helpers_ogimage_function();
if ($url) {
  $ogimage = [
    '#tag' => 'meta',
    '#attributes' => [
      'property' => 'og:image:secure_url',
      'content' => $url,
    ],
  ];

  $variables['page']['#attached']['html_head'][] = [$ogimage, 'og:image'];
}

```

Does anyone see any better way to do this?
> 0 votes

---
Tags: theming, 8, commerce
---


title: switch project to dev mode

text:
# Question
Title: switch project to dev mode
I faced to problem trying drupal console:

1) In documentation written (https://www.drupal.org/docs/8/theming/twig/debugging-compiled-twig-templates):

```
drupal site:mode de

```

But I haven't that command in a list of other commands when I attempt drupal list in a project root

2) Then when I put in settings.php or settings.local.php this:

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

```

I got Error...

```
The website encountered an unexpected error. Please try again later.
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "cache.backend.null". Did you mean one of these: "cache.backend.apcu", "cache.backend.php", "cache.backend.memory"? in Drupal\Component\DependencyInjection\Container->get() (line 157 of core/lib/Drupal/Component/DependencyInjection/Container.php).
Drupal\Component\DependencyInjection\Container->get('cache.backend.null') (Line: 83)
Drupal\Core\Cache\CacheFactory->get('render')
call_user_func_array(Array, Array) (Line: 254)
Drupal\Component\DependencyInjection\Container->createService(Array, 'cache.render') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('cache.render', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.page_cache') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_middleware.page_cache', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.reverse_proxy') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_middleware.reverse_proxy', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.negotiation') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_middleware.negotiation', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_kernel') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_kernel') (Line: 1320)
Drupal\Core\DrupalKernel->getHttpKernel() (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

If someone resolved it please share)

# Answer
> 2 votes
1 It appears that there is no site:mode command in the latest drupal console (1.0.0-rc16), but instead site:maintenance (sma) (on/off) is available. Maybe they ditched site:mode at some point because site:maintenance made more sense in Drupal context.

2 Make sure you have this code in development.services.yml:

```
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

```

---
Tags: debugging
---


# Question
Title: Content restrictions for logged in user with specific role
We use a D7 site to market and sell products B2B. We have a special client that only wants to see a small selection of products when logged in. I can of course give them a special role and allow them permission to view content that others cannot see. But when it comes to hiding ALL the other products on the site, I'm not sure how to think... it means giving them more restrictions when logged in with a special user role.

Normally you get more access when logged in and given a special role, compared to not being logged in at all. But in this case I need to do the opposite.

Any ideas?

# Answer
> 0 votes
This looks like a perfect use-case for hook\_node\_access with $op='view'. You check if the user is 'special' and apply your logic to approve/deny the view. You could have a new role for this, or a new field on the product nodes, or some other idea. It very much depends on what your logic is there.

---
Tags: 7, users
---


# Question
Title: How to uncheck a checkbox programmatically?
How can I uncheck a checkbox programmatically in Drupal 8. I need this in an ajax call, when an option is selected, a checkbox must be unchecked

# Answer
After a lot of trial and error, I found out:

Imagine a checkbox with name 'Coffee' has one option: \['Y' =\> 'I want an espresso'\].

To uncheck this selection, enter: $form\['Coffee'\]\['Y'\]\[#checked\]=false
> 2 votes

---
Tags: 8, forms
---


# Question
Title: Use a different theme when your site is being embedded in an iframe
We have the requirement to make a trimmed back version of the website, for use for other websites to embed via an iframe. For instance, there will be no left navigation, no global navigation, and all elements will be re-flowed to fit in a smaller width.

I would like to do this with a separate theme (more than likely the iframed theme would be a sub theme of the main site theme).

What is the best way to ensure the site loads the alternative theme when it has been embedded (and switch back to the main theme when it is not)?

A thought I had:

* Use a different sub-domain e.g. `www.example.com` and `iframe.example.com`

I am after what you think the best way to solve this would be

# Answer
> 6 votes
Create a custom module and put this lines there:

```
/** Implementation of hook_init **/
function yourmodule_init(&$vars) {

  //here put any condition to you want, for example a domain
  $url = url("<front>", array('absolute' => TRUE));
  if( $url == "http://mydomainiframe.com") {
    global $custom_theme;
    $custom_theme = 'new-theme'; //setting a new theme for this domain.
    init_theme();
  }
}

```

Also you can avoid create a whole new theme creating only a new page.tpl.php and using it.

```
/** preprocess_page **/
function your_module_preprocess_page(&$vars) {

  //here put any condition to you want, for example a domain
  $url = url("<front>", array('absolute' => TRUE));
  if( $url == "http://mydomainiframe.com") {
    $vars['template_file'] = 'page-iframe'; //setting a new page template
  }
}

```

And the page-iframe.tpl.php will be used instead of the page.tpl.php of your theme, in this way you can reuse things to you have in your actual theme.

# Answer
> 3 votes
Domain Access *project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.*
\- this module commonly used for supporting multi-domains, and it can switch themes depend on current domain.

# Answer
> 1 votes
ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

```
individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
...

```

And unlike other theme switching modules, ThemeKey should play well with internal and external page caches, like Boost or Varnish, even for anonymous users.

---
Tags: 6, theming
---


# Question
Title: How to alter the name of downloadable excel sheet of webform
**Issue:**

When I click on the link of`webform` **Download** as shown in below screenshot the default name of excel sheet before save to local disk appears like `localhost_worklog.xlsx` but I want something like `localhost_worklog_02172017.xslx` which is appended with `_<current time>`.

**SCREENSHOT:**

**EDIT:** After using **iLLin's** answer

**Problem:** How can I alter the name of `localhost_worklog.xlsx` before save?

I am using `drupal 7.53`.

# Answer
The only way to do this is to change the `$node->title` on the loaded object for the webform. That filename uses that title, so I am assuming you have a webform title of "Localhost Worklog".

The problem with that is you only want to change the node title, when you are downloading the webform (or atleast running through that process).

You have two options (I think). You could implement a `hook_entity_load()` function and then check if the URL is

node/%webform\_menu/webform-results/download **or**

node/%webform\_menu/webform-results/download-file

```
function MYMODULE_entity_load($entities, $type) {
  if (arg(2) == 'webform-results' && (arg(3) == 'download' || arg(3) == 'download-file')) {
    foreach ($entities as $entity) {
      $entity->title = $entity->title .'_'. now();
    }
  }
}

```

Docs

The other way I can think of is altering the page callback with a `hook_menu_alter()`, changing the title there and then calling their function to return the form or download file with the updated node object to include the time appended to the title.

## EDIT

From reviewing your update, it seems it's changing the title too soon on that page. So I think you will need a combo approach. Using `hook_entity_load` and `hook_form_alter`. The point is changing that title in the $node object that is passed around for download. So try this.

```
/*
 * Implements hook_entity_load().
 */
function MYMODULE_entity_load($entities, $type) {
  // Change the node title to include the time when downloading.
  if (arg(2) == 'webform-results' && arg(3) == 'download-file') {
    foreach ($entities as $entity) {
      $entity->title = $entity->title .'_'. now();
    }
  }
}

/*
 *  Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == WEBFORM_DOWNLOAD_FORM_ID) {
    // Change the node title that is passed around for download.
    // @TODO: Check to make sure this is correct.
    $form['node']['#value']->title = $form['node']['#value']->title . '_'. now();
  }
}

```
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Problem with drupal $queue->DrupalQueue::get and $queue->createItem
I am updating approx 10000 nodes using hook\_cron\_queue\_info and hook\_cron(), it execute only for 25 nodes. Is there any problem?

```
function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'skip on cron' => FALSE,
  );
  return $queues;
}

function my_module_cron() {
  $contents = lode_update_nodes(); // get node list for updation 10000 nodes.
  $queue = DrupalQueue::get('my_module_batch');
  foreach ($contents as $p_file) {
    $process_data = array(
    // set values for process
    );
    $queue->createItem($process_data);
  }
}

function _my_module_process_queue($arr) {
    // code for updation
    watchdog('update node', 'Custom msg');
}

```

# Answer
You have to add the 'time' key in de function modulename\_cron\_queue\_info() because the default call time for the queues are 15 seconds. In order to update 100000 nodes you need to asign more time, so you have to try adding time until all 100000 nodes are updated:

```
$queues['my_module_batch'] = array(
  'worker callback' => '_my_module_process_queue',
  'skip on cron' => FALSE,
  'time' => 60,
);

```
> 0 votes

---
Tags: cron
---


# Question
Title: Is there a ready made gruntfile available for Drupal Bootstrap Child Theme (SASS)
**This applies to Drupal 7.**

I am fairly new to grunt and can't really make much sense of out of a gruntfile. I've just started with a drupal child theme (which has been created off bootstrap SASS startkit).

Can you point out a readymade grunt file which I can use to watch and compile my scss (output as css) and minify js.

# Answer
```
module.exports = function(grunt) {
grunt.initConfig({
compass: {
 dist: {
    options: {
      sassDir: 'sass',
      cssDir: 'css',
      environment: 'production',
    },
  },
},
watch: {
  css: {
    files: ['sass/*.scss'],
    tasks: ['compass'],
  },
},
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.registerTask('default', ['compass']);
};

```
> 1 votes

# Answer
Not sure if this is a Drupal subtheme, but an alternative is looking into the Drupal Bootstrap theme and checking out the grunt configuration they have.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to automatically create a node for each user and set the user as author of the node?
I have 50 users on my site. I want to create 50 nodes and then set the author of the node to each of my 50 users.

Is there a way to do this using a module or programmatically, rather than having to first create all the 50 nodes and then editing the author fields?

# Answer
### Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to **Create an entity** (of type node). Make sure to use a parameter (of type "integer"), and which you use as the value to be assigned for the "author" of the node to be created. Here is an example of such Rules Component (in Rules export format, if you have the Rules UI enabled you should be able to import it in your own site):

```
{ "rules_create_a_new_node" : {
    "LABEL" : "Create a new node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "uid_of_author" : { "label" : "Uid of the user to be used as author", "type" : "integer" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "uid-of-author" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Node created for user [user-fetched:name]",
            "param_author" : [ "user-fetched" ]
          },
          "PROVIDE" : { "entity_created" : { "node_created" : "Created node" } }
        }
      },
      { "drupal_message" : { "message" : "Node creation completed for user with name \u0022[user-fetched:name]\u0022." } }
    ]
  }
}

```

Some details about the above Rules Component:

* It checks if the user using it, has role "admin" (just to be secure it a bit, feel free to omit that if you don't want that).
* It fetched the info about the user for which the `uid` was entered as a parameter.
* It creates a node of type (machine name) `page` (adapt that to whatever machine name fits for you).
* It shows a Drupal message to confirm the node got created (just for testing, remove it if you don't need it anymore).

After you imported the above Rules component, use the "execute" link in front of this Rules Component to QA-test your component (for which you'll need to enter an appropriate `uid` value for the author you want). After it completes, it'll show an informational Drupal message similar to this one (with Demo.User = the name of the user for which I entered the `uid`):

> Node creation completed for user with name "Demo.User".

### Step 2

Create a view of the group of users for which those nodes should be created. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1. Make sure one of the fields (columns) in your VBO view is the `uid` for each of the (50) users for which you want to create such node.

### Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

PS: no need for custom code ...
> 2 votes

# Answer
You can do that by a drush script looking like this:

```
$users = entity_load('user');
foreach ($users as $user) {
        $node = new stdClass();
        $node->type = 'yourContentType';
        $node->status = 1;
        $node->uid = $user->uid;
        $node->title = $user->name;
        $node->promote = 0;
        $node->sticky = 0;
        $node->language = 'en';
        $node->body = '<p>body</p>';
        node_save($node);
}

```

Here is more info about how to execute it How to execute php script using drush?
> 0 votes

---
Tags: 7, nodes, users
---


# Question
Title: Delete directory from private folder programatically?
I'm using D8, and am writing a cron task to remove old backups from my private files directory. The backups are generated in `private://db_backups/date-of-backups/backup.gz`. The following code is properly deleting the actual backup files, but it is not removing the parent date directory. I am not receiving any errors in the drupal or server logs, so I'm a bit lost as to what's causing the failure.

```
function custom_changes_cron() {
    drupal_set_message(t('Custom cron function has run.'), 'status');
    $private_path = PrivateStream::basePath();
    $interval = strtotime('-430 hours');
    foreach(glob($private_path . '/backup_db/*' , GLOB_ONLYDIR) as $folder) {
        if (filemtime($folder) <= $interval ) {
            $files = glob("$folder/*"); // get all file names
            foreach($files as $file){ // iterate files
              if(is_file($file))
              unlink($file); // delete file
            }

            // Have tried both of the following
            rm_dir($folder);
            drupal_rmdir($folder);
        }
    }
}

```

# Answer
> 3 votes
Note that `glob('*')` ignores all hidden files by default. This means it does not return files that start with a dot (e.g. `.file`). If you want to match those files too, you can use `{,.}*` as the pattern with the `GLOB_BRACE` flag. This will include the special cases `.` and `..` so you need to exclude those by using `{,.}[!.,!..]*`.

So in summary, try the following:

```
$files = glob("$folder/" . '{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);

```

As a sidenote: you mention you tried using `rm_dir`. I assume you mean `rmdir`?

# Answer
> 3 votes
Interesting. Did you try using the following functions? I think one of them should work:

Make sure that PHP has permission to delete the directories. To test this, delete the contents of one of the backup directories manually and then try one of the above functions on it - this will help you understand whether the directory deletion is causing the problem or something else inside the directory.

Alternatively, you can set up a server-side cron in a shell script if you are considering that.

BTW, I notice you are using `drupal_set_message()` \- it will not work from within a cron due to some session-specific reasons. Use `\Drupal::logger('custom')->debug('Description');` \- the message will appear in the `Reports > Recent log messages` menu.

Hope it helps!

---
Tags: 8, cron
---


# Question
Title: Why we need the key property in the Upsert class if it is never used?
I recently tried to use an Upsert query in a table with a composite primary key, but when I go to see the key() method it only allows one parameter and not an array, so we only can only have a singular key:

```
public function key($field) {
  $this->key = $field;

  return $this;
}

```

I just tried to use one key and the query works fine! **How is posible this?** Let see in the core files.

This always will work because if you see the code inside the \__toString() function the key property is never used:

```
public function __toString() {
    // Create a sanitized comment string to prepend to the query.
    $comments = $this->connection->makeComment($this->comments);

    // Default fields are always placed first for consistency.
    $insert_fields = array_merge($this->defaultFields, $this->insertFields);

    $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';

    $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
    $query .= implode(', ', $values);

    // Updating the unique / primary key is not necessary.
    unset($insert_fields[$this->key]);

    $update = [];
    foreach ($insert_fields as $field) {
      $update[] = "$field = VALUES($field)";
    }

    $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);

    return $query;
  }

}

```

Ok, If the key property is never used I will try to made my upsert without it.

```
$upsert = $this->database->upsert('forcontu_node_votes')
        ->fields(['nid', 'uid', 'vote'])
        ->values([
          'nid' => $nid,
          'uid' => $uid,
          'vote' => $node_vote,
        ]);
dpm($upsert . '');
// Using dpm() because dpq() doesn't works with upsert https://www.drupal.org/node/2847155
$upsert->execute();

```

The code will throw an exception because always you need to set the key, if you don't set the key property you will get an exception:

```
protected function preExecute() {
  // Confirm that the user set the unique/primary key of the table.
  if (!$this->key) {
    throw new NoUniqueFieldException('There is no unique field specified.');
  }
...

```

If you put comments in the lines

```
  // if (!$this->key) {
  //  throw new NoUniqueFieldException('There is no unique field specified.');
  //}

```

the code will works fine, and you will see that if you set or not the key property always the query is the same, in my case:

```
INSERT INTO {forcontu_node_votes} (nid, uid, vote) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2) ON DUPLICATE KEY UPDATE nid = VALUES(nid), uid = VALUES(uid), vote = VALUES(vote)

```

So, Why we need the key property in the Upsert class if it is never used?

**Note:** This is just in the mysql and sqlite clases that the key is not used, but in the postgre clases is used (at this moment I don't have postgre to made some test).

***Database Schema:***

```
CREATE TABLE `forcontu_node_votes` (
  `nid` int(11) NOT NULL COMMENT 'Node ID',
  `uid` int(11) NOT NULL COMMENT 'User ID',
  `vote` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1 to 5',
  PRIMARY KEY (`nid`,`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Stores Node votes';

```

***forcontu\_blocks.install:***

```
/**
 * Implements hook_schema().
 */
function forcontu_blocks_schema() {
  $schema['forcontu_node_votes'] = [
    'description' => 'Stores Node votes',
    'fields' => [
      'nid' => [
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'Node ID',
      ],
      'uid' => [
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'User ID',
      ],
      'vote' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => '1 to 5',
      ],
    ],
    'primary key' => ['nid', 'uid'],
  ];
  return $schema;
}

```

# Answer
> 3 votes
You basically said it yourself. The check is there to enforce that Upsert is used in ways that is compatible with all databases, including PostgreSQL, which needs it, as it does not actually support an UPSERT-like operation.

On MySQL, the key doesn't need to be specified as it is only supported on a table with a single unique key anyway:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Query!Upsert.php/class/Upsert/8.2.x

> This class can only be used with a table with a single unique index. Often, this will be the primary key. On such a table this class works like Insert except the rows will be set to the desired values even if the key existed before.

---
Tags: 8, database
---


title: Printing Fields Multiple Times

text:
# Question
Title: Printing Fields Multiple Times
I have a custom template for a node (Photograph) that needs to print a field multiple times for different reasons. You can see an example here: http://history.arvadahistory.org/photograph/elizabeth-lunau-house-52st-and-dover

Where you see in the table "Individual ID", there is supposed to be a field printout, but I had to cut it out so a copy of the field could be printed with priority.

So using the above example, the Individual ID should be printed HF513, but I can't for unknown reasons, place this field in multiple places, and I need it absolutely attached to the "Order Image" button, where the link it loads for the above example is as such: http://history.arvadahistory.org/order-historic-image?edit\[attributes\]\[2\]=HF513

Below is the code I have included in my template, as you can see, the second row, where the initial copy of "Individual ID" is supposed to be printed, I have commented out because if I leave it uncommented, it won't print the field the second time near the bottom with the "Order Image" button.

As a note, I do have a module that provides my fields with a "Do not write drupal standard markup around the field" option so I can print out the individual ID with just the ID to include in my "Order Image" URL.

```
<table width="100%" border="0">
    <tbody>
      <tr>
        <td class="category">Object ID</td>
        <td class="non-title"><?php print render ($content['field_photo_object_id']);?></td>
      </tr>
      <tr>
        <td class="category">Individual ID</td>
        <td class="non-title"><?php /**print render ($content['field_individual_id']);**/?></td>
      </tr>
      <tr>
        <td class="category">Object Name</td>
        <td class="non-title"><?php print render ($content['field_object_name']);?></td>
      </tr>
      <tr>
        <td class="category">Description</td>
        <td class="non-title"><?php print render ($content['body']);?></td>
      </tr>
      <tr>
        <td class="category">Copyright</td>
        <td class="non-title"><?php print render ($content['field_copyright']);?></td>
      </tr>
       <tr>
         <td class="category">Properties & Locations</td>
         <td class="non-title"><?php print render ($content['field_property_references']);?></td>
       </tr>
       <tr>
         <td class="category">People</td>
         <td class="non-title"><?php print render ($content['field_biography_references']);?></td>
       </tr>
       <tr>
        <td class="category">Photograph Category</td>
        <td class="non-title"><?php print render ($content['field_photograph_category']);?></td>
      </tr>
      <tr>
        <td class="category">Collection</td>
        <td class="non-title"><?php print render ($content['field_ahsphotograph_collection']);?></td>
      </tr>
      <tr>
        <td class="category">Photograph Date(s)</td>
        <td class="non-title"><?php print render ($content['field_photograph_date_s_']);?><?php print render ($content['field_date_specific_']);?></td>
      </tr>
      <tr>
        <td class="category">Original Available</td>
        <td class="non-title"><?php print render ($content['field_original_available']);?></td>
      </tr>
      <tr>
        <td class="category">Print Available</td>
        <td class="non-title"><?php print render ($content['field_print_available']);?></td>
      </tr>
      <tr>
        <td class="category">Negative Available</td>
        <td class="non-title"><?php print render ($content['field_negative_available']);?></td>
      </tr>
      <tr>
        <td class="category">Credit Line</td>
        <td class="non-title"><?php print render ($content['field_credit_line']);?></td>
      </tr>
       <tr>
        <td class="category">Tags</td>
        <td class="non-title"><?php print render ($content['field_photograph_tags']);?></td>
      </tr>
      <tr>
        <td><?php print render ($content['field_photo_object_id']);?><?php print render($content['field_photo_object_id']['1'][0]['value']); ?></td>
      <td><a href="http://history.arvadahistory.org/order-historic-image?edit[attributes][2]=<?php print render ($content['field_individual_id']);?>" target="_blank""><img src="http://history.arvadahistory.org/sites/default/files/imageorder_small.gif"></a><img src="http://history.arvadahistory.org/sites/default/files/feedback_small.gif" style="padding-left:50px"></td></tr>
    </tbody>
  </table>

```

--------------------------------------UPDATE-------------- As per the suggestion @rovr138 I have implemented the "tmpField" suggestion, which has worked out. I'll accept his answer tonight if there is nothing else that pops up.

# Answer
A quick fix (since this is live), above table add,

```
<?php
  $tmpField = $content['field_individual_id'];
?>

```

Then the commented field, change it to:

```
    <td class="category">Individual ID</td>
    <td class="non-title"><?php print render ($tmpField); ?></td>

```
> 1 votes

---
Tags: 7, theming, entities
---


title: Convert view route parameter to entity

text:
# Question
Title: Convert view route parameter to entity
**Task:** Create a view with link to it displayed among node tabs (View, Edit, etc.).

**Solution:** Create a view with page display and set its path to "node/%node/foo".

**Issue:** When the page "node/%node/foo" is visited, `\Drupal::routeMatch()->getParameter('node')` returns node ID instead of node object.

Is there a simple way to make it return the node object? (Currently I have to alter the view route and set the parameter type.)

# Answer
> 2 votes
Views doesn't use typed arguments as it doesn't understand them anyway. Why do you need that to work? You can just load it where you need it? And if you have code that relies on that being an object then that code is wrong and will also fail on node/N/revisions for example.

What might work is defining such a page with page\_manager, that will allow to define the right type.. but on the other hand, page manager does not yet support defining local tasks.

---
Tags: views, 8, entities, routes
---


title: Creating content type using views

text:
# Question
Title: Creating content type using views
I created a content type using views called Bars & Restaurants

I want that content type to show under my Bars & Restaurants menu link at the top of my page.

I have changed the path to http://localhost/drupal/barsandrestaurants

and the menu to: menu tab - navigation and it still only shows up on my home page.

Is there a way to display the content type only on my bars and restaurants page?

I want authenticated users to be able to go into the page and add bars and restaurants themselves.

I am very new to drupal so any help will be great!

I want the content that Im adding to be under the Bars & Restaurants page there

# Answer
> 0 votes
**Assuming what you want to do is :**

* Make a content type which authenticated user can add by themselves called **barandrestaurant**.
* Make a view displaying all the **barandrestaurant** content-type.

**First creat a new content type called barandrestaurant** :

1. You should unchecked the "promote to front page" in the content type page :
2. Allow user to add your content type in admin/people/permission --\> find your content type node name (barandrestaurant) and allow authenticated user to create new content.

**Second make a view page filtering your content type barandrestaurant**

3. Go to admin/structure/views/add a new view and fill the form to filter on your content type like that :
4. Specifiy that what you want is a view page and that you want to add a menu link in navigation menu :
5. Add in the header or in the footer (as you want) a "global text area" with a html link to create new barandrestaurant content type page :

```
<div><a href="node/add/barandrestaurant">Add a new bar or restaurant</a></div>

```

This should look like this :

Now you should have a content type called barandrestaurant which can be created by your authenticated users visiting the link http://www.yoursite.com/bar-and-restaurant. The link should be in your navigation menu too.

---
Tags: views
---


# Question
Title: How to override a single function in a core javascript library?
Drupal 8's core comments module has a library "node-new-comments-link" with a file "node-new-comments-link.js".

This contains `Drupal.behaviors.nodeNewCommentsLink = { ... }` which calls another function in the library which in turn calls another function in the library `function render(results) { ... }`.

This render function controls the text used to show how many new comments a node has: `.text(Drupal.formatPlural(results[nodeID].new_comment_count, '1 new comment', '@count new comments'))`

I want to use different text. (I want it just to say 'New' rather than 'x new comments').

I can replace the whole js file or the whole library and that works fine, but it's very heavy handed. It requires me to copy paste lots of complex code I don't need to understand.

Is there a way to override just this one render function?

# Answer
> 2 votes
You can enable interface translation for English in */admin/config/regional/language/edit/en*

\[x\] Enable interface translation to English

and then you are able to change the string you are looking for in *User Interface Translation*.

---
Tags: theming, 8, javascript
---


# Question
Title: Why is the subtheme_style.css not being called?
On a Drupal Commerce Kickstart installation, I have created a subtheme of Omega Kickstart, following the process described here.

Subtheme is saved to: public\_html/sites/all/new\_theme

I kept only two of the \*.css files for customization:

* new\_theme\_style.css
* new-theme-alpha-default.css

I updated the new\_theme.info file as follows:

```
name = New Theme
package = Commerce Kickstart
core = 7.x
screenshot = screenshot.png
base theme = omega_kickstart

```

No changes to the Regions / Theme Settings. Updates to the Optional Stylesheets: ; OPTIONAL STYLESHEETS

```
css[new_theme_style.css][name] = New theme global style.
css[new_theme_style.css][description] = This file holds all the globally active custom CSS of Monkey theme.
css[new_theme_style.css][options][weight] = 12
settings[alpha_css][new_theme_style.css] = 'new_theme_style.css'

```

Changes made in new-theme-alpha-default.css are working, but changes made to new\_theme\_style.css are not showing. When I use "Inspect element" tools, I see that global.css is called instead.

Is this an issue with the weight I am assigning here? I copied the css over from another subtheme that is working. I cannot pinpoint the problem...but know it is likely a noobie mistake.

Thx - keb

# Answer
> 0 votes
Turns out, I had everything set up correctly, but hadn't toggled "ON" the style sheet.

1. Navigate to: Site settings \>\> Appearance \>\> Settings \>\> Toggle Styles
2. Click "ON" checkbox next to New Theme global style. (all) - new\_theme\_style.css

I slept on it and woke early in the morning, remembering that not only do you need to enable your theme, you need to turn on the style sheet.

---
Tags: theming
---


# Question
Title: How to debug a Commerce value in Rules if field is not exposed?
I use Drupal Commerce with Commerce Credits module to let users buy credits which later can be used to submit content.

The module has support for Rules but I can't get a very simple condition to work. The problem is that 'Entity has credits' rule always returns 0 even if my users have credits:

I tried to debug the amount of user credits but without any results:

* Rules evaluation log shows me that comparison to 0 always returns true but to different values always false, independently if user has credits or no. Before that I check if entity is of type node.

+ Checking if entity is of type *commerce\_credits* and using 'Entity has credits' doesn't give me any result.
* Devel debug using action "Debug value" to show credits for user fails for *node:author* and *site:current-user* as no reference to credits is shown.
* I tried also to get access to *commerce\_credits* by "Fetch entity by id/property", but couldn't figure out what id/property to define.

Looking at the code of Commerce Credits module it looks like credits get saved to an entity called *commerce\_credits*. But I can't figure out how to use this token.

Any other way to debug Rules and find the credits value related to a user?

# Answer
Looks like you did pretty much everything you can do to "debug" a rule that doesn't seem to do what you want, so I can't give you any other hints to the "how to debug"-part of your questions. ***But...*** I may have a solution to get around the actual problem ...

Have a look at the issue `"After updating existing content" runs before content is saved`, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which IMO is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your **Rules Conditions and -Actions** in a Rules Component, so that after your **First Rules Action** you "schedule the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs).

BTW, there are also scenarios where it is sufficient to just execute the Rules Component (containing the equivalent of your "subsequent Rules Action"), instead of using the Rules Scheduler to schedule its execution.

**Update**: as per geraldo's comment below this answer, the actual solution to the question here seems to be as described in comment nr 8 of support issue # 2502703, and which is like so:

> The problem is line 317 in commerce\_credits.rules.inc. Using `count($credits->credits)` always returns `1`. Everything works fine when changing it to:
>
> ```
>  if ($credits->credits >= $credit_number) {
>
> ```
> 1 votes

---
Tags: 7, commerce, entities, rules, debugging
---


# Question
Title: How to set up component on another site?
I've been tasked with setting up a simple gallery component on a global site.

The component exists and works on a sub-site, but I want to move it to the parent site and ensure it's available globally.

I found the component's files in the sub-site and moved them to the same directory in the global, parent site.

The good news is that I can now see the component when I go to add it to a panel. But I can't access it to set it up. Clicking on it does nothing.

Does anyone know if there are any other steps I need to take to do this?

# Answer
Here's what I did:

1. Transferred component files from one site to the other to the same directory.
2. In the components.module file (which for me was up a couple of levels from the place I dropped the component files) paste in any hooks the correspond to the component (my component was an image gallery which used Masonry, so there were some hooks there).
3. Ensure the render function is relating to the right theme. See my other issue here for more info.
4. Clear caches, rebuild registry.

It's not the best response, but I hope it helps someone.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Complete checkout for all orders Drupal commerce
I am working with Drupal Commerce and Commerce Billy to generate invoices. My question is :

In *Complete checkout process* I want to edit all *orders status* to "**Invoiced**" !! .

I already created this Rules Component and it works fine. With component I can add 1 order for me(admin) and other orders to user concerned , is that make sense.

So what I want to do is : after complete checkout process I want to change all these orders status to "**invoiced**"

```
{ "rules_add_prod_to_cart_6" : {
"LABEL" : "Add Prod to cart 6",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"USES VARIABLES" : { "commerce_product" : { "label" : "Commerce Product", "type" : "commerce_product" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "commerce-product" ], "field" : "field_user_concerned" } }
],
"DO" : [
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "site:current-user" ],
        "sku" : "[commerce-product:sku]\t",
        "quantity" : "1",
        "combine" : "1"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
    }
  },
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "commerce-product:field-user-concerned" ],
        "sku" : "[commerce-product:sku]\t",
        "quantity" : "1",
        "combine" : "1"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item2" : "Added product line item 2" } }
    }
  }
]

```

} }

Example :
**SKU** | **Label** | **Price** | **User** |
001 | Product 1 | $10 | Userexample1 |
002 | Product 2 | $40 | Userexample2 |
003 | Product 3 | $20 | Userexample1 |
004 | Product 4 | $70 | Userexample2 |

*what I already done:*

So after Clicking on "Add product and generate order" button :
In the above example I get 3 orders
*the owner of the first order = **\[site:current-user\]** and it will return :*
**All Products** (Product1,Product2,Product3,Product4)
The owner of the second order = **Userexample1** and it will contain
Product1 and Product 3
The owner of the last order = **Userexample2** and it it will contain
Product2 and product 4

So the order status of all those orders = Shopping cart (because we didn't complete the checkout yet), and when we complete the checkout it will change ONLY the FIRST ORDER status to **"Invoiced"**, because \[site:current-user\] is the owner of it.

I want to change all the above orders status when "Complete checkout process" event is fired !

Please see images below:

After Clicking on "Add products to cart and generate orders"

"New 3 orders"

Complete checkout process

**First order status = Invoiced , BUT THE TWO OTHERS DOSEN'T CHANGE**

Is that possible ? How could I do that using Rules Module ?

# Answer
> 0 votes
I fixed this issue by adding this PHP code:

`$orders = commerce_order_load_multiple(array(), array('status'=>'cart'), TRUE);
foreach($orders as $order){
 $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
 foreach($order_wrapper->commerce_line_items as $line_item_wrapper){
 $product = $line_item_wrapper->commerce_product;
 $node_product = $node_wrapper->field_product;
 $order_wrapper->status = 'invoiced';
 $line_item_wrapper->save();
 $order_wrapper->save();
 }
}`

---
Tags: commerce, rules
---


# Question
Title: show all the blocks added to the particular page?
I've been tasked to remove a tracking javascript from a particular URL on our Drupal 7 website. I've grepped our site's codebase for the name of the javascript that's being loaded, but I don't see it.

I need to start combing through content, but I'm looking at making my task easier.

Sometimes our front-end devs will include scripts in blocks. I want to look at all the blocks that are included in my target URL, but I don't see how to do that in the interface.

It seems that I must look at each of our blocks and then see if it's added to the page. I wonder, however, if there is a page somewhere in the admin menu where I can enter the URL I'm looking at and see what blocks are being attached to it.

# Answer
The simple answer is that there isn't such a page. But you can go to the block administration page and see a list of all blocks for the given theme. If there is a 'configure' link for the block, it's a block that was created through the admin interface, so you can go through them to try to find the block in question.

The other thing you can do is examine the HTML to find the HTML id for the block. This will give you an indication of which block it has been added to, or if it was even added through a block or not.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How do I return an SQL query result as custom variable in a template?
Is there any way to pass a SQL result with using hook in .theme file? My scenario is following: I have a paragraphs module's view in which I've need of all nodes from content type News to iterate and show by taxonomy term.

# Answer
You can add variables using a `hook_preprocess_THEME()` function. For example, if you are trying to add a variable to the `page.html.twig` template, the theme hook is `page`. So you would use the following:

```
function hook_preprocess_page(&$vars)
{
  // Add your result to the $vars array:
  $vars['some_variable'] = db_query('SELECT something FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();
}

```

Because you've added `some_variable` to the `$vars` array, `some_variable` will be available in your template.
> 1 votes

---
Tags: 8, hooks, paragraphs
---


title: "Changed by" column for node list

text:
# Question
Title: "Changed by" column for node list
If a node is changed by another user, the change time is shown on /admin/content but not by which user the node was changed. I couldn't find any field in the respective view to add. Did I miss sth?

# Answer
> 0 votes
* Edit the "Content" view.
* Add "User - Content revision" in Relationships under "Advanced" tab.
* Add "Name - User" in the fields using the Revision user relationship. You can set a label for this field as "Last modified by".

---
Tags: views, nodes, 8
---


# Question
Title: Why has the security shield for my new module been removed?
I have recently managed to create a module on Drupal.org, following the entire process from sandbox, to project application, to full project.

After few weeks, my module lost the security shield and the following message is visible on the project page.

> This project is not covered by the security advisory policy.
> It may have publicly disclosed vulnerabilities. Use at your own risk!

>

I have gone through some of the documentation, such as Security advisory process and permissions policy, but I couldn't find an explanation.

Why does that message appear in the project page?
How can I resolve it?
How can I find what is wrong in my module?

# Answer
Only full releases get the security shield. Your screenshot only shows a dev version. I don't think the shield was removed from your module, as it wouldn't have had one in the first place since you don't have a full release.

To get the security shield, you'll need to release a full version (one not suffixed with -dev, -alpha or -beta).

\** EDIT \**

I have just discovered that an additional step needs to be taken in addition to creating a full release. Until recently, if a module was given a full-release, it automatically received the security advisory. However, I just promoted a module I've got from RC to a full release, and it did not receive the security advisory. Editing the module page now has an option that requires to module maintainer to opt into the security advisory.

Even having done so, my module still does not have the advisory shield, so I assume it now goes under some review from the security team before receiving it. This issue seems to support that assumption: https://www.drupal.org/node/2666584

--- Edit 2 ----

It turns out their was a bug in the system. I am already able to promote modules to drupal.org rather than the sandbox. With existing modules, when upgrading from D7 -\> D8, modules were automatically given the shield when I released a full version. However the module I mentioned above did not have a D7 version, and when I promoted it to a full release it didn't receive the shield. After waiting two weeks for approval I finally contacted the security team, and they looked into it and found a bug in the caching system, and fixed it.

So it appears that the original information I gave - that you just need to release a full version, and have opted into security advisory coverage, is correct.

Here's a screenshot of the module edit page.
> 10 votes

# Answer
***`You need to create an official release, for at least 1 version of Drupal core that is supported.`*** In your case, for D7, like a 7.x-1.0 version of your module. Shortly after doing so, your module will have the security shield.

If you want, have a look at modules such as the Conditional Rules module, used in over 11K Drupal 7 sites. It has the same message shown on its project page also.

### Drupal core criteria

* "*Only full releases get the security shield*" (as in the accepted answer) may need some refinement: have a look at the Support Ticketing System module, which does have a full release for D6 (which is no longer supported). But it does NOT have the security shield either.
* If a module does have an official release for at least 1 version of a supported Drupal core version (eg: for D7), then the security shield will not be removed by adding a dev, alfa, beta or rc version (with no official release yet) for another supported Drupal core version (eg: for D8). For a sample of this, have a look at the Rules module. Note however that in this case the D7 version has an extra (green) shield that is not shown for the D8 version of it.

### More info

For way more details on this, refer to these issues:

### How to create an official release

Head over to your `https://www.drupal.org/project/myproject/git-instructions` (whereas you replace `myproject` with your module name). Near the bottom of it, you'll find detailed instructions about ***Creating Releases***. More specifically you should do what's mentioned within ***Tag for a stable release*** there, which is like so:

> git checkout 7.x-1.x
>
> git tag 7.x-1.0
>
> git push origin tag 7.x-1.0
>
> Once you've pushed the properly formed tag or branch, see Creating a project release for directions to actually create the release node.

### Bonus tips

* If you're not ready yet to create an official release, you can always add some note on your project page like "***`Note: as the module maintainer, I'm not aware of any publicly disclosed vulnerabilities`***".
* IMO "***`Use it at your own risk!`***" applies NOT only to contributed modules for which the security shield is NOT shown.

### Related article

Drupal Security Shield For Contributed Modules,What That Means? (Credits: zhilevan)
> 3 votes

---
Tags: 7, community-official-site
---


# Question
Title: adding drop-down subject (html select) to contact form
I would like to add a select field like a drop-down in the contact form to let user select the reason why they contact (contact, customer support, etc.)

Based on this (excellent) answer Adding check boxes to contact form, i’ve managed to create a field with check box :

source : Adding check boxes to contact form

How can i do that with a select ?

**Solution :**

You can choose in the "manage form display". The column "widget" allow to choose "Select list" (see screenshot)

# Answer
The question you referenced explicitly changes it *from* Select list (Which is the default for list fields) to checkboxes. All you need to do is skip that last step and keep it on Select List, then you have your Select.
> 3 votes

# Answer
There is a select form element that you can add to your buildForm or hook override, depending on how you are building your form:

```
$form['example_select'] = [
  '#type' => 'select',
  '#title' => $this->t('Select element'),
  '#options' => [
    '1' => $this->t('Contact'),
    '2' => $this->t('Other'),
    '3' => $this->t('Customer Support'),
  ],
];

```

This is from the Drupal documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Select.php/class/Select/8.2.x.
> 3 votes

---
Tags: 8, entities, emails
---


# Question
Title: Drupal commerce and multiple products sharing SKU
I have a commerce shop, and a question about product "sharing" SKU.

I have products which is sold as single products, but also in a box.

Lets say I have "Product A" with price $ 1 , with SKU 00001.

I have a box with 10 x "product A" which on the website should appear as "Product A box" and price $ 9. (I need it to be the same product, but shown as separate "product"

I need it because, if I have two separate products, then I can't be sure I have the correct amount in stock.

Is that even possible ?

# Answer
You can handle that with Commerce Product Bundle. Some details about it, from its project page:

> This module extends Drupal Commerce by allowing the site admin to collect a number of existing products together in a bundle, and offer them at a new bundle price, with a new bundle SKU.
>
> You can define products that consists of other products. They are all combined in one add to cart form which works like the core add to cart form. The bundle is then represented by one order line item. This allows the maximum compatibility with other modules such as shipping or payment modules.

As an alternative, there is also Commerce Bundle. Some details about it, from its project page:

> Implements product bundles for Drupal Commerce. For example, you want to offer products A, B, and C for a lower cost if purchased together rather than standalone. Notable features include setting the prices at the bundle group or product level, and product attribute support.

**Note**: if you wonder how those to modules compare to each other, then this might help (= quote from the Commerce Product Bundle project page):

> Commerce Bundle also allows creating product bundles. Customers add a bundle to their cart, but the component products show in checkout and order history. It therefore doesn't allow assigning an overall price to the bundle (but it has some neat ways to assign prices to component products). With Commerce Product Bundle, the bundle, not the component products, show in checkout and order history. Therefore an overall price can be assigned to the bundle
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Clicking any administration menu link results in empty overlay screen
I've created a Drupal site which behaves rather strange - whenever I click an item in the administration menu or use a contextual link to edit a page, the half-opaque overlay shows, but no editing window opens on top of it as it should (not just "not immediately", but never).

Once I'm in "overlay mode", if I click a menu item, the linked page opens as it should, on top of the overlay. From here, all items work as intended, except when opened in a new tab - that will also only show an empty overlay page.

When the overlay is eventually closed again (for example, by clicking the home link to return to the front page), the error described above will reoccur the next time an administrative link is clicked.

Can anyone assist me in finding the source of this problem? Please let me know if you need additional information.

---

The site was built on 7.53 originally and is now updated to 7.54 (up to date). No changes to the `.htaccess` file have been made, therefore all of my changes are within the `/sites/` directory.

I'm using these contrib modules: Chaos tools, CKEditor, Views, Views UI, Webform

My administration theme is Seven.

I've set up other Drupal 7 sites on the same environment and didn't have this problem, so I clearly I did something different here. I have no idea where to start looking, though, and wasn't successful in finding other questions or external info covering anything even remotely related.

# Answer
> 0 votes
The issue turned out to be caused by me including jQuery via the following line in my theme's info file:

```
scripts[] = js/jquery-3.1.1.min.js

```

Removing this line and using the jQuery version included by default (1.4.4) will return the *$ is not a function* error when using `$()` syntax, which can be resolved by wrapping existing jQuery code in the following:

```
jQuery(function ($) {
  // ...
});

```

---
Tags: 7, debugging
---


title: How do I add custom template files?

text:
# Question
Title: How do I add custom template files?
Currently, I am using the following code.

```
/**
 * Implements hook_theme_registry_alter().
 */
function MY_MODULE_theme_registry_alter(&$theme_registry) {
  // Defined path to current module.
  $is_admin = Drupal::service('router.admin_context')->isAdminRoute();
  $node = \Drupal::routeMatch()->getParameter('node');
  if (isset($node)) {
    if ($node->getType() == 'MY_CONTENT_TYPE' && $is_admin == 0) {
      $module_path = drupal_get_path('module', 'reveal_js');
       $theme_registry['html']['path'] = $module_path . '/templates';
       $theme_registry['page']['path'] = $module_path . '/templates';
    }
  }
}

```

This works, but when going to another page, I have to rebuild cache in order for it to re-evaluate whether the node is 'MY\_CONTENT\_TYPE' or a different type.

# Answer
It looks like `hook_theme_registry_alter()` is only executed when the theme cache is rebuilt. This means that what you need to do is use one of the theme\_suggestion\_alter hooks, such as `hook_theme_suggestions_alter()` or `hook_theme_suggestions_node_alter()`. These get run for each page before it is cached, I believe, instead of only once on cache rebuild.

So, what you want to do in your module is create a theme implementation using `hook_theme()`. That would look something like this:

```
function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'my_theme_implementation' => array(
      'path' => drupal_get_path('module', 'reveal_js') . '/templates',
      'template' => 'my_theme_implementation',
    ),
  );
}

```

And then your `hook_theme_suggestions_node_alter()` would be something like

```
function MYMODULE_theme_suggestions_node_alter(&$suggestions, $variables) {
  $is_admin = Drupal::service('router.admin_context')->isAdminRoute();
  $node = $variables['elements']['#node']
  if ($node->getType() == 'MY_CONTENT_TYPE' && $is_admin == 0) {
    $suggestions[] = 'my_theme_implementation';
  }
}

```

Does that all make sense?
> 7 votes

# Answer
Tried both solutions listed and only the first one, using `hook__theme_registry_alter` had the desired result that I was looking for, i.e., I wanted to create a template that would behave just like creating a template file in a theme would do, i.e., want it to be processed just like a page template. You can see that with the working implementation you get the full set of preprocess functions.

```
    [page] => Array
    (
        [template] => page
        [path] => modules/futusign/templates
        [type] => base_theme_engine
        [theme path] => core/themes/bartik
        [render element] => page
        [preprocess functions] => Array
            (
                [0] => template_preprocess
                [1] => template_preprocess_page
                [2] => contextual_preprocess
                [3] => futusign_preprocess_page
            )

    )

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Fill Date field in a hook form alter with ajax callback
I'm trying to populate some fields via Ajax.

Is working good with textfields, but no with date field and select list.

After the rebuild of the form the date field is empty and the select too.

Here my code:

```
function PORTO_SUB_form_alter(&$form, &$form_state, $form_id)
{ if ($form_id == 'datore_node_form')
{
global $user;
  $form['title']['#type'] = 'hidden';
  $form['title']['#value'] = 'test';

  $form['#prefix'] = '<div id="datore_node_form_prefix">';
  $form['#suffix'] = '</div>';

    $form['user_copy'] = array(
      '#type' => 'button',
      '#value' => 'Sono io il datore!',
      '#ajax' => array(
        'event'=>'click',
        'callback' =>'user_copy_ajax_callback',
        'wrapper' => 'datore_node_form_prefix',
    ),
  );
  // field_group_hide_field_groups($form, array('group_azienda'));

  $user = user_load($user->uid);

  dpm($form);

  if (!empty($form_state['values']['field_cognome']))
  {
    unset($form_state['input']['field_cognome']['und'][0]['value']);
    $form['field_cognome']['und'][0]['value']['#value'] = $user->field_cognome['und'][0]['value'];
    $form['field_nome']['und'][0]['value']['#value'] = $user->field_nome['und'][0]['value'];
    $form['field_luogo_di_nascita1']['und'][0]['value']['#value'] = $user->field_luogo_di_nascita1['und'][0]['value'];

    $form['field_data_di_nascita1']['und'][0]['#date_items']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#date_items']['value']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#date_items']['value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#default_value']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#default_value']['value']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#default_value']['value'] = $user->field_data_di_nascita1['und'][0]['value'];
return $form;
}

function user_copy_ajax_callback($form, &$form_state)
{
dpm($form['field_data_di_nascita1']['und'][0]['#default_value']['value']);
return $form;
}

```

# Answer
Here the solution finally:

https://www.drupal.org/node/1984838#comment-11736060

I had to fill both $form and $form\_state values...

$form\_state\['input'\]\['your\_field\_to\_change'\]\['und'\]\[0\]\['value'\] = $new\_date; $form\['fyour\_field\_to\_change'\]\['und'\]\[0\]\['#default\_value'\]\['value'\] = $new\_date;
> 0 votes

---
Tags: ajax, forms
---


# Question
Title: After node creation how do i add simple buttons to edit the field values
\`\`I'm new to drupal,I'm trying a create a content type with some field values which the user can use to create the content for the content type.In the node\_view i have added some markup html to create additional generated fields to the content type.Now i want to add few buttons for the user to change the values in my content.

I created a form in node\_view hook with a submit button so when user clicks the button i get to modify the node's properties,but i dont understand how to pass the node\_id to callback form handler.

Or In general what's the standard process to let users create content for content type with server generating the additional info for the content.

```
function mymod_node_view($node, $view_mode, $langcode) {
if ($node->type == 'app')

$node->content['apikey'] = array(
        '#markup' => "<strong>Client Key</strong> <br/> ".$key['client_key'] ." <br/> <strong>Client Secret</strong> <br/>".$key['client_secret']."<br/> Node id". $node->nid.",",
        '#weight' => 10
    );

    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'button',
        '#value' => t('Reset Key'),
       // '#callback' => 'my_special_btn_function',
    );

  $form['nid'] = array(
    '#value' => arg(1),
    '#type' => 'hidden'
);
}

function redirect_button_form_submit($form, &$form_state) {

$nid=$form_state['input']['nid'];

drupal_set_message('The form has been created nodeid,'. $node->nid .',key reset');

```

# Answer
1. The $node\_id is blank as there is no value passed for it. In order to get node\_id in the submit handler function, you should pass the node\_id in the form. So pass the node id value as a hidden field in the form and get the value of hidden form element through $form\_state of *redirect\_button\_form\_submit*. In that way you can do it. Example : $form\['node\_id'\] = array('#type' =\> 'hidden', '#value' =\> $nid);
2. Yes it is possible for you to edit $node-\>content\['apikey'\] if and only if it is saved in database. Create a new field as apikey in the content type and store it. Hope it helps. Thanks.
> 2 votes

# Answer
There are couple of ways to find the node nids.

1. You can get from the URL using **arg ()** function for example if the url is www.example.com/node/123645/ arg (0) represents : node arg (1) represents : 123645
2. Through node object always **$node-\>nid** gives you the node nid
> 0 votes

---
Tags: commerce, hooks
---


# Question
Title: Edit Unit Price line item After Adding product to the cart
I am working with Drupal Commerce.

How I could edit the Unit Price of all Commerce Line Items to *$200* when "Add a Product to Cart" Event is fired. !

# Answer
> 1 votes
this rule update unit price Unit Price of all Commerce Line Items to $200 when "Add a Product to Cart" Event is fired.

```
{ "rules_set_unit_price" : {
"LABEL" : "Set Unit Price",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"DO" : [
  { "data_set" : {
      "data" : [ "commerce-line-item:commerce-unit-price" ],
      "value" : { "value" : { "amount" : 20000, "currency_code" : "USD" } }
    }
   }
  ]
 }
}

```

# Answer
> 0 votes
I already tried this , and it works fine for me , Thanks for your answers.

{ "rules\_calp8" : {
```
"LABEL" : "Set Unit Price",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [
  "commerce_cart",
  "rules",
  "commerce_line_item",
  "commerce_product_reference"
],
"ON" : { "commerce_product_calculate_sell_price" : [] },
"IF" : [
  { "commerce_order_is_cart" : { "commerce_order" : [ "commerce-line-item:order" ] } },
  { "data_is" : { "data" : [ "commerce-line-item:order:uid" ], "value" : "1" } }
],
"DO" : [
  { "commerce_line_item_unit_price_amount" : {
      "commerce_line_item" : [ "commerce_line_item" ],
      "amount" : "20000.00",
      "component_name" : "base_price",
      "round_mode" : "1"
    }
  }
]

```

} }

---
Tags: commerce
---


# Question
Title: Within bootstrap theme, print radio item with label and input as siblings instead of parent -> child
By default, Bootstrap will render the `input` radio and checkbox elements as children of the `label`. This is done in `Drupal\bootstrap\Plugin\Preprocess\FormElement`, starting at line 45:

```
// Place single checkboxes and radios in the label field.
if (($checkbox || $radio)) {
  $label = Element::create($variables['label']);
  $children = &$label->getProperty('children', '');

```

In some instances, I don't want these printed as siblings - how can I undo this? `form-element.html.twig` isn't helpful unless I can somehow print the children first e.g. `{{ label.#children }}` and then twig will know not to print them again. Not sure if that solution is even possible.

Thanks!

# Answer
> 1 votes
At first I was going to say `hook_form_alter`, but when I started digging into the Bootstrap theme I found they've created their own plugin system. I would checkout this page, you might be able to get to the render array by creating a Bootstrap theme plugin: https://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins\_form/8

# Answer
> 0 votes
As @icicleking states, bootstrap uses theme plugins that can be extended. So that we have a thorough answer for what I did I'll post it separately here.

Extend `\Drupal\bootstrap\Plugin\Preprocess\FormElement`. There's only one method, `preprocessElement`. In my case I replaced the following:

```
// Place single checkboxes and radios in the label field.
if (($checkbox || $radio)) {
  $label = Element::create($variables['label']);

```

with

```
// Place single checkboxes and radios in the label field.
if (($checkbox || $radio) && !$element->hasProperty('no_wrap_label')) {
  $label = Element::create($variables['label']);

```

Then you can use the `no_wrap_label` property on any element that you don't want to be wrapped inside a label, I'm using `hook_preprocess_form_element`:

```
function your_module_preprocess_form_element(&$variables) {
  if ($variables['name'] == 'field_field_name') {
    $variables['element']['#no_wrap_label'] = TRUE;
  }
}

```

---
Tags: theming, 8
---


# Question
Title: avoid fatal guzzle exception error on api requests
how can i avoid fatal error due to ?

```
 |GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host|

```

My code here do not catch it

```
try {
      $client = new Client();
      $response = $client->request('GET', $url);
      $content = json_decode($response->getBody(), true);
    }
    catch (Exception $e) {
      \Drupal::logger('amu_hal')->error('this url aint good'.$url);
    }

```

# Answer
> 3 votes
This is an example on how to catch this error:

```
    use GuzzleHttp\Client;
    use GuzzleHttp\Exception\ClientException;
    use GuzzleHttp\Exception\RequestException;

    try {
         // example of status code 500
         $url='http://httpstat.us/500';
         $client = new Client();
         $response = $client->request('GET', $url);
         $content = json_decode($response->getBody(), true);
    } catch (ClientException $e) {
    // catches all ClientExceptions
} catch (RequestException $e) {
    // catches all RequestExceptions
}

```

---
Tags: 9
---


# Question
Title: Error when using Rules to automatically email user referenced by node when node is updated
I am having trouble setting up a rule to email a specific user referenced by a node. The structure I am trying to set up is:

When node of type A is updated, and satisfies certain criteria, the user referenced by node of type B, which is referenced by the original node of type A, should receive an email.

Below is the error log:

```
0 ms Reacting on event After updating existing content.
13.753 ms Evaluating conditions of rule Released Email. [edit]
15.155 ms The condition entity_has_field evaluated to TRUE [edit]
19.279 ms The condition entity_has_field evaluated to TRUE [edit]
19.535 ms The condition entity_has_field evaluated to TRUE [edit]
26.27 ms The condition data_is evaluated to TRUE [edit]
26.288 ms AND evaluated to TRUE.
" Rule Released Email (Maintenance Log) fires. [edit]
0 ms Rule Released Email (Maintenance Log) fires.
47.438 ms Unable to get the data value for the variable or parameter to. Error: Unable to get the data property mail as the parent data structure is not set.
48.391 ms Unable to evaluate action mail. [edit]
48.472 ms Rule Released Email (Maintenance Log) has fired.

```

And this is what the condition structure looks like:

```
Entity has field
Parameter: Entity: [node], Field: <referenced node>

Entity has field
Parameter: Entity: [node:<referenced node>], Field: <referenced user>

Data comparison
Parameter: Data to compare: [node:field-status:name], Data value: <desired value>

```

Export:

```
{ "released_email_maintenance_log" : {
    "LABEL" : "Released Email (Maintenance Log)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--maintenance_interval" : { "bundle" : "maintenance_interval" },
      "node_update--maintenance_interval" : { "bundle" : "maintenance_interval" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_project" } },
      { "entity_has_field" : { "entity" : [ "node:field-project" ], "field" : "field_pm" } },
      { "entity_has_field" : { "entity" : [ "node:field-project" ], "field" : "field_client" } },
      { "data_is" : { "data" : [ "node:field-status:name" ], "value" : "Released" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "node:field_project:field_pm:mail" ],
          "subject" : "[node:field-project] is [node:field-status]",
          "message" : "[node:field-project:0:field-client:title] maintenance updates are ready for your review here: [node:field_testing_url]\r\nFor more information, visit [node:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Based on the answer below, here is an updated export of the rule in question:

```
{ "released_email_maintenance_log" : {
    "LABEL" : "Released Email (Maintenance Log)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--maintenance_interval" : { "bundle" : "maintenance_interval" },
      "node_update--maintenance_interval" : { "bundle" : "maintenance_interval" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_project" } },
      { "entity_has_field" : { "entity" : [ "node:field-project" ], "field" : "field_pm" } },
      { "entity_has_field" : { "entity" : [ "node:field-project" ], "field" : "field_client" } },
      { "data_is" : { "data" : [ "node:field-status:name" ], "value" : "Released" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "node:field-project:field-pm:uid" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "mail" : {
          "to" : [ "user-fetched:mail" ],
          "subject" : "[node:field-project] is [node:field-status]",
          "message" : "[node:field-project:field-client:title] maintenance updates are ready for your review here: [node:field_testing_url]\r\nFor more information, visit [node:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

And the error this new configuration produces:

```
0 ms Rule Released Email (Maintenance Log) fires.
3.423 ms Unable to get the data value for the variable or parameter id. Error: Unable to get the data property uid as the parent data structure is not set.
5.291 ms Unable to evaluate action entity_fetch. [edit]
6.352 ms Unable to get variable user_fetched, it is not defined.
7.117 ms Unable to evaluate action mail. [edit]
7.177 ms Rule Released Email (Maintenance Log) has fired.

```

# Answer
The crucial error message in your error log is the one like "`Unable to get the data value for the variable or parameter to`". The way I read that is like "sorry, you want me to send an eMail to some eMail ID, but I'm missing its value".

It seems like you could get it to work by inserting a (1st) Rules Action (before the Rules Action you already have) like "Fetch entity by ID", to go get the relevant data of the referenced user. Whereas you use the value indicated by the user that is referenced.

If you then store the fetched user data in (eg) `user_fetched`, you should be able to use `user_fetched:mail` as the token in the "To" of the eMail you want to send.
> 0 votes

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


# Question
Title: Alter a custom block depending on custom block type
I need to alter all the blocks of custom type 'my\_custom\_block\_type' that get displayed on my site. In order to achieve this, i added a custom prerender in which i filter on the block bundle :

```
function my_module_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = '_custom_block_custom_prerender';
}

function _custom_block_custom_prerender(array $build) {
  if ($build['content']['#block_content']) {
    $block_bundle = $build['content']['#block_content']->bundle();

    if ($build['content']['#block_content']->bundle() === 'my_custom_block_type') {
      // do your thing here
    }
  }
  return $build;
}

```

I think it's not the most elegant way to do this.

I tried to enhance this, but i did not manage, after several attempts, to retrieve the block type directly inside a hook\_block\_view\_alter or a hook\_block\_build\_alter ...

```
function hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // things
}
function hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // stuff
}

```

Is there a way to easily get the custom block type inside those two hooks ?

# Answer
Try `hook_ENTITY_TYPE_view()`/`hook_ENTITY_TYPE_view_alter()`, that gives you the `block_content` `$entity` as an argument, just like `hook_node_view()`.
> 2 votes

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


# Question
Title: How to get the URL addresses of all the photos on form
I have standard input form for custom content (for example, /node/add/page and /node/%/edit) with image-field in which you can upload multiple photos. How to get the full URL addresses of all the photos when user add new content or editing old one (delete or upload extra photos)?

# Answer
> 0 votes
I implemented it this way. Hopefully this will save someone's time. The code works well if you upload files, delete if it works after the removal of the second file in this list and removes only the first remote URL.

```
function testmodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo']['#element_validate'][] = 'my_function';
}

function my_function($element, &$form, &$form_state){

        $lang = $element['#language'];
        foreach (element_children($element[$lang]) as $key) {
                $fid = $element[$lang][$key]['#value']['fid'];
                $file = file_load($fid);
                $url = file_create_url($file->uri);
                dpm($url);
        }
}

```

---
Tags: 7, forms, media
---


# Question
Title: Is it possible to create 'grouped' fields of related data?
I have a content type (Recipe) in which my users can add ingredients (terme references). I also have a text field to enter quantity How is it possible to link this "ingredient" field to the quatity field?

I want to recreate something like this (from Recipe module) :

# Answer
> 3 votes
You could use the Paragraphs module OR Field Collection module

Example (from paragraphs):

Then with a little CSS magic, you can put them side by side, if you really want it like that.

# Answer
> 2 votes
Since this is Drupal 7 I would advise using Field Collection to do this. I have done it many times, and for a generic use case of 'bundled' or 'grouped' fields, this is precisely what you want. Note that you will have to redo these fields (pictured above) and define them in a collection. Then, every collection entity holds X fields, therefore, each collection entity is in this case, one ingredient of the recipe.

If you are running an ecommerce store, you can get creative with these as well by adding a product reference, for example, if you sell the ingredients. That is, you can add collection fields that are not displayed publicly, but used to drive other content displays based on relationships.

Just know that the difficulty in theming field collection data might throw you for a loop at first, as well as searching/Views with collections.

You will also want to pick up Field Collection Table module so the field is formatted in a table for editing or display.

---
Tags: 7, forms
---


# Question
Title: Term page doesn't show nodes when terms are added in a field collection?
I'm using field collection in my content type Recipe. In my field collection, there is a term reference (ingredient) and a text field.

When I create a Recipe, I add terms (ingredients) with the field collection. But when I visit the term page (ingredient X), no recipes are listed even if this ingredient is used in a recipe.

I think the problem comes from Field collection : the term is linked to the field collection but not to the created content.

How do I display all the recipes linked to an ingredient when I visit a term page ?

Sorry for my bad English, i'm not sure i'm clear.

# Answer
This is because the default term page implementation in Drupal 7 is querying node relationships, it has no awareness of relationships to Field Collections that are related to Nodes (or potentially, other entities).

You would have to solve this yourself by using a module like Taxonomy Views Integrator, which lets you create Views and set them as the term page view instead of the default Drupal page callback which won't ever work in this scenario.

You can follow why you aren't getting hits from Drupal core here. Hence, you need to override this presentation.

So, if you use TVI, you'd want to create a View that selects field collections with relationships to terms and nodes, and give it a contextual filter of taxonomy term id from URL (assuming taxonomy/term/%tid path). This should get you results, and let you link to the node. I don't have a sandbox setup to try this out, so you may need to experiment on the View formula.
> 0 votes

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


# Question
Title: How to create a Rule to email referenced authors after saving new content?
I am trying to create a review platform. I have multiple content types, and I have created ***review*** content types which are referenced to these content types.

I want to create an action (tell me if you think there is a better way) which would send an email to the original content author to notify them that a review has been published about their content.

Any ideas how to do this or if it's possible?

# Answer
However, I think that with the answer you posted yourself (which works for you), you've been lucky quite a bit. Especially because of the "`:0`" part in the token you used: that sounds like your reference field is a multi value field (which you didn't say in your question). So therefor your answer will only work for the 1st referenced node, ie if you have multiple referenced nodes, any additional authors (of the other nodes) will never receive such eMail. As per your "***tell me if you think there is a better way***": read on for some more details to make that also work ...

Create a rule like so (in Rules export format):

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

```

Some more details about the above rule:

* **Rules Event**: After saving new content of type "Review" (adapt the type to fit your needs).
* **Rules Action**: a "loop" for all selected values of a multi value select list (contains the referenced content types). For each item (= `current_referenced_node`), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs.

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

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

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

# Answer
Actually it's a LOT easier than I thought. I found that the following worked for me so far:

```
node:referenced-field:0:author:mail

```

I hope that this helps someone.
> 1 votes

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