# Question
Title: Add external JavaScript files containing a parameter in the URL
I need to add some external JS files to my website. This is an extract of the module.libraries.yml file.

```
my_live_chat:
  js:
    https://mylivechat.com/chatinline.aspx?hccid=12345678 : { type: external, attributes: { defer: true, async: true, data-cfasync: 'false' } }
    https://www.mylivechat.com/chatapi.aspx?hccid=12345678 : { type: external }

```

As you can see, they have this final variable `hccid` in them that is different for each website.

I'd like to create a custom module where I only need the client ID (the `hccid` value) and the module adds all the needed JavaScript files.

I know how to create a custom module with a settings form to ask for the variable value and I know how to add external JavaScript files to my module.libraries.yml file.

How can I deal with that variable so it can be different on each website without modifying the module?

# Answer
> 7 votes
Use the `hook_library_info_build` hook to add dynamic library definitions.

The key(s) could be stored as configuration. e.g. use Simple Configuration API

You would then in the hook, check if the configuration has a value and if so add the library and if not, well depending on how you want to deal with it.

---
Tags: 8, javascript
---


# Question
Title: How to display the average of the votes of a rating field from a form made with webform (D8)?
I've made a rating form using the webform module. I'm looking for a way to display the average result of the votes on the node. Any suggestions?

# Answer
Check out the Webform Analysis module.

> This module is used to obtain statistics on the results of form submissions.
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Using one exposed filter on different date fields
So been looking at this for a bit now and nothing springing to mind so question and advice needed. On Drupal 8.

**What I want:** I have a content type with three date fields (Date A, Date B and Date C). Using a view I can create an exposed filter to filter dates between ranges, before, after, etc on say Date A. I can do the same for the other date fields.

I would like to restrict it to one date field at a time. So select the dates for Date A **OR** Date B **OR** Date C but never more than one date field.

**Question** Sounds simple. I cannot find a simple way to do this so unless I have missed the obvious am going to have to create a module. Before I look into that and start the ball rolling are there any existing solutions I have missed?

Assuming there is no easy way my thought was to create a new module.This would allow one date input and then a select box to choose which field to perform the operation on.

I have not yet looked at this in depth so as to using JS/AJAX to achieve this or a PHP solution (Class or hook), I am open to suggestions.

Thanks

# Answer
> 0 votes
Create three different views, each with one exposed filter. Use css class to control visibility, use a bit of javascript to move around.

Refer How to create views tabs in D8?

---
Tags: views
---


# Question
Title: How to hide View Page Menu if there is no content?
I'm using the Views module (7.x-3.14) and I have a *news* view which shows all the articles on a page. I also have its *Menu* settings set to *Normal*, thus adding *News* to my navigation.

This works as expected; however, if there are no articles published, I would like the *News* link not to be added to my navigation. Essentially I would like a *No results behavior* for the menu.

Is there a way to accomplish this?

EDIT: I'm using Zurb\_Foundation as my base theme which uses a custom function to create the menu that is called in `preprocess_page`. What I was attempting to do remove *News* from the menu at this point.

```
function theme_links__topbar_main_menu(&$variables) {
  // We need to fetch the links ourselves because we need the entire tree.
  $links = menu_tree_output(menu_tree_all_data(variable_get('menu_main_links_source',     'main-menu')));
  foreach ($links as $link){
    if(is_array($link) && array_key_exists('#title', $link)) {
      if($link['#title'] == 'News'){
        $view = views_get_view('news');
        echo count($view->result);
        echo $view->total_rows;
      }
    }
  }
  $output = _zurb_foundation_links($links);
  $variables['attributes']['class'][] = 'right';

  return '<ul' . drupal_attributes($variables['attributes']) . '>' . $output . '</ul>';
}

```

`count($view->results)` returns 0 and `$view->total_rows` returns NULL even though there should be results.

# Answer
There are multiple options do do this, but all seem to require custom coding.

Maybe Hiding tab when view is empty or How to find out programmatically if a view has a result before rendering the whole view? give an idea of how to do that. They are both mainly about Drupal 6, but the same principles apply.

I would probably use some hook\_preprocess or theme function, load the view using views\_get\_view(), execute that with all the necessary arguments if any, then check the result count and if that's empty, remove the menu link from the page. That last part is described in How to hide menu items without relying on permissions \[SOLVED\] and Customizing menu link output

**Update:** So in your example you could do:

```
$view = views_get_view('news');
$view->execute();
$link['#access'] = count($view->result) > 0;

```
> 1 votes

# Answer
While the answer above is helpful I didn't find it isn't complete. Personally, rather than tweaking the output I preferred to modify the *access* of the particular menu items dynamically.

* Hook\_menu\_alter - Provides the available modifications to setup new access permissions
* Access\_callback - Is your personal access callback function
* hook\_module\_implements\_alter - Use this to override the order of modules processing the menu items, placing yours at the bottom after views

```
    /**
     * Implements hook_menu_alter()
     */
    function yourmodule_menu_alter(&$items) {
      // Modify view access callback functions
      $items['viewpath']['access callback'] = 'yourmodule_access_callback';
    }

    /**
     * Access callback function
     */
    function yourmodule_access_callback($options = array()) {
      // Grab the default access callback function name, prepare the access
      // arguments, then see what the default access call back result is
      // according to views.
      $access_callback = $options[0];
      $access_arguments = $options[1];
      $access = call_user_func_array($access_callback, $access_arguments);

      // If the default access call back was false, then the user is not allowed
      // access.
      if (!$access) {
        return FALSE;
      }

      // So far the user is allowed access from the views' settings, let's now
      // determine if we want to customize the access to the tab.

      // Determine if the view has any result
      $view = views_get_view(yourview);
      $view->set_display(yourdisplay);
      $view->execute();
      return (count($view->result) > 0);
    }

    /**
     * Implements hook_module_implements_alter().
     */
    function yourmodule_module_implements_alter(&$implementations, $hook) {
      // When the implementations of hook_menu_alter are called, we need our module
      // to be called after views, so let's remove it from the implementations then
      // add it to the end.
      if ($hook == 'menu_alter') {
        if (isset($implementations['yourmodule'])) {
          unset($implementations['yourmodule']);
          $implementations['yourmodule'] = FALSE;
        }
      }
    }

```
> 1 votes

---
Tags: 7, views, navigation
---


# Question
Title: How do I install Drush 9 on Windows 7 with Composer?
Should I globally install Drush and use it locally, or should I use install and use it locally?

I globally installed it with Composer, then added C:\Users\Md. Shafiq Hossain\AppData\Roaming\Composer\vendor\drush\drush to the PATH variable.

When I change the current directory C:\My Work2\src\Drupal\clientname\projectname and type `drush version`, it gives me the following error.

> 'C:/Users/Md.' is not recognized as an internal or external command, operable program or batch file

I tried with the project wise. I installed correctly, but `drush version` returns the following error.

> Drush is not recognize as internal or external command

If anyone can help me on this will be great.

# Answer
The Drush 9 documentation is pretty clear: Install Drush locally, in your Drupal site, using composer. You can install Drush Launcher in addition if you want it more convenient.

Without Drush Launcher, you can use the site local Drush be running

```
vendor\bin\drush some-drush-option

```

from your Drupal site root. No need to modify any paths.

If you install the Drush launcher (and use Windows), create a suitable bat file.

NB! Adding `C:\Users\Md. Shafiq Hossain\AppData\Roaming\Composer\vendor\drush\drush` to the path is plain wrong. If you really want to modify the path (to get the convenience of using just `drush` without installing Drush Launcher), the correct path is `[...]\vendor\bin`.
> 2 votes

---
Tags: drush
---


title: Render node from Controller

text:
# Question
Title: Render node from Controller
I have a controller that passes a list of nodes to a template for rendering. I think I'm missing something simple.

I've tried this with no success:

```
public function content() {
  $students = $this->getStudents();

  return [
    '#theme' => 'dashboard',
    '#students' => $students,
  ];
}

private function getStudents() {
  $user = $this->currentUser();

  $nids = \Drupal::entityQuery('node')
    ->condition('type','student')
    ->condition('uid', $user->id())
    ->execute();
  $nodes = Node::loadMultiple($nids);
  return $nodes;
}

```

I have a dashboard theme function:

```
function dashboard_theme() {
  return [
    'dashboard' => [
    'variables' => ['students' => NULL],
    ],
  ];
}

```

And a twig template being called:

```
<ul>
  {% for student in students %}
  <li>{{ student }}</li>
  {% endfor %}
</ul>

```

This blows up the page with the error `Object of type Drupal\node\Entity\Node cannot be printed`, which is no surprise, I'm just not sure what/how to send a proper object to twig.

# Answer
Of course as soon as I posted this I figured an answer. This looks a little ugly, but I guess this is the way to go:

```
public function content() {
  $nodes = $this->getStudents();

  foreach ($nodes as $node) {
    $student = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->view($node);
    $students[] = render($student);
  }

  return [
    '#theme' => 'dashboard',
    '#students' => $students,
  ];
}

```

Basically, I'm looping through the list of nodes, getting the view builder on each, then calling the `render` function and adding it to a new array. I had stumbled on this earlier because I was using `viewMultiple`, which output another array...

If you have a cleaner implementation with `viewMultiple` let me know.
> 5 votes

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


# Question
Title: Setting up Content Synchronization module
# Blanca.Esqueda,

I'm interested in using your Content Synchronization but am having a little bit of problem getting it to run. I'm using Drupal 8 on Acquia Devdesktop, running Content Synchronization 8.x-2.0 using PHP version 7.1.12. The installation instructions is a bit cryptic to me (see image below).

Where do you put this in settings.php? I just appended it to the last lines. But then where is ../content/sync pointing to (see image below)?

After all that I'm getting:

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=17&op=do\_nojs&op=do StatusText: 500 Service unavailable (with message) ResponseText: The website encountered an unexpected error. Please try again later.

I would love to use the Content Synchronization module. Can you give me a hand on this?

Thank you very much for your help, Kai

# Answer
> 5 votes
`$app_root` is the top directory of your website. The one where your `index.php` is located.

Therfore the `../content/sync` is a location like this:

```
- content
    - sync
- public_html
    - index.php
    - (all the Drupal 8 files)

```

To add to that — this is probably done out of security reasons. Not to store your data from DB with the code. Same reasoning was followed for the Config Management core module.

And lastly - you have to make sure there is such a location on your server. Locate index.php, go one directory up and locate or create the `content/sync` path and try again.

---
Tags: 8
---


# Question
Title: How to Pass a Variable to Commerce Order Twig Template
I have located commerce-order-receipt.html.twig in commerce/order/templates/ and I have copied it to my theme directory, properly overriding it. My basic changes all work.

Now I am trying to figure out how to pass my own variable to it. I can't figured out which hook\_preprocess function I need to use in order to do this. I have figured out how the suggestion and original variables were made in commerce\_order.module but this has not helped me hook into it and add more variables.

Can someone point me in the right direction?

# Answer
> 2 votes
I think this should work, in **THEME\_NAME.theme** add

```
function THEME_NAME_preprocess_commerce_order_receipt(&$variables) {
  $variables['test'] = "test";
}

```

<sub>**Note:** replace THEME\_NAME with actual name of theme </sub>

Then doing `{{ test }}` should output "test".

<sub>**Note:** remember to flush all cache to see changes. </sub>

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


# Question
Title: Determine Next Item in DrupalQueue for Drupal 7
I am trying to figure out how Drupal pulls what will be the next item to be processed in the queue for Drupal 7. I have looked at `SystemQueue::claimItem` and I am missing something. I have a queue that jams from time to time and I do not know how to figure out what record it is jamming on.

Thanks, Steve

# Answer
> 0 votes
`SystemQueue::claimItem` has the code you're looking for. https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/function/SystemQueue%3A%3AclaimItem/7.x

You can run the same query that will be used to get the next item in the queue. Just replace `$this->name` in the code below with the queue name.

```
    $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE expire = 0 AND name = :name ORDER BY created, item_id ASC', 0, 1, array(
      ':name' => $this->name,
    ))
      ->fetchObject();

```

`$item` should have everything you're looking for.

---
Tags: queue
---


# Question
Title: How do I add the "error" class when a form validation fails?
I'm working with Drupal 7.56 and I am using the Webform module to create a custom form.

I used `hook_form_alter()` in a custom module to add a validation test.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='webform_client_form_1') {
    $form['#validate'][]='mymodule_form_validate';
    return $form;
  }
}

function mymodule_form_validate($form, &$form_state) {
  $aux = $form_state['values']['submitted']['aux'];
  if ($aux != '') {
    if( /* my test */ ) {
      $text = t('Please check your input');
      form_set_error('aux', $text);
    }
  }
}

```

How can I add the *error* class when my test fails?

# Answer
> 0 votes
First try removing your `if` test and see if you can get the `form_set_error` to trigger. That way you can make sure your test is correct. You should be able to call `form_set_error` in a validation function and it will work.

If that isn't the problem then make sure the name of your field is correct.

To answer the question about simply adding a class in form validation you can use the following: `$form_state['complete form']['aux']['#attributes']['class'][] = 'error';`

It won't add to the input itself but to the field wrapper and you can style it from there. But I think figuring out why `form_set_error` isn't behaving how you want is your best bet. That should really be adding the error class.

---
Tags: 7, webforms
---


# Question
Title: Configuration management and site specific configuration
I have different site environments for my site; dev, test and live site. On dev (local develop) my solr settings are different then on my live environment.

How do I configure site-specific solr configuration, so I am still able to export my configuration from my dev environment (`drush cex`) and import the configuration into my live environment using `drush cim`?

I know there is the config split module. Is this suitable for this, or is there a better solution? I want to controle and export all configuration only form my dev environment. I don't want to use `drush cex` on my live environment. Only import configuration (`drush cim`). The drush command `drush cim` is also implemented in the deploy script.

# Answer
There are multiple ways to override the configuration on a per-environment base.

The config split module is a great tool for splitting complex configurations between the environments. E.g. having some development modules enabled/configured in development, but not installed/no database stored configuration for them in production.

Besides splitting entire module configurations, it also allows you to split single configuration items like parts of your solr settings. You can have them stored in separate configuration folders. These folders can be used as argument when running `drush cim <folder>` to get them re-imported to a site.

However, this kind of configuration management most often is overly complex, when your configuration differs slightly only between your environments (e.g. some URLs, IDs or flags, while other settings keep unchanged).

The better approach for minor differences might be overriding the configuration within your `settings.php`, or even better a `settings.local.php` file, which can be enabled by uncommenting the according inclusion lines at the end of your `settings.php` (given it's based on default.settings.php):

```
/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

```

You can then override your environment specific configuration using the `$config` array in your `settings.local.php`:

```
$config['search_api_solr.settings']['site_hash'] = '...';

```

This will not alter the database stored configuration or the managed configuration imported using `drush cim`. Instead, it will override the database stored configuration during page load. Therefore, it might be wise to having production values stored in your database/configuration management and config overrides for your local and/or staging environments. Once you remove your overrides from your settings file, the database stored configuration (re-)applies.
> 2 votes

---
Tags: 8, drush, configuration
---


# Question
Title: CkEditor Toolbar not available/visible to Administrator when creating content
I am having a strange problem on my local dev site install. When either Basic HTML or Full HTML mode is selected in CkEditor, the toolbar and the whole area where text would be typed, are not available or visible. Yet when selecting Restricted HTML, the area for text and toolbar are visible and available.

This is the only user I have on my site so I am assuming it has full administrative privileges correct?

Where else do I need to change any settings for this user to have access and use Full or Basic HTML along with the toolbar?

The Text formats and editors section have Administrator under the `Roles`column for Full HTML

Any ideas or suggestions of where I am going wrong?

Brand new Drupal user here, obviously.

Semi Reolved.. Found the issue for a temporary fix.. Status Report showed an error for a CodeTag module that was not loaded for some reason. Even though it was installed and enabled with drush. Even showed up in list from `drush pm-list` command so not sure what the deal is with it. Uninstalled it in UI on-site instead of with drush and the editor issues are no more. For what I originally posted.

# Answer
Sounds like you have a ckeditor plugin conflict.

Your symptoms are typical what happens if there are for example a js error on a added ckeditor plugin.

Quick way to confirm is using Firefox Console, it will in most cases flag the offending js for you. Armed with that you can google for a fix or patch.

Alternatively you can turn of the plugins off one by one, but you need to remember to clear your cache, else the offending js could still be there.

So try FF console first and post any extra info you get.
> 0 votes

---
Tags: users, wysiwyg
---


# Question
Title: Comments not showing up when set to open and assigned a region in manage display in drupal 7
I just set my comments for my content type to "open" and assigned the comment field to show up in the full content manage display. But it doesnt show up when viewing in my full display node. I tried changing the theme and it still doesnt show up. How can I debug something like this?

# Answer
My issue was that comments was "CLOSED" for the nodes I already created as the default setting initially was set as "CLOSED". Even thought I set the comment settings to OPEN on the content type, this doesn't affect previously created work.

Solution was to bulk update all the nodes types to open comments with the following sql:

```
UPDATE node SET comment = 0 WHERE type LIKE "MY_NODE_TYPE_HERE";

```
> 0 votes

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


# Question
Title: How to manage multiple drupal 7/8 sites with multiple drush versions
We manage a bunch of Drupal 7 sites and a few Drupal 8 sites. I have been trying to workout the change to Drush 9 on the Drupal 8 sites and I have hit a roadblock.

For some reason when I try to use a local drush alias to contact the site it fails. If fails slightly differently for all the different contexts.

Locally, I have Drush 8.1.15 installed globally with composer, Drush 9.2.1 in my drupal site. I have a yaml alias and a php alias both local and remote.

On the dev server Drush 8.1.10 was installed with the phar download.

```
$ ./vendor/drush/drush/drush @project-client.dev st
Missing argument 2 for Drush\Sql\SqlBase::__construct() SqlBase.php:34                                                                            [warning]
#0  Drush\Drush::getContainer() called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Drush.php:193]
#1  Drush\Drush::service(config) called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Drush.php:238]
#2  Drush\Drush::config() called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Drush.php:274]
#3  Drush\Drush::simulate() called at [/mnt/www/project-client.dev.example.net/repo/vendor/drush/drush/src/Sql/SqlBase.php:221]
#4  Drush\Sql\SqlBase->query(SELECT 1;) called at [phar:///usr/local/bin/drush/includes/environment.inc:393]
#5  drush_valid_db_credentials() called at [phar:///usr/local/bin/drush/lib/Drush/Boot/DrupalBoot.php:462]
#6  Drush\Boot\DrupalBoot->bootstrap_drupal_database_validate() called at [phar:///usr/local/bin/drush/lib/Drush/Boot/DrupalBoot8.php:111]
#7  Drush\Boot\DrupalBoot8->bootstrap_drupal_database_validate() called at [phar:///usr/local/bin/drush/includes/bootstrap.inc:430]
#8  drush_bootstrap_validate(4) called at [phar:///usr/local/bin/drush/includes/bootstrap.inc:507]
#9  drush_bootstrap_max() called at [phar:///usr/local/bin/drush/includes/bootstrap.inc:456]
#10 drush_bootstrap_to_phase(-2) called at [phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php:59]
#11 Drush\Boot\BaseBoot->bootstrap_and_dispatch() called at [phar:///usr/local/bin/drush/includes/preflight.inc:66]
#12 drush_main() called at [phar:///usr/local/bin/drush/includes/startup.inc:458]
#13 drush_run_main(, /, Phar detected. Proceeding to drush_main().) called at [phar:///usr/local/bin/drush/includes/startup.inc:365]
#14 drush_startup(Array ([0] => /usr/local/bin/drush,[1] => --alias-path=/Users/fanderson/.drush/sites,[2] => --root=/var/www/project-client.dev.example.net/current/web/public,[3] => --uri=project-client.dev.example.net,[4] => st)) called at [phar:///usr/local/bin/drush/drush:114]
#15 require(phar:///usr/local/bin/drush/drush) called at [/usr/local/bin/drush:10]
PHP Fatal error:  Declaration of Drush\Command\DrushInputAdapter::hasParameterOption() must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in phar:///usr/local/bin/drush/lib/Drush/Command/DrushInputAdapter.php on line 27
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Declaration of Drush\Command\DrushInputAdapter::hasParameterOption() must be compatible with
Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in
phar:///usr/local/bin/drush/lib/Drush/Command/DrushInputAdapter.php, line 27
Connection to project-client.dev.example.net closed.

```

It looks to me as though it is attempting to run the global drush. How do I stop that? There are Drupal 7 sites on this dev server as well.

# Answer
> 0 votes
I assume the command above is run locally and it connects to the dev server? On the dev server you have the phar-installed global Drush 8 *and* the site-local Drush 9. From the debug backtrace you see that it starts with launching the global Drush 8 and then at the end it uses some functions from the site-local Drush since those are included when Drupal 8 bootstraps. Not strange that it doesn't work. And to make it even worse the: The phar-installed global Drush is too old - Drush 8.14 is clearly needed.

It might work to upgrade the phar-installed Drush 8 to 8.15, but why not use Drush Launcher (which is recommended) and install in globally instead of Drush. It even supports a fallback to a globally installed Drush of your liking.

---
Tags: drush
---


title: Exit pop up with registration form

text:
# Question
Title: Exit pop up with registration form
I want to have anonymous users to have a pop up displayed after they visit first page and moving to second page. The pop up should have a Name and email and after submission user gets registered to our website. I'm confused which existing module can achieve it. I tried using popup module. Or do I have to custom code to achieve it?

# Answer
> 0 votes
If you're looking for a module, try Splashify. Splashify is although not available for Drupal 6. Tinybox can help too but I haven't tried it myself.

You can also create this yourself, simplest way would be to change your front-page in configuration in toolbar, create that page, in drupal template, write something like this:

```
<?php
if (drupal_is_front_page()) {
    ?>
/*Your Splash Screen Code*/
<?php
    }
?>

```

Your Splash Screen Code can be a simple HTML Model, see this Simple Tutorial.

# Answer
> 0 votes
For drupal 8 users, Check this module https://www.drupal.org/project/simple\_popup\_blocks.

Description: Turn any blocks, forms or anything with CSS selectors into popup.

Triggering Methods: Automatic, Manual and Before browser/tab close

---
Tags: forms, 6
---


# Question
Title: Programmatically set active facets on non search page
I'm using facet api with search api and SOLR. This all works as expected.

For non-search pages I use the views facet block and this displays the facets as required.

What I want to do though is have some of the facets pre-selected on non search pages.

For example: I have a views page: example.com/london I would like to show facets with 'london' preselected as if I was on a search page for london.

I've tried using a contextual filter on the views facet block and it half works. It shows only the selected city BUT the facet checkbox isn't checked; and if I click any of the other facets it does not show results filtered by city...

Any suggestions how I can get this to work?

# Answer
> 0 votes
So, despite the overwhelming response ;) after about 20 hours of banging my head against the desk I have this figured. I'm not sure if it is the most efficient way to do this, but I don't think the overheads are massive.

I did end up hooking into the adapter class but I couldn't find a facetapi hook that was called at the right time. In the end, I used `hook_init`.

You will need to get your parameters `($SOME_ID_VARIABLE)` into the code. I used the current URL via `request_path()` and got node IDs from this.

The important bits of the code looks something like:

```
function MY_MODULE_init(){
  $searcher = 'search_api@MY_INDEX';
  $adapter = facetapi_adapter_load($searcher);
  $param_arr = array();

  $param_arr['f'][] = 'field_WHATEVER_FIELD:'.$SOME_ID_VARIABLE;
  $param_arr['q'] = 'VIEWS_SEARCH_PAGE/search';
  $adapter->setParams($param_arr);
}

```

Oh, and you still need to use a views facet block to get the facets to show up on the non-search page. I have used some caching on this block and everything still seems to work as expected.

The info on this page got me going in the right direction.

---
Tags: 7, views, search
---


title: captcha.module error

text:
# Question
Title: captcha.module error
I've just installed recaptcha module and it works fine but I get this error only at the sign up screen (registration screen).

Does anyone know what can I do to fix it??

The error:

Notice: Undefined index: form\_id in \_captcha\_get\_posted\_captcha\_info() (line 604 of /var/www/drupal/sites/all/modules/captcha/captcha.module). Notice: Undefined index: captcha\_info in \_captcha\_get\_posted\_captcha\_info() (line 607 of /var/www/drupal/sites/all/modules/captcha/captcha.module).

Screenshot:

https://image.ibb.co/eYQdhn/Captcha.jpg

# Answer
check if you have installed the latest module(7.x-2.2) and selected the reCaptchas challenge type dropdowns(for the required pages).. I too had error in displaying reCaptchas..Later i figured that i installed old versions.
> 1 votes

---
Tags: 7, theming, debugging
---


# Question
Title: After rearranging field order in a view, how do I export this modification in features?
I am using drupal 7, I rearranged the order of the fields in a view, using the contextual menu link 'raerrange' (see image). But now I am not able to export this modification into the feature related to this view. The feature is still in 'default' status. Which is the feature component that is storing this modification? Which component should I add to the feature?

Any help will be really appreciate.

# Answer
I found out there was no component to add to the feature: the modification was already there even if the feature status didn't change. The field order is stored into the file: 'feature\_name.views\_default.inc'. In order to update the file with the modification, the feature must be 'generated'. (Go to feature --\> recreate--\> advanced options --\> generate feature)
> 0 votes

---
Tags: views, entities, features
---


# Question
Title: Development to staging to production process
I am looking for suggestions on the right way of moving configurations and code from Dev to Staging to the Production environment for Drupal 8 Site. I also need to set up a Reference environment which will be a replica of the production environment but on a server with less resources.

I am using git for code, so it is an easy task to move code changes around.

The site is developed iteratively, hence I need to deliver content types, views and display in an iterative manner to the production site, which will have content already present based on the previous iteration.

I can see some documentation on this topic but all of them are about Drupal 7 or earlier versions.

Any help/suggestions or pointers will be appreciated.

# Answer
This is a good start, drupal 8 has inbuilt configuration import/export functionality: https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration

You could automate/speed up the process abit by adding the exported configs to your git repository and using drush to create them

But its especially: do an export on your dev which will generate config files all zipped up. Then do an import on production which allows you to review the changes before actioning them
> 0 votes

# Answer
Found the solution in the Features module!

https://www.drupal.org/project/features

The video https://events.drupal.org/losangeles2015/sessions/features-drupal-8 is quite useful.

PS: thought this will be of use to someone else in future
> 0 votes

---
Tags: 8, migrations
---


title: Can't install drush8, having drush6

text:
# Question
Title: Can't install drush8, having drush6
I installed drush, and when I do "drush status" it says that my drush version is 6.6.0.

I want to have drush7 instead, so I downloaded it from github, and did following commands:

chmod +x drush.phar

sudo mv drush.phar /usr/local/bin/drush

drush init

I get following error: the drush command init could not be found.

When I do drush status, it still says I have drush6 version... what do I need to do?

# Answer
> 0 votes
Can always install manually

```
# get drush latest 8 version from
# https://github.com/drush-ops/drush/releases
# or any version that you want
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar

# move it to home directory or any other directory
mv drush.phar ~/drush

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bash_profile
# or in some systems
# nano .bashrc

# add this the end of the file
alias drush='/home/your_user/drush'

# use the alias you just setup
source ~/.bash_profile

```

**NOTES:** Above example works in ubuntu but should be similar on other distros

According to the docs drush 8 works with D8, D7 and D6 so no reason to install drush 7

If you want to call it with drush8 use following `alias drush8='/home/your_user/drush'` in `.bash_profile` file

---
Tags: drush
---


# Question
Title: drupal_http_request() returns "Invalid JSON primitive"
I am developing a module for Drupal 7 which calls a remote API. I am using drupal\_http\_build\_query(), drupal\_http\_request(), and drupal\_json\_decode().

My code is as follows

```
$username = $form_state['input']['name'];
$password = $form_state['input']['pass'];

$authurl = variable_get('sgauth_base_url_authenticate', '');
$headers = array('Content-Type' => 'application/json');
$data = array('email' => $username, 'password' => $password);
$query = drupal_http_build_query($data);
$options = array('headers' => $headers, 'method' => 'POST', 'data' => $query);
$result = drupal_http_request($authurl, $options);

dpm($result);

```

$authurl is returning the correct url for the API.

When I look at the returned object I see the following

The request is (Note host, username and password have been hidden)

```
POST /SingPostApi/MobileAuthenticate HTTP/1.0
Content-Type: application/json
User-Agent: Drupal (+http://drupal.org/)
Host: xxxxxxxxxxxx.xxxxxxxxxx.com
Content-Length: 36

email=xxx%40xx.xxx&password=xxxxxxxx

```

Which seems OK

$result-\>code I see a 500 error

$result-\>data shows Invalid JSON primitive: email.

As far as I can tell my code is OK based on my reading of the Drupal API. I don't understand why I am getting the wrong data returned.

When I make he POST request from the Firefox HTTP Requester I get a 200 code and the data I expect to see returned

I would appreciate it if someone who can see where I am going wrong can point me in the right direction.

# Answer
> 0 votes
If your request URL accepts only JSON object data, then you need to pass the value as JSON object, To convert the PHP array/object to JSON object use

```
drupal_json_encode($input);

```

If your request URL's output in the form of JSON object, you need to print the array/value after conveting into a JSON object and you need to add the header as 'application/json'

```
header('Content-Type: application/json');
echo drupal_json_decode($output);

```

---
Tags: 7, http-request
---


# Question
Title: Entity form Submissions automatic numbering over 1000
I have reach an entity form submission count that has hit 1,000.

The problem I have is the URL is '/entityform/1,000' - notice the comma. This screws up the link to the url. I have searched and cannot find how to remove the comma when entityform creates the link.

I have check alias patterns, module settings and every where else I can look within the drupal/module configuration.

Can someone help me figure out where to make this update?

Thank you!

# Answer
Okay after searching it was probably the 12 forum post I found another module that helps with this issue.

Install this module along with Pathauto. https://www.drupal.org/project/pathauto\_entity

The URL Alias is: \[entityform:type:label\]/\[entityform:entityform-id\]

Hopefully that helps someone. Peace
> 0 votes

---
Tags: forms, entities
---


# Question
Title: How to autofill webform with node field data
I have a content type, `applicant` with a `name`, and `birthday` field. I also have a entity reference to a webform, which has a `name` and `birthday` fields, as well as others. I want to allow users to create the `applicant` content type, then click the link to webform, and autofill the appropriate fields on the webform.

I've been trying to use the `FormStateInterface::setValue` method. Here' where I am so far:

```
function mymodule_webform_element_alter(array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  kint($element); // this outputs '#webform_key' => string(4) "name"

  $form_state->setValue('name', 'bob'); // Here I'm just trying to statically set the field.
}

```

This method doesn't actually autofill, and it also doesn't actually set the value. This is a demo-project, so we don't have specs yet, so I'm actually fine with either auto-filling, or setting the value, probably both.

The main thing I'm trying to do here is to link one node entity to a webform submission.

# Answer
Using hook\_form\_alter() or hook\_form\_FORM\_ID\_alter(), you can set the default value by php code

**For Example**

```
function HOOK_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'YOUR_FROM_ID'){
    $form['submitted']['FIELDNAME']['#default_value'] = date("Y-m-d h:i a", time());
  }
}

```
> 0 votes

---
Tags: 8, entities, webforms
---


# Question
Title: Add a configurable text before the webform
I'm working with Drupal 7.

I created a webform content and I want to add a configurable text as an introduction before my form. It's not a textarea. It's just a simple text wich should be configurable from my admin.

I created a block wich contains my text and in **settings** \> **Show block on some pages only** \> I chosen **Only the pages listed** and set my link /content/add\_project

But my text is not displayed.

Any idea please?

Thank you.

# Answer
> 1 votes
You don't have to create a block for it. There is *markup* type field in the webform module you can use it for display informative or configurable text in the webform where you like to show. You can also use HTML for this.

**For Example**

For more details, click here

# Answer
> 0 votes
In drupal 7 when specifying what page to put a block on dont have the starting slash. So if you've got the show on pages as: /content/add\_project

Change it to: content/add\_project

---
Tags: 7, blocks, webforms
---


# Question
Title: How can I programmatically place blocks?
I'm migrating a Drupal 7 site to Drupal 8.

The old site uses `$ drush block_configure` (available in Drush extras) to put blocks in regions while deploying, as well as `$ drush block-disable` to remove unwanted blocks. Unfortunately, Drush extras is no longer available for Drush 8, which seems to be the first version supporting Drupal 8.

The site will be deployed multiple times by multiple people, so adjusting region settings manually in admin view is not a solution. Everything needs to be done in an Ansible playbook so it can be passed on easily.

It seems that **configuration management** can be used to move blocks, but this would require all the environments to have up-to-date copies of a master database. While this is not impossible, it does feel like a hassle and a possible security risk. The developers don't really need to have all production data in their dev environments, and I wouldn't want to put production data on servers using developmental (and possibly vulnerable) code.

**Twig Tweak** seems to have an option to render a block anywhere regardless of regions. However, if I hardcode all blocks on templates, admins can no longer use admin block management.

Would it be possible to write a custom module and use **block alter functions** to set regions on blocks created by core modules? Are there any examples of this?

Are there more ways I'm not aware of? What is the best practice?

# Answer
I was able to accomplish what I wanted using theme config, as described in How to assign blocks to particular regions on theme install? . This solution works for me, because my site will only ever use one (custom) theme, and I don't mind configuring all blocks this way.

I created a config file (this one is for a language switcher, provided by language module) and put it in MYTHEME/config/install/block.block.MYTHEME\_BLOCKNAME.yml. It's just what you would export from configuration management, without uuid.

```
langcode: en
status: true
dependencies:
  module:
    - language
  theme:
    - MYTHEME
id: MYTHEME_BLOCKNAME
theme: MYTHEME
region: header
weight: -6
provider: null
plugin: 'language_block:language_interface'
settings:
  id: 'language_block:language_interface'
  label: 'Language switcher'
  provider: language
  label_display: '0'
visibility: {  }

```
> 1 votes

---
Tags: 8, blocks
---


title: CSS Grid and Drupal

text:
# Question
Title: CSS Grid and Drupal
I'm loving the new CSS Grid feature, but I'm running into a limitation with responsive layouts and how Drupal blocks things together. To explain one use case simply, I have a right sidebar that breaks into two components, a search form and advertising. On tablet and desktop, those should be stacked into the same sidebar. But on mobile, I want to break that search form component out and put it above the content. I put together a wireframe example that shows how things move around. However, when I start to put this together in Drupal (8) with blocks, regions in my custom theme (which I made as a subtheme of classy), Drupal organizes them into nested HTML divs and other elements (ASIDE, MAIN, HEADER, etc). So the question is do I scrap base theming and keep things really really flat, like in the wireframe example, or is there a way to get a sub-element into a parent grid area, or do I need to delve into subgrids?

Thanks!

# Answer
> 4 votes
I'd update theme's `.info` to add a specific region for your search block. It should enable you to make it a normal grid area as all the rest regions and apply all the theming you want.

---
Tags: 8, theming
---


# Question
Title: Submission handler for the user registration form doesn't work
I'm working on a Drupal 7 portal. I added a custom field to the registration form and I would like to get hold of custom field value when the registration form is submitted and before it is stored in the database.

I'm trying to use the submission handler for the registration form and print the content of `$form` and `$form_state`, but those values never get printed as message. I installed the Devel module as well.

```
function user_register_form_submit($form, &$form_state) {
    drupal_set_message('<pre>'. print_r($form, 1) .'</pre>');
    drupal_set_message('<pre>'. print_r($form_state, 1) .'</pre>');
    drupal_set_message(t('An info message from user_register_form_submit'), 'error');
}

```

I appreciate any input on what the issue could be.

# Answer
In `hook_form_alter` use foloowing code

```

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'user_register_form'){
    $form['#submit'][] = 'module_custom_form_submit';
   }
}

```

after that use

```

function module_custom_form_submit($form, &$form_state) {
    // Do whatever you want.
}

```
> 0 votes

# Answer
There are two issues in the shown code.

1. Simply defining a function is not sufficient for Drupal to consider it a form submission handler, not even if the function name ends with `_form_submit`. To add a new form submission handler, the module you are developing needs to implement `hook_form_alter()` or `hook_form_FORM_ID_alter()`, and add a new form submission handler.

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_user_register_submit';
}

```
2. To debug a form submission handler you should use `watchdog()`. Once the *Database logging* module is installed, on admin/reports/dblog you can read all the messages added with `watchdog()`.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: how do I display both a term view and parent terms view on the same taxonomy term page
I am using search api views to override core taxonomy term pages. I would like to create a view that displays parent term content as well like a related content block. Or as a view I can use when results are empty.

I am not able to achieve this so far. I have tried the Parent terms (indexed) filter using every default argument combination I can think of. I have tried the indexed taxonomy terms filter also using every default argument I could imagine. What I assumed would be a very simple views has turned out to be rather complicated. I am starting to wonder if it is actually not a configuration problem at all but related to search api and might not even be possible in the first place.

# Answer
Please follow the steps to show **content of Parent Term on current Term**.

1. Create a view as block
2. Add relationship as **Parent Term**
3. Add contextual filter as **Term ID** using the **relationship** and set it like this
4. Add filter criteria as **Taxonomy Vocabulary** using the relationship
5. Add **fields** whatever you have in taxonomy and use relationship as well

You can also follow the steps in the pics I've created for you.

You don't need to create a new view to show the **content of current taxonomy**, you can set **manage display**. Go to `admin/structure/taxonomy/TAXONOMYNAME/display`

While if you want to display using view, then create another view and follow these steps:

1. Add contextual filter as **Term ID** and set it like this
2. Add fields of the taxonomy you want to show

*Note that we won't use any relationship in this view*

Now, go to in the block configuration `admin/structure/block` and enable these.

I hope this will work for you
> 0 votes

---
Tags: 7, views, search
---


# Question
Title: Same tax for all territories and tax-free products
We're selling registrations to a congress through Drupal Commerce 2 and have been informed by the government of the country where the conference takes place that we have to charge their local tax to all attendees. Our attendees come from all over the world.

Is there a way to configure the Commerce 2 tax module to have it charge the same tax rate to all orders, regardless of where the customer is, other than creating a custom tax type and adding all territories one by one?

We also sell other products and do not want this local tax applied to those products. How would we go about configuring those products so they are not included in the tax calculation?

# Answer
> 2 votes
(Answering my own question.)

I ended up not using Commerce's Tax module but coding my own. I added a "Taxable" field to products and created an **Order Processor plugin** to calculate the tax amount and add it to orders as an adjustment.

It took much longer to figure out how to do it than to actually do it.

---
Tags: 8, commerce
---


# Question
Title: Drupal Common's 3 How To Edit The Commons Browsing Widget Tabs?
In Drupal 7 Common 3

Browsing Widget Tabs https://drupal.org/project/commons\_bw

Want to remove the Wiki's Tab How can I do this please?

Many Thanks for your help

# Answer
> 2 votes
If you specifically need to remove the *Wiki's Tab* instead of turning off **Commons Wiki module**, none of the functions to override has been set up as a hook, as far as I can understand.

So even if the following method is not the best approach, you could make a very quick patch to commons\_bw.module :

Into `function commons_bw_get_tab_definitions($widget_type = 'group')`

add `unset($tabs['commons_wikis']);` before `return $tabs;`

Of course you'll have to remember this whenever you update your Commons distrib...

See also this great post on how to add your own content type to the **Commons browsing widget**. This will give you a complete overview of what you can do

# Answer
> 1 votes
You can disable the tabs at this address \[yoursite\]/admin/config/user-interface/commons-browsing-widget-user-interface.

# Answer
> 1 votes
You can use https://www.drupal.org/project/commons\_bw\_ui. This module provides a user interface that allows you to disable, remove or add new tabs.

Commons Browsing Widget User Interface comes with a number of useful features:

* Greatly simplifies the process of adding, altering or removing browsing widget tabs.
* Provides configuration options for all tab settings including: title, weight, view, display and bundle.
* Allows the default browsing widget tab settings to be overridden.
* Automatically configures content types for proper integration with Commons (adds fields, enables title replacement, etc.).
* Configuration is fully exportable.

---
Tags: 7
---


# Question
Title: How to remove a term programmatically from entity reference field using entity browser on translation form?
I have a content type "Articles", this is a multi-language site, by default the content is created in English, and then translated into Spanish. On new article in English, I set a title and a term for the "Category terms" field, this field is an "Entity Reference", and I'm using "Entity Browser" to show terms from a view (they are a lot of terms), when I create a translation from English to Spanish I need to remove any term related to "Category terms" field. I have tried a couple of ways, but this is not working for this field.

Here is the hook code that I'm using.

```
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Form state object double check.
  if (is_object($form_state) && method_exists($form_state, 'getStorage')) {

    $form_storage = $form_state->getStorage();

    // Temporal condition to avoid unexpected results while developing
    if ($form_id == 'node_articles_form') {

      // Check if form is a translation.
      if (isset($form_storage['content_translation'])) {

        // Hard coded test to override title - This works.
        $form['title']['widget'][0]['value']['#default_value'] = 'Forced title text translation';

        // Hard coded test to override Meta Search Terms - This doesn't work. Is not applyed
        $form['field_category_terms']['widget']['entity_browser']['#default_value'] = [];

        // Removing completely the field - This is not a solution, only for test.
        // unset($form['field_category_terms']);

        // Removing data from "Callback Object"
        $build_info = $form_state->getBuildInfo();
        // Getting the entity
        $entity = $build_info['callback_object']->getEntity();
        // Removing terms from entity
        $entity->field_category_terms = [];
        // Setting the entity
        $build_info['callback_object']->setEntity($entity);
        // setting a modified callback object to the $form_state
        $form_state->setBuildInfo($build_info);

        // Removing target_id default value.
        unset($form['field_category_terms']['widget']['target_id']['#default_value']);
      }
    }
  }
}

```

# Answer
> 0 votes
To remove them from the user interface, you would have to empty the items array of 'current'

`$form['field_category_terms']['widget']['current']['items'] = [];`

This would however only hide them in the user interface, to actually remove them you also have to NULL `target_id`

`$form['field_category_terms']['widget']['target_id']['#default_value'] = '';`

If the users are allowed to add new terms during the translation, you'd also need to make sure the emptying of the terms only are done initially, because if not, they would always appear empty since Entity Browser uses AJAX and change the form when you add a new term. Something like:

```
  if (!$form_state->isProcessingInput()) {
    $form['field_category_terms']['widget']['target_id']['#default_value'] = '';
    $form['field_category_terms']['widget']['current']['items'] = [];
  }

```

---
Tags: 8, forms, taxonomy-terms, i18n-l10n
---


# Question
Title: How do I display a view pane with all items of a category?
I created an Events content type. I created a vocabulary that has two category terms, Events and Plays.

I have a view that contains a list of all content of type Events.

Each Events listing displays with the category term as the title/link.

The link should go to a page that has a content pane containing a list of all of the Events with that tag.

So, the view looks something like,

**Movie** (term)

movieName

movieTime

**Play** (term)

movieName

movieTime

**Movie** (term)

movieName

movieTime

**Play** (term)

movieName

movieTime

**Movie** (term)

movieName

movieTime

The term field is configured to be a link.

If I click on **Movie** or **Play** I want to go to a page that has a content pane containing a list of all of the Events tagged with Play or Movie, depending on which I clicked.

On the view, I set up a Contextual filter:

Content: Has taxonomy term ID

I set up a Relationship:

Content: Taxonomy terms on node

How can I set up this view so that clicking on the category will take me to another page with a view/content pane that displays a list of Events based on that tag?

# Answer
> 0 votes
First you will need to have the views page that displays all the Events for the tag you want, then it should be a matter to rewrite the Link field to output as a link that point to that page you had created.

**FOR THE PAGE:**

1. Create the page using views that will filter all Events with category Terror
2. In the URL make it the exact TERM you will have in the list you need, i.e. www.yourwebsite.com/TERROR
3. Save

**FOR THE LIST:**

1. Create the block/page view you need with the list
2. You need to add the field TERM again (it should appear twice, one above the other, rearrange if not).
3. In the first TERM FIELD check the box for **Exclude from display**
4. On the second one, go to **Rewrite Results \> Output this field as a link,** check that box
5. In the text field that appears, enter the replacement pattern for the first TERM FIELD, something like \[field\_term\].

That will render your TERM as a link to the TERM page, that will contain all the events for that term. If not, place a link so I can help you.

# Answer
> 0 votes
There are two scenarios here:

1 If your terms were exclusive to the events content type: Then you just make the terms linked -- they should provide what you need... it would display a list of content tagged with move or play. You then don't need to set up the contextual filter.

2 If your terms were NOT exclusive to the Event content type: Then you would need to need to change the link of the taxonomy term to point to a views page with the Contextual filter (it can be the same views page or a different one). The easiest way to do that is to just use the tag ID.

You'd make the taxonomy term in the views fields output as plain text, and then use "Output this field as a link" under "rewrite results" to make it link to "your-view-path/\[field\_tags-tid\]"

Your title on the page can be Events %1 and that should change as well when the user clicks on a movie or plays.

I don't think you need the relationship here in either case.

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


title: Separate domain for a single language

text:
# Question
Title: Separate domain for a single language
I have a website with three languages (Polish, English, and French) with English being the default. English and French should use a URL like domain.com/en and domain.com/fr; Polish should use a separate domain, domain.pl.

How can I achieve this? I've seen suggestions to use `hook_language_negotiation_info()`, but it's not working for me at all.

# Answer
This is can be done using TMGMT, from the TMGMT domain setting you can set up configuration per domain. You can also check out this module =\> https://www.drupal.org/project/domain\_site\_settings
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Update existing node (not created by Migrate) via Migrate 8.5.x
I have got existing Drpal 8.5 site with hundreds of nodes. With migrate, if i try to upgrade, new nodes are rather created. Node have a field which is being used as key however that seem to be not working. It seems that node are only updated if their record present in migrate\_map\_xyz. Any suggestions?

# Answer
Updating existing content was possible by changing the default behaviour of a migration with the system of record concept in **Drupal 7**.

In **Drupal 8** this concept has been revised & is available with the `overwrite_properties` option in the destination of the migration YAML:

```
...
destination:
  plugin: 'entity:node'
  # define the entity properties that are to be updated.
  overwrite_properties:
    - title
    - field_foo
    - field_bar
...

```
> 1 votes

---
Tags: migrations
---


# Question
Title: How do I display category items in a view content pane?
I created an Events content type. I created a vocabulary that has two category terms, Events and Plays.

I have a view that contains a list of all content of type Events.

Each Events listing displays with the category term as the title/link.

The link should go to a *page that has a content pane* (not a view page) containing a list of all of the Events with that tag.

I already have a page set up with two columns. When I click on any term in the list of Events, I want to navigate to this page (or an iteration of it, based on term selection), and one of the columns should contain the view pane with the view of events of just that category that was clicked on.

In other words, I want the destination of the term links to be a page containing the content pane of items of that category (i.e. not just a page view.)

So, the view looks something like,

**Movie** (term)

movieName

movieTime

**Play** (term)

movieName

movieTime

**Movie** (term)

movieName

movieTime

**Play** (term)

movieName

movieTime

**Movie** (term)

movieName

movieTime

The term field is configured to be a link.

If I click on **Movie** or **Play** I want to go to a page that has a content pane containing a list of all of the Events tagged with Play or Movie, depending on which I clicked.

On the view, I set up a Contextual filter:

Content: Has taxonomy term ID

I set up a Relationship:

Content: Taxonomy terms on node

How can I set this up so that clicking on the category will take me to another page with a column containing a view content pane that displays a list of Events based on that clicked tag?

# Answer
> 0 votes
Try this...

1. In your view that displays movies and plays, add the term id (tid) to the list of fields.
2. Rearrange your fields so that the tid field is above the term name field.
3. In the tid field settings, check `Exclude from display.`
4. In the settings for the term name field, check `Rewrite the output of this field`. In the text box underneath, enter this:

`<a href="path-to-page-with-content-pane/[placeholder1]">[placeholder2]</a>`

Expand the `Replacement patterns` section of the dialog box to see what to insert in place of `placeholder1` and `placeholder2`. Click Apply to close the dialog box, then save your view.

Now, in your content pane view, you simply have to match up the contextual filter with the tid. One way to do that is in your contextual filter settings, click the `Provide default value` radio button, select `Raw value from URL` from the dropdown, and set the path component to match where placeholder1 appears in the link generated in your other view.

This is the simplest way to do it and it has some limitations (e.g. a non-intuitive Url) but hopefully is enough to get you on the right track. One you're comfortable with it you can experiment with different arguments and different ways to pass them. The link below has a good description of how to use contextual filters:

https://www.metaltoad.com/blog/using-drupal-contextual-filters-views

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


# Question
Title: Find target bundle(s) for a specific entityreference field
I am creating a simple administration page that shows all content types and some details about each content type field.

* I am getting the list of content types with `node_type_get_types()`
* I am getting the list of fields with `field_info_instances()`

When the widget module is `entityreference` I'd like to display the target bundle(s) of that entity reference field.

```
foreach(node_type_get_types() as $value) {

  $fields = field_info_instances('node', $value->type);

  // Loop through fields
  foreach($fields as $field) {

    if ($field['widget']['module'] == 'entityreference') {

      // Get the target bundle(s) for this field
    }
  }
}

```

Thanks in advance for any help on that!

# Answer
Nevermind. I found a solution. I can get them with `field_info_field()`:

```
foreach(node_type_get_types() as $value) {

  $fields = field_info_instances('node', $value->type);

  // Loop through fields
  foreach($fields as $field) {

    if ($field['widget']['module'] == 'entityreference') {

      // Get the target bundle(s) for this field
      $field_info_field = field_info_field($field['field_name']);
      $target_bundles = $field_info_field['settings']['handler_settings']['target_bundles'];
    }
  }
}

```
> 1 votes

# Answer
Drupal 8 version:

```
$bundles = \Drupal::entityManager()
->getAllBundleInfo()['node'];
 foreach ($bundles as $id => $value) {
 $node_fields = \Drupal::entityManager()
  ->getFieldDefinitions('node', $id);
   foreach ($node_fields as $field) {
      if ($field instanceof \Drupal\field\Entity\FieldConfig) {
        if ($field->getType() == 'entity_reference') {
          $target_bundle = $field->getSettings()['handler_settings']['target_bundles'];
          kint($target_bundle);
        }
      }
    }
  }

```

With `$target_bundle`, You can do something like this as well to filter out a specific bundle:

```
if ($target_bundle != null && key($target_bundle) == 'mybundle'){
  kint($field->id());
}

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Node/add form don't working from page template
I put the node/add form in the page.tpl file:

```
module_load_include('inc', 'node', 'node.pages');
$form = drupal_get_form('my_page_node_form', $node);
print drupal_render($form);

```

It is perfectly added and output in accordance with form\_alter() function. The idea is that an anonymous user can create a node from custom page. From a 'node/add/my\_page' page, this functionality works. But the other page does not work. My form\_alter() for this:

```
  $form['title']['#access'] = user_access('administer my page node title');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#weight' => 50,
    '#submit' => array('node_form_submit'),
  );

```

I do not see anything in the logs, and I do not see any messages. Why is it not saved?

# Answer
> 0 votes
Then just use hook\_node\_submit() into your custom module. https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_submit/7.x

(i.e)

```
function modulename_node_submit($node, $form, &$form_state) {
   if($node->type == 'node_machine_name'){
      //you code..
   }
}

```

And also if your submit button does not work then don't render submit button instead use drupal\_render\_childern()

```
<?php print drupal_render_children($form); ?>

```

Thank you.

---
Tags: theming, nodes, forms
---


# Question
Title: Create hook menu with custom module (child/%)
In my custom module I want to create menu with the name "**child/%**" is it possible. When I create menu "**child/test**", whenever I load the page http://localhost/project/child/test it gives error page could not found. so if I run http://localhost/project/%E2%80%8Bchild/test like this it is working. Its confusing, Kindly clarrify.

Thanks, John.

# Answer
try to follow this code

```
<?php
/**
 * Implements hook_menu().
 */
function example_menu() {
  // In this example, the third parameter will be passed.
  $items['admin/example/%'] = array(
    'title' => 'Example of first parameter being passed',
    'description' => 'This has a page arguments index of two because the wildcard occurs at the 3rd parameter',
    'page callback' => 'one',
    'page arguments' => array(2),
    'access arguments' => array('access administration pages'),
  );
  // The third and fourth parameters are being passed, hence we need to create an array with values 2 and 3 for the page arguments key
  $items['admin/example/%/%'] = array(
    'title' => 'Example of multiple parameters being submitted',
    'description' => 'Example of multiple parameters being submitted',
    'page callback' => 'two',
    'page arguments' => array(2, 3),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

/**
 * One parameter being passed.
 */
function one($one) {
    return $one;
}

/**
 * Two parameters being passed.
 */
function two($one, $two) {
    return $one . ' ' . $two;
}

```

Thank You.
> 0 votes

---
Tags: hooks, navigation
---


# Question
Title: How to have SimpleSaml create a new account only when the user doesn't have a Drupal account already?
I'm new to Simplesaml...I feel like I'm missing something obvious in the configuration. Could someone point me in the right direction?

Drupal - 7.53

simpleSAMLphp Authentication - 7.x-2.0-alpha2

# Answer
> 1 votes
We have this setup running, and it does not register a new user each time but only the first time a user logs in, as expected. I just remember running into problems when unique identifier and user name where set to different values (my old bug report is possibly related). To further manage the displayed user names you could use Drupal modules like RealName.

## configuring SimpleSAMLphp\_auth to register new users

In the admin interface, navigate to admin/config/people/simplesamlphp\_auth

Under the tabs

```
USER PROVISIONING
check - Register users (i.e., auto-provisioning)

```

and

```
USER INFO AND SYNCING
Which attribute from simpleSAMLphp should be used as user's name *
eduPersonPrincipalName

```

(enter an attribute that uniquely and consistently identifies the user in your realm and that your SAML IdP provides, some attributes change with each invocation and are therefore not suitable, eduPersonPrincipalName is suitable for most educational entities, email could also work fine here)

```
Which attribute from simpleSAMLphp should be used as unique identifier for
the user *
eduPersonPrincipalName

```

(enter an attribute that uniquely and consistently identifies the user, make sure to use the same attribute as in user's name before)

From the documentation:

> Determines wether or not the module should automatically create/register new Drupal accounts for users that authenticate using SimpleSAMLphp. Unless you've done some custom work to provision Drupal accounts with the necessary authmap entries you will want this checked.

## Checking which SAML attributes are available

Navigate to the admin interface of your simplesamlphp install (you might need to activate the interface and look up the password of the install from config.php). navigate to the Tab Authentication and "Test configured authentication sources" (/module.php/core/authenticate.php), log in **to the same authentication source** that is configured in the drupal plug-in under "Autenticaton source for this SP (default: default-sp)" and an overview of all SAML attibutes for that user will be displayed.

The attributes that can be used are possibly best obtained from the documentation of the identity provider, example: https://www.feide.no/attributelist

# Answer
> -1 votes
You may need to write something custom to handle this--I don't think the out-of-the-box config will take care of it. As you've probably experienced, when you have "Register users" checked (under User Provisioning), that will create a new account for every new SimpleSAML login--even if it is duplicating an existing Drupal user's email address or other user information.

Based on the help text there, I think you'll need to write something custom (probably checking the authmap entries before provisioning the account):

From the config page (admin/config/people/simplesamlphp\_auth)

> Unless you've done some custom work to provision Drupal accounts with the necessary authmap entries you will want this checked.

It looks to me like you'll need to provide authmap entries for your existing Drupal accounts, and then you can write a check for SimpleSAML. But that is theory; I've never tried to do what you're looking for. Hope this helps.

---
Tags: 7, users
---


# Question
Title: Form states expanded or collapsed not working
I cannot get this to work. Visible/Invisible works for me but this doesn't. Have I misunderstood anything?

```
    $form['items']['delivery_address'] = array(
    '#type' => 'fieldset',
    '#title' => '',
    '#collapsed' => true,
    '#collapsible' => true,
    '#states' => array(
        'expanded' => array(
            ':input[name="add_address"]' => array('checked' => false),
            ':input[name="delivery_type_radios"]' => array('value' => 0),
        ),
    ),
);

```

# Answer
> 0 votes
This makes it work:

```
   '#title' => 'bleh',

```

It kinda makes sense...

---
Tags: 7
---


# Question
Title: Display/Hide node page as modal with drupal_goto or similar way
I want to display a node page I built inside a modal or overlay and be able to open/close the modal with simple commands.

That is without the need of an html element like clicking a link like I've seen in some examples just using something like: drupal\_gotto($url. ?open/?close) so that I could call it inside a rule.

Also I might need to open a modal on top of another modalpage.

# Answer
> 0 votes
I did it with Overlay Paths module but it was not working as I expected, I had to do these things:

1. drupal\_goto(current\_path(), array('fragment' =\> 'overlay=path-alias'));
2. Non-admin overlay paths: \*path-alias

check here for more

---
Tags: 7
---


# Question
Title: Module always returns the default language in hook_theme()
I am developing a custom block that shows a different image URLs for different languages. Currently, I enabled English and French.

The code I am using is the following one.

```
function MODULENAME_theme($existing, $type, $theme, $path) {
    $currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
    $imageUrl = "";
    # If current language code is english
    if ($currentLangCode == "en") {
        $imageUrl = "English image url"
    } elseif ($currentLangCode == "fr") {
        $imageUrl = "French image url"
    }
    return [
       "modulename_block_template" => [
            "variables" => [
               "description" => [],
               "image" => $imageUrl,
               "current_language" => $currentLangCode
            ],
       ],
    ];
}

```

The problem is that the value for `$currentLangCode` is always `'en'`.

What can I do to get the current language?

# Answer
Data from `hook_theme` is cached, any logic decisions you make in it will only apply when the theme registry is rebuilt.

The point of variables is that they're passed in at the time the theme is called, not when the theme hook is declared.

For example `hook_theme()` should look like this:

```
MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'modulename_block_template' => [
      'variables' = [
        'description' => '',
        'image' => '',
        'current_language' => '',
      ],
    ],
  ];
}

```

And you pass the variables in when you use it:

```
$currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
$imageUrl = '';
# If current language code is english
if ($currentLangCode == "en") {
    $imageUrl = "English image url"
} elseif ($currentLangCode == "fr") {
    $imageUrl = "French image url"
}

$build = [
  '#theme' => 'modulename_block_template',
  '#description' => '...',
  '#image' => $imageUrl,
  '#current_language' => $currentLangCode,
];

```
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Unable to install the Cloudinary Integration module
I downloaded the Cloudinary Integration module and installed it.

The module appears in the module list, but I cannot enable it. The modules page shows this message after the description of the module.

> Requires: Cloudinary Stream Wrapper (disabled), Cloudinary SDK (disabled), Libraries (missing)

# Answer
> 1 votes
You haven't installed the dependencies.

They're listed on the module page:

> **Requirements**
>
> * Libraries
> * Cloudinary SDK for PHP
> * Cloudinary API Account

Download each of those as well, then try again.

---
Tags: 7
---


title: Create a template for a specific view

text:
# Question
Title: Create a template for a specific view
I have a view containing an unformatted list of fields. I want to create a specific template for the view. I have turned on Twig debug, but it suggests 'views\_view\_unformatted' for the file name, which would apply to all unformatted lists, but I want it specific to this view. What should be file name be?

# Answer
> 5 votes
I think the issue here is that Twig debug does not suggest all possible names.

Names containing the view display id or type are possible, but don't seem to be suggested by Twig debug.

The following are the possible template names sorted by precedence:

```
[base template name]--[view machine name]--[view display id].html.twig
[base template name]--[view machine name]--[view display type].html.twig
[base template name]--[view display type].html.twig
[base template name]--[view machine name].html.twig
[base template name].html.twig

```

# Answer
> 1 votes
To create template for view use following naming convention :

**views-view-fileds--views-name--page/block.html.twig**

Use page if you are creating template for page view and block for block view

Hope this helps :)

# Answer
> 1 votes
I searched for a while till I finally found the solution in the Drupal API:

https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views\_templates/8.2.x

So the correct filename for your case would be:

```
views-view-unformatted--[view machine name]--[display].html

```

Like for example:

```
views-view-unformatted--frontpage--page.html

```

# Answer
> 0 votes
to be more precised with underscore and comma

* get the view machine name and display name from url

> /admin/structure/views/view/event\_related/edit/page\_1

* then the template name would be

> ```
> views-view-fields--event_related--page-1.html.twig
>
> ```

* for all display of type page for that view:

> views-view-fields--event\_related--page.html.twig

---
Tags: theming, 8
---


# Question
Title: Custom Gallery images showing in one column
In Drupal 7, I have created a custom gallery, but all images are showing in only one column.

I have Bootstrap theme for Drupal. I'm using the modules Views (Bootstrap), Colorbox, Multiupload Imagefield Widget, Multiupload Filefield Widget (both for multiimage uploads).

Steps I took:

1. I created a new content type Gallery
2. Added an image field to the content type and selected multiload (to enable upload of several images at once)
3. Removed body field as I only need images.
4. Image display has been set to Colorbox (I previously created different image styles - preview, full, etc.)
5. In Views, I created a new page Galleries, which contains all galleries that I have on the site. I had no problems putting those Galleries in a 4 column layout. So basically this is a Albums view.

My problem is that when I click on Album name, a new page (of content type Gallery) opens. It contains all the images of the particular album. However, all the images are shown in only one column.

I have tried to change the layout with panels and display suite, but as Images are considered as one field, the end result stays the same. Is there any way I could change the steps I took and do this differently, so I could have the Gallery with listed Albums as I have now, and then when I click on albums the images are shown in 3 or 4 column layout?

Thanks

# Answer
> 0 votes
Its has multiple ways to do that but I recommend you to do it with **views**.

Create a new views as block view and follow the following steps:

1. Add image field in **fields**
2. Add filter criteria
3. You can change the **FORMAT** of the views as you like (according to your requirement you should select **Grid type**) to display images in multiple columns.
4. Add a contextual filter with **nid** (node ID) field and set it like this
5. Save the views and go to `admin/structure/block` and enable your block
6. Don't forget to **hide the image field in the manage display of Gallery Content Type**, path is `admin/structure/types/manage/CONTENT-TYPE/display`

**Image as Example**

For more details, click here

---
Tags: theming, media
---


# Question
Title: After submission of a webform block how to replace that webform block with thank you message in the same page?
I have created a webform block and assigned to a page in the right sidebar. After successful submission of that block, I want the thank you message with the values submitted in the webform to displayed where block was there before in the same page.

I have given **no-redirect** option in the **form settings** of the **webform**.

Also in the **block settings** of the webform block given **view mode** as **form only**.

But how would I replace the webform block with thank you message on successful submission of webform in the same page? **Is there any Drupal way to achieve this. Have I missed any settings** ??

Any help will be much appreciated.Thanks in advance.

# Answer
If you have the webform set as a block, you can go to admin \> structure \> block. Look for your webform block. It should be named something like **Webform: 'name of webform node'**. Click on the configure link to the right. When the edit form for the block loads, look for the section **Confirmation message**. Select the option **Display the confirmation page in the block on the same page (no redirect)**. Now when you submit the form from the block, it will redirect back to it and show the confirmation message on reload.

You may need to fill out a message in the webform settings. I have attached an image of the edit block page for you to compare.
> 1 votes

# Answer
This is sort of hacky but I couldn't figure out a way to do it with Webforms natively. This implementation uses a custom module.

// Register custom module block

```
function my_module_block_info() {
  $blocks = array();
  $blocks['my_form'] = array(
    'info' => t('My Form Title'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

```

// set block content

```
function download_training_plan_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'my_form':
      $block['subject'] = '';
      $block['content'] = my_form_details();
      break;
  }
  return $block;
}

```

// set block theme

```
function my_form_details() {
  return theme('my_form_details');
}

```

// use custom template file.

```
function download_training_plan_theme() {
  $template_path = drupal_get_path('module', 'my_module_template_file') . '/templates';
  $theme_hooks = array(
    'my_form_details' => array(
      'path' => $template_path,
      'template' => 'Altered form',
      'variables' => array('title' => NULL),
    ),
  );
  return $theme_hooks;
}

```

// when webform is used, alter form to include callback function

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->title == 'Obstacle Teaser 2018 Data Capture'){
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'my_form_callback',
        'wrapper' => str_replace('_', '-', $form['#form_id']),
      ),
      '#value' => t('Submit'),
    );
  }
}

```

// set cookie to remember submitted state and show hidden content

```
function my_form_callback(&$form, &$form_state) {
  if (!form_get_errors() && $form_state['values']['details']['sid']) {
    // Save cookie.
    setcookie('is_submitted_cookie', TRUE, REQUEST_TIME + (31556926 * 2), '/');
    $commands = array();
    $commands[] = ajax_command_invoke('#secret_content', 'show'); //show hidden content
    return array('#type' => 'ajax', '#commands' => $commands);
  }
  return $form;
}

```

// in file: my\_module\_template\_file.tpl.php

```
        <?php $download_form = module_invoke('webform', 'block_view', 'client-block-999999'); ?> // replace 999999 with nodeID of webform.
        <?php if (!empty($download_form['content'])): ?>
          <?php print render($download_form['content']); ?>
        <?php endif; ?>
<div id="secret_content" style="display:none;"><a href="#">Download content</a></div>

```
> 0 votes

# Answer
Enable Webform AJAX module, install it. To configure:

* Go to your Webform's Form Settings
* Check AJAX mode
* and then check on Show confirmation screen
* And make sure you select No redirect (reload current page) under Redirection location.
* Add some text in Confirmation message textarea.

And when you submit the webform you will see Confirmation message instead of the webform.
> 0 votes

# Answer
Goto your Webform Form Setting & add your Confirmation message.

**Confirmation message :** Put your message in this field.

**Redirection location :** Check "Confirmation Page"
> -1 votes

---
Tags: 7, webforms, forms
---


# Question
Title: How to name views-exposed-form.tpl.php per views display
I tried `views-exposed-form--"view_name"--"display_name".tpl.php` but it doesn't work. Is it possible to make a template file which applies only to the exposed filter of a views display?

I have two exposed filters from two different displays within a same view, and I would like to theme the two exposed filters differently by two template files.

# Answer
Everything is possible in Drupal ;)

Probably Views does not automagically provide template suggestions for the exposed filter, like it does for the fields themselves. So you will need to do a little bit more work for this one:

1. Use the the devel\_themer module to find out what function/template is theming that exposed filter.
2. Create a *preprocessor* for that theme function/template. In your preprocessor you can then insert dynamic template suggestions that will fire off based on any condition you want. You can create this preprocessor either in your custom theme's template.php file or in one of your custom modules. This D.O. article will guide you with creating the dynamic template suggestion.

I will assume that you will be displaying different Views displays based on a URL path. If this were the case, then you can use Drupal's `arg()` function in your preprocessor to figure out what is the View display that you are currently displaying, and construct your template suggestion using that information.

Once you've setup your suggestions properly, then Drupal would automatically call the appropriate template and voilá, you have different filter templates based on the path (or any other condition that you specify in your preprocessor).
> 2 votes

# Answer
For Drupal 7, you can use views-exposed-form--view\_name--display\_name.tpl.php (Replace underscores with dashes in view name and display name.)

It worked for me that way.
> 25 votes

# Answer
in drupal8

> /admin/structure/views/view/event\_related

would be

> views-exposed-form--event\_related.html.twig
> 3 votes

# Answer
For drupal 8, theme debug mode does not display the available template suggestions. You can find out which ones are avaliable using kint() or create new ones in this hook:

```
/**
 * Implements template_theme_suggestions_node_HOOK_alter().
 * Add theme suggestions to the view exposed forms.
 */
function YOUR_THEME_theme_suggestions_views_exposed_form_alter(&$suggestions, $vars, $hook) {
  kint($vars['form']['#theme']);
  //$suggestions[] = 'views__exposed__form__' . $anything;
}

```
> 1 votes

---
Tags: views, theming
---


# Question
Title: Shared subset of users in a multi-site instance
Can I have a shared subset of users in a multi-site instance? In other words, I have the same list of administrators across all sites. Can these administrators be admins for all sites through a shared database rather than producing the same list of admins for each site?

* I am aware that each site in a multi-site instance has its own database, which contains content and users specific to said site.
* I am aware that content and users can be shared by configuring a shared database. However, I only want to share administrators among sites and keep content and other users with site-specific roles and permissions specific to its respective site.

# Answer
> 1 votes
As you mentioned yourself you can share users across multiple site but that are **all** users. So you need an external 'database' for your admin users that magically exists for all sites.

For this you could use https://www.drupal.org/project/ldap which could contain you administrators.

Normal users can login as normal aka without use the LDAP directory.

Note LDAP can work with MS Active Directory too.

# Answer
> 1 votes
You might be able to use what Drupal.org uses(d?), the bakery module. This requires the sites to be on the same sub-domain by default.

---
Tags: 7, users, multi-sites
---


title: Theming a table '#type' vs '#theme'

text:
# Question
Title: Theming a table '#type' vs '#theme'
I am dynamically rendering a table in a Drupal 8 module. While creating my renderable array I noticed that I can define my table as a `'#theme' => 'table'` or as `'#type' => 'table'`.

```
$variables['test_table'] = [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class'=>array('my-table')),
    '#header_columns' => 4,
];

```

vs:

```
$variables['test_table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class'=>array('my-table')),
    '#header_columns' => 4,
];

```

Both of these options seem to output the same thing.

My question is this: Why can I use either `'#theme' => 'table'` or `'#type' => 'table'` when defining a table renderable array and is there any difference between how Drupal will render these differently.

# Answer
I believe ultimately both will do the same thing. But when you use 'type' you are referring to what drupal element to use (see https://api.drupal.org/api/drupal/elements) and when you use '#theme' you're directly telling it what twig template to use.
> 4 votes

# Answer
As Matt already said, the advantage of using `#type` is that you can have standard render array children instead of using #rows, which you shouldn't use with #type but works because it's basically just a wrapper that eventually uses \`'#theme' =\> 'table' internally.

That allows to put form elements inside a table. In 7.x, this was always a pain that required custom theme functions to reshuffle a form structure back into something that the table template understands.
> 3 votes

---
Tags: 8, theming
---


title: I don't see Views Theme Suggestions

text:
# Question
Title: I don't see Views Theme Suggestions
For some reason I don't see the views theme suggestions in my twig debug information? What do I miss?

* In my development.services.yml in set debug to true.
* I do see debug information and theme suggestions from other page items.
* I do see views debug info but not the theme suggestions. See image below:

On other website I see suggestions like this:

# Answer
This is a bug in Drupal 8 core, currently being worked on in several different core issues, many of which have working patches.

If you need the functionality now, you have two options:

1. Try the patches from comment #22 (or more recent) on Issue #2923634 and the patches on Issue #2752443. Read the comment thread on #2923634 to get a full understanding of what's going on here.
2. Or use the well-vetted patch from comment #139 on Issue #2118743 which has been postponed in favor of option 1 above.

I'm using the patch from option 2 (#2118743) successfully. Please note that this does go against the standard core contributor recommendations. But the reason is because #2118743 has a single, well-vetted and working patch for something that is only enabled / used during development, and instead of needing to test out various combinations of two separate patches that are still under development. Once the better solution (#2923634 and #2752443) get fixed in core, #2118743 should be obviated and no longer required.
> 16 votes

# Answer
You can see that you get views-view-fields.html.twig for example, the naming conventions is then:

* views-view-fields--foobar--page.html.twig
* views-view-fields--page.html.twig
* views-view-fields--foobar.html.twig
* views-view-fields.html.twig

From: https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views\_templates/8.2.x

In case you have a custom news feed it would look like this:

**views-view-fields--news-feed.html.twig**

where **news-feed** is the machine name of the view.

You can copy the default templates in the stable theme in core to have something to start building from.
> 2 votes

---
Tags: views, 8
---


# Question
Title: how do I return a count of items returned from an entityfieldquery
Is it possible to return a count of the number of items returned in an entityfieldquery query?

# Answer
> 18 votes
if you just want the count then you could set the query to count.

something like

```
$count = $query->count()->execute()

```

See here for more detail

# Answer
> 0 votes
If required you might as well try Field Count Formatter It will display the number of item in a multifield

---
Tags: 7, database
---


# Question
Title: Install Webform on Drupal 8 : checkboxes greyed out
(Pretty much a Drupal newbie here)

I'm having difficulty completing he installation of "Webform version '8.x-5.0-rc3 released 4 February 2018'" on Drupal 8.4.5 on a development box running Windows 10.

My Webforms installation is in my htdocs\modules\custom\contrib\webform folder, and 13 modules are showing up in Drupal admin/modules. But I can’t click on the checkboxes to install any of these modules because they’re grayed out. I’ve been able to intall other modules successfully, both homebuilt and contributed ones.

Any thoughts on how to proceed? Thanks in advance…..

# Answer
The new webform 8.5 versions requires the "Contribute" module. If you click the little expander next to webform you'll see its a dependency. Have a look on the webform project page for more info https://www.drupal.org/project/webform

Also just as a tip as I noticed from your question you've got your modules as /custom/contrib/webform its better if you do your module file structure as:

/modules/custom/

/modules/contrib/

with your own build modules in custom and anything from drupal.org in contrib.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to include order details in eMail notifications created with the Message module?
I am working with placing an order with the Commerce module in Drupal. When the order is confirmed, a notification will be send to the user with order details. Here I am using a rule like when an order is confirmed, customer will receive an email.

The email content will be from the Message module based on the Rules module. Also there is a content from the Commerce module regarding order details.

My doubt is that how to get this order details content from the Commerce module to this Message module content.

Below is the mail content that I saw in the backend when the rule is applied. But the content doesn't have any order details. But when the mail is received order details are present. I want to find out how to get these order details along with this content.

> Dear \[message:message-commerce-order:commerce-customer-billing:commerce-customer-address:first\_name\], Thank you for purchasing through \[site:name\]. You can view your order history by logging into our website at:\[message:message-commerce-order:view-url\] Sincerely, Order Number: \[message:message-commerce-order:order-number\]

# Answer
> 0 votes
# Part 1: About the concept of using Replacement tokens

By using the Rules module, you should be able to make any relevant token concerning the `order details content` (as in your question ...) available by using the Replacement patterns for each message type created with the Message module.

So the answer to your question is "***Whatever token you're missing, just make it available via Rules, by creating a replacement token for them***". Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that.

These *Replacement tokens* are really a hidden gem about how Rules integrates with Message. For an example to see them at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".

# Part 2: Including some order detail in your message type

### 1. Scenario

Let's assume you want allow the user to enter some (custom) order detail. I.e. let's just call it "order remark" (some free format text, which any customer can use for whatever they want).

We want the related order confirmation message (actually an eMail) to have an eMail subject that includes the value of the free format text entered as "order remark".

Read on for the steps needed to get this to work ... Starting from a vanilla "Commerce Kickstart" installation.

### 2. Add an additional order field

Use relative path `admin/commerce/config/order/fields` to add another (custom) field within "Order settings". In my case, I use a text field, with machine name `field_order_remark`.

### 3. Define a replacement token

Use relative path `admin/structure/messages/manage/commerce_order_order_confirmation` to *edit* the configuration of Message type "Commerce Order: order confirmation". Within the field labelled "Replacement tokens", enter something similar to `@remark_related_to_order` (= this will be the name of the token we want to use / populate in the next step).

On the same (Message type) form, you can start to use (= refer to) this replacement token, and this anywhere you want to do so. As a sample, I just added `(remark: @remark_related_to_order)` at the end of the eMail subject (within the Message Text labelled "View modes: Notify - Email subject").

### 4. Custom rule

The only thing left, is to create an appropriate rule (or tune an existing rule), so that when a Message is created (of type "Commerce Order: order confirmation"), a value is assigned to the replacement token `@remark_related_to_order`, whereas the actual value is the value entered for the (custom) order field with machine name `field_order_remark`.

To do so, just consider the rule below (in Rules export format):

```
{ "rules_commerce_order_message_order_notification" : {
    "LABEL" : "Commerce order message: order notification e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "3",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "message_notify", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_order_remark" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commerce_order_order_confirmation",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:message-commerce-order" ],
          "value" : [ "commerce-order" ]
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:remark-related-to-order" ],
          "value" : [ "commerce-order:field-order-remark" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : 1 } },
      { "message_notify_process" : {
          "message" : [ "entity-created" ],
          "save_on_fail" : 0,
          "save_on_success" : 0
        }
      }
    ]
  }
}

```

The above rule is actually a minor variation of the same named rule shipped with Commerce Kickstart, in which these are the specific changes I applied to get it to work:

* the extra Rules Condition "Entity has field". This is to make rules aware of the (custom) order field with machine name `field_order_remark`. And so that we can refer to it in a subsequent Rules Action.
* the extra Rules Action to "Set a data value". I.e. for the replacement token `remark_related_to_order`, whereas the actual value is the value entered for the (custom) order field with machine name `field_order_remark`. Note the special syntax used for that `entity-created:arguments:remark-related-to-order`

***Voilà***, that's really it. Just repeat the steps above for any other "order detail" you want to be processed in a similar way (each of them will require an additional replacement token, and the rule will have to assign an appropriate value using some order related token.

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

# Answer
> 1 votes
You just goto http://localhost/project/admin/commerce/config/checkout/rules/manage/commerce\_checkout\_order\_email/edit/3

then as screenshot into the message value you can set your custom message and also use "Replacement patterns" for order detail to the message.

thank you..

---
Tags: commerce, notifications, message-subscribe
---