# Question
Title: What's the alternative to using the Conditional Rules module?
The Conditional Rules module allows for including Rules Conditions within Rules Actions (using its `If/Else` constructs), something you cannot do by only using the Rules module. Here are just a few (out of many) typical questions that can be solved by using Conditional Rules:

However, there are some issues with the Conditional Rules module, such as:

* It does not have an official release for D7 yet.
* There is not a lot of documentation about it (and no Community documentation).
* There are some scenarios for which this module produces incorrect results.

Is there any alternative solution for building equivalent Rules logic, and which doesn't require using the Conditional Rules module?

# Answer
> 6 votes
For any custom rule where you are tempted to use the Conditional Rules module, you can always create corresponding Rules Components, with similar Rules Actions to be performed, but also with additional Rules Conditions equivalent to any Rules Conditions you'd want to include by using the Conditional Rules module. And then perform that Rules Component inside your Rules Actions of your original rule.

Consider this prototype-example (just assume it's a simplified version of a more complicated rule with preceding Rules Actions like "Fetch entity by ID", "Set a variable", etc):

```
{ "rules_show_a_message_using_conditional_rules" : {
    "LABEL" : "Show a message using Conditional Rules",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "node:promote" ], "value" : "1" } },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo ... using \u0022Conditional Rules\u0022 ..." } }
            ]
          }
        ]
      }
    ]
  }
}

```

Here is its equivalent using Rules Components:

```
{ "rules_show_a_message_using_a_rules_component" : {
    "LABEL" : "Show a message using a Rules Component",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [ { "component_rules_say_bingo" : { "current_node" : [ "node" ] } } ]
  }
}

```

And the related Rules Component looks like so:

```
{ "rules_say_bingo" : {
    "LABEL" : "Say bingo",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "current_node" : { "label" : "Current node", "type" : "node" } },
    "IF" : [
      { "NOT data_is" : { "data" : [ "current-node:promote" ], "value" : "1" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Bingo ... using a Rules Component instead of \u0022Conditional Rules\u0022 ..." } }
    ]
  }
}

```

Some details about the alternative using a Rules Component:

* The Rules Condition within the Conditional Rules construct, has become a Rules Condition of the Rules Component.
* The actual Rules Action to be performed, was moved to a Rules Action of the Rules Component.
* The original rule simply calls the Rules Component, thereby passing the node to be processed as a parameter of the Rules Component.
* The Rules Event in the original rule is unchanged, and if there would have been any additional Rules Conditions in the original rule, those would have remained unchanged also.

**Note**: the above is just a "concept", to illustrate the key-part of the solution. Because this prototype did not require any previous "Fetch entity by ID" (or "Set a variable", or "load current user points") as a previous action.

---
Tags: 7, rules
---


# Question
Title: Views support for custom entity with base table in seperate database
I have a custom content entity that has been setup with several properties declared. This was really nothing special, just a standard entity representation of data from a custom table in the Drupal database. Everything worked as expected (CRUD operations, views integration, etc.).

This was initially just a test however. The table behind this entity needs to live in a separate MySQL database. This database will be on the same sever as the Drupal database, but must be managed independently with write operations initiated from separate platforms. To attempt this I simply modified the relevant part of the entity annotation from:

```
base_table = "mytable",

```

To:

```
base_table = "mydb.mytable",
persistent_cache = FALSE,

```

The first line declares the base table inside the separate DB (also discussed here) and the second line bypasses local entity caching so fresh data is always displayed in Drupal (also discussed here). For the most part this also works great and seems fully compatible with Drupal's entity API (CRUD operations still work as expected). The issue is that views integration now fails. I can still create a new view based my content entity, but no properties are available (not even the base ID). If I attempt to alter a view created before changing the annotations all properties result in broken handlers and query errors, in the same manner as describe in this question (which is similar, though related to the prefixing of the base table, not fetching it from a separate database).

There are certainly projects in the contrb space that attempt to integrate views with external/remote data, and I always have the option to use search\_api as an intermediary between my custom content entity and views, but I'd like to see if there is a native Drupal 8 core solution for this. Given that the main entity APIs appear to support entity data from another database just fine I was hopeful views support would be implied. Are there alterations required to my entity delcaration (perhaps something in the extended \Drupal\views\EntityViewsData object for my custom entity) to get this working?

# Answer
> 0 votes
Further research has led to the conclusion that this is a current limitation in views. Special characters are not escaped correctly in table names, specifically the "." separator notation in dbname.tablename. It could be framed as a bug depending on what sources views officially supports in core. I've opened an issue with more details:

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

---
Tags: 8, entities, database, views
---


# Question
Title: Wrong path when moving from MAMP multisite to remote website
I have different sites in MAMP, each of them being located in ../htdocs/
i.e. ../htdocs/site1, ../htdocs/site2, ../htdocs/site3, etc.
In some page of site1, I have something like

```
<ul>
    <li>Petit retour aux sources : comment tout a commencé</li>
    <li>Le golfe du Morbihan en 2008</li>
    <li>En 2009, cap sur l'archipel de Glénan</li>
    <li>Cette année (2010), c'est Bénodet !</li>
    <li>Et pourquoi pas <a href="/site1/node/2">Stockholm</a> en 2011 ?</li>
    <li>2012, <a href="/site1/node/36">l'année des cairns</a> du golfe du Morbihan</li>
    <li>En 2013, tranquillement sur la Vilaine...</li>
    <li>Golfe du Morbihan « agayne » en 2014</li>
    <li>2015 : encore le <a href="/site1/node/50">Golfe</a> mais en famille</li>
</ul>

```

Then, I move site1 to web provider and ../htdocs/site1 becomes www (root of the web site).
And, of course, URLs such as "/**site1**/node/36" don't work anymore :-(
How can I solve that?

# Answer
> 0 votes
It sounds like in MAMP you're using one domain, localhost, instead of three separate domains for three separate codebases.

You should set up three domains in MAMP and then you can use relative urls such as "/node/50" instead of "/site1/node/50".

Then your config would be in /sites/default/settings.php, with an included settings.local.php that is git excluded to use different database credentials between the local and production sites.

Multisite is a different set up.

You wouldn't have three separate codebases, such as "/htdocs/site1", "htdocs/site2" and "htdocs/site3".

You would have one codebase such as "htdocs/mymultisite".

With a non-multisite set up with three separate codebases, you would create three hosts in MAMP and then point each docroot to that site's docroot, for example, "/htdocs/site1", "htdocs/site2" and "htdocs/site3".

For a multisite set up, you would use one codebase (such as "htdocs/mymultisite" and create a sites folder for each domain. First, you would copy example.sites.php to sites.php in the /sites folder of your repo. Then for each host, you would set up a folder with a separate settings.php, for example:

```
/sites/site1.local/settings.php
/sites/site2.local/settings.php
/sites/site3.local/settings.php

```

with the folder name corresponding to the domain set up in MAMP.

(With a non-multisite set up with separate codebases, you can just use the /sites/default/settings.php)

For both separate codebases and hosts in mamp, and for multisite with sites folders, it should work to visit each domain, such as site1.local in your browser, the urls will be relative to that URL.

If you are using multisite, when you want to go to production, you can set up a folder for production. Set up a folder for production:

```
/sites/mysite.com/settings.php

```

There is a lot of information about setting up multisite Drupal.

---
Tags: 8
---


# Question
Title: How do I change a field description using hook_form_alter()?
I used to simply replace the string in the #description property, but now it isn't a string and I am not able to change it.

>

# Answer
I found a solution.

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['field_myfield']['widget'][0]['value']['#description'] = \Drupal\Core\Field\FieldFilteredMarkup::create(t('My custom description'));
  }
}

```
> 8 votes

# Answer
```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['field_myfield']['widget'][0]['target_id']['#description'] = \Drupal\Core\Field\FieldFilteredMarkup::create(t('Description'));
  }
}

```
> 0 votes

---
Tags: 8, forms
---


title: How to perform x = x + y in Rules

text:
# Question
Title: How to perform x = x + y in Rules
How can I add this action in Rules? This is my pseudocode:

```
1 total=0;
2 //loop through each line item {
3 //get quantity of each product
4 total = total + line_item_quantity;}
5 if total =< 2 then total = 0;
6 total_cost = total * $1.50

```

I think I can get everything working with the Conditional Rules module. but I cannot get

```
x = x + y

```

to work on Rules because they say that the variable already exists.

Also, how do I use conditions on entities like calculated shipping cost? What's the variable name?

# Answer
Have a look at my answer to the question about "How to add up all items of a field collection field using Rules?". Your question is, IMO, a minor variation of it. Just replace `article-details-item:field-price` by `line_item_quantity` (as in your pseudocode) and it is close to identical.

The custom rule to do the calculation, looks like so:

```
{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

```

Enough to get you going and get it to work (or should I say "How good are you in reading/digesting the Rules-export-language)?
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: How to teach PhpStorm to recognise drupal {table} SQL syntax?
I'm dealing with some really old drupal project full of SQL queries. PhpStorm's understanding of SQL is very handy however I have problems with drupalism like `{table_name}`. IDE complains that `<reference> expected, got '{'`.

How can i set up PhpStorm so that it will understand that the string inside curly braces is just a table name? Or at least make it ignore the curly braces?

# Answer
> 10 votes
In PhpStorm Preferences \> Tools \> Database \> User Parameters:

* Check "Enable in string literals with SQL injection"
* Add `\{\w+\}` to Parameter Patterns.

You may also want to modify the line with `%\w+` to be allowed for language php for placeholders like `%d`. See screenshot and also JetBrain's PhpStorm blog post: Database Language Injection Configuration.

# Answer
> -5 votes
I don't know of any way to make PHPStorm recognize the Drupal SQL syntax.

But if you just want to debug a query that was created by Drupal, then you can remove the curly braces from the query after copying it to the PHPStorm query console.

---
Tags: database
---


# Question
Title: Custom module with custom theme/template
I have tried to get this question answered in the past, but I was never given a satisfactory response.

I am building a custom module. I do not want the module to inherit the current theme being used by Drupal core; it should have its own themes/templates. This is the code I have written.

### myApp.module

```
// $Id$
require_once ('myApp.theme.inc');
function myApp_menu()
{
 $result = array();
 $result['myApp'] = array(
    'title' => "My App",
    'page callback' => "myApp_home",
    'access callback' => true,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

 return $result;
}

function myApp_home(){
    $output = theme('myApp_home', array('data'=> ''));
    return $output;
}

```

### myApp.theme.inc

```
function myApp_theme() {
    $path_to_theme = drupal_get_path('module', 'myApp')."/theme/";

    $themes = array();
    $themes['myApp_home'] = array(
    'template' => 'myApp_home',
    'path' => $path_to_theme ,
    );
    return $themes;
}

```

### myApp\_home.tpl.inc

```
<html>
<head></head>
<body>Hello World</body>
</html>

```

The problem is that the module still resides within the Drupal core. I want to have it be a full page web application.

I am new to this, so if anyone could provide an explanation of the best practice, and example code, I would really appreciate it.

# Answer
As Clive said, you can simply return HTML instead of the render array, e.g.

```
function myApp_theme() {
    $html = "<html><head></head><body>Hello World</body></html>;
    return $html;
}

```

A more general way is to modify the page.tpl.php in your theme and add a wrapper around the normal styling. E.g.

```
<?php if ( $plain_page ) { ?>
  <?php print render($page['content']); ?>
<?php } else { ?>
Normal stuff
<?php } ?>

```

Then in your module, use the template\_preprocess\_page hook to set the $plain page variable. E.g.

```
my_module_preprocess_page( &$vars ) {
  [ check if it's a page you want as plain ]
    $vars['plain'] = TRUE;

```

You will only need the content for the tags as the html.tpl.php template handles that.
> 0 votes

---
Tags: theming
---


# Question
Title: Get the draft data in the webform hook_form_FORM_ID_alter()
I'm building a multi page webform in Drupal 8 as shown below

(1) Consent to ask questions \>\>\> (2) Chekcing eligiblity \>\>\> (3) Consent to Participate \>\>\> (4) Base line info \>\>\> (5) Complete

multipage webform

In the 2nd page (Checking eligibility) as soon as the user clicks on Next Page \> button, I need to validate the submitted values (which contains several radio buttons) and assess the user whether he is eligible to participate in a survey or not.

```
/*
 * hook_form_FORM_ID_alter()
 */
function webform_form_webform_submission_registration_content_node_77_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    ...
    if($form_id == 'webform_submission_registration_content_node_77_form')
    {
        $form['#submit'][] = 'webform_webform_submit_handler';

    }

}

function webform_webform_submit_handler($form, &$form_state) {
    /* This is not displaying any submited values mostly because I haven't clicked on Sumbit button yet */
       dpm($form_state['values']);
}

```

src: https://www.drupal.org/node/2634266

Is there any way to get the Form's draft values before submission? Any better approach to process the values within the page(form) itself? Any help much appreciated.

# Answer
As jrockowitz suggested, the best way to get the webform's data and processing it is, to create custom WebformHandler. Please refer "Creating a custom webform handler plugin for drupal 8" section here for more details.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: How to check that cron is reindex the complete site?
I'm using drupal 7 and cannot find a log that the site is reindexed.

Cron is running every 3 hours which I can see in the log. How can I check that the cron is reindex my site as well?

# Answer
Go to `admin/config/search/settings` or Configuration \> Search and the top of the page will tell you how much of the site has been indexed.

The button "re-index" will let you re-index the site and the status above it will still tell you how far along the indexing process is. By default, Drupal indexes the website during cron runs and the option below the "re-index" button lets you select how many nodes are indexed per cron run.
> 1 votes

---
Tags: 7
---


# Question
Title: How to import user roles and pictures using the Migrate_d2d module?
I haven't been able to find any clear instructions for how to include roles & user pictures in the user migration using the migrate\_d2d module.

I *have* found a number of links with *some* information, but it is all incomplete - or at least it is incomplete for someone who isn't a programmer...

The "Role Migration" page on Drupal.org (https://www.drupal.org/node/1819698) has as its first step: "Instantiate the appropriate role migration class."

Problem is, I have no idea how to do that...

I've tried to find examples of doing this but have found none.

The Migrate\_d2d module has some example code in it that does a pretty good job of describing how to import users, vocabularies, nodes, & menus, but it is silent on how to bring along roles - which is vital to getting most of the rest of a site to work.

I need some help. Every source I've found seems to assume one or two things I just don't know - or maybe I do, but don't understand how to apply them in this case. Any specific, full examples - *not* the snippets I've seen a bunch of that don't give enough context - of how to get the user import to include role mappings would be greatly appreciated.

# Answer
> 0 votes
The following block of code allowed me to import user pictures, roles, & users, and connected them all properly:

```
  /*
   * User Picture Migration
   */
  $api['migrations']['UserPictures'] = $common_arguments + array(
    'description' => t('Migration of user pictures from Drupal 6.'),
    'class_name' => 'DrupalPicture6Migration',
    'default_uid' => 1, // The default owner id if owner is not present
    'source_dir' => 'http://www.example.com',
    'destination_dir' => 'public://',
  );

  /**
   * Register the role migration
   */
  $api['migrations']['UserRoles'] = $common_arguments + array(
    'description' => t('Import Drupal 6 roles.'),
    'class_name' => 'DrupalRole6Migration',
    'role_mappings' => array(
      'unconfirmed' => 'unconfirmed',
      'contributor' => 'contributor',
      'superadmin' => 'superadmin',
    ),
  );

  /**
   * Register the user migration.
   */
  $api['migrations']['Users'] = $common_arguments + array(
    'description' => t('Migration of users from Drupal 6'),
    'class_name' => 'DrupalUser6Migration',
    'picture_migration' => 'UserPictures',
    'role_migration' => 'UserRoles',
  );

```

I looked at probably 30-40 different search results - and some let's-see-what-this-does stabs in the dark - before I finally got things working, but there were 3 main resources I used:

---
Tags: migrations
---


# Question
Title: Create a PDF with one result from a view
I have a view with information from a specific database table and I want users to be able to generate a PDF with the results from one row, which would contain all the information from the row. So far, I've only been able to generate a PDF of an entire view instead of one result. I'm not sure how to "tell" the PDF which view result to generate as a PDF.

Note: This is a different way of asking a question I previously posted, which I think was too confusing at this point.

# Answer
> 1 votes
It is just an idea. You need to create a one more view with same field. But you use views contextual filters and also use view pdf in this view . create a link for print with where you pass argument for this view . Print this link in your first view using view php.

You can also do this custom . create a custom menu item .Pass argument (id,nid) load content programmatically and add pdf download option.

Thank you

---
Tags: 7, views, files
---


title: Cannot install core in the root of site

text:
# Question
Title: Cannot install core in the root of site
I am going absolutely insane. I have been up for several hours scouring the internet, installing, removing, installing, removing, and I CANNOT get Drupal (7 or 8) to install at the root of a site (hosted Linux server, not local or vm). If I try to run the drush si with the package outside of the target site's directory structure I get the site-install needs a higher bootstrap error. Of course, if I move the the install base into the root of the target site's directory, it installs fine...in a subfolder with the name of the install base! I have followed all of the documentation, reviewed hundreds of comments on multiple sites, watched YouTube videos, looked at Pluralsight tutorials. I am at a loss. I saw suggestions to edit the settings.php file (which the install package creates during the install process and doesn't exist beforehand...). I saw suggestions to rename files that are not yet existant because the install hasn't happened. I'm sure much of these apply to an upgrade, but not a new site install. Can anyone please offer some insight into this. Installing with drush is supposed to make things easier. I have now wasted 4 hours trying to figure this out when I could have just manually installed it. But now it's principle. I want to know. Besides I might have to do this again for other sites. Thank you in advance.

# Answer
When you download and install Drupal, it will install inside the directory that contains the files. So if you download Drupal into public\_html and the directory with the Drupal files is called "drupal" it's going to install in `public_html/drupal`. Depending on what server you are running, you will need to identify the new webroot. In this example, you would change the webroot from public\_html to `public_html/drupal`. The folks over at StackOverflow or your hosting company should be able to help you with your specific server settings for your new Drupal root.

Alternatively, you may be able to copy all the contents from the unzipped folder containing all the Drupal files into the webroot, but I've never tried that because I like keeping Drupal in it's own root.

Also, check `sites/default/settings.php` and see what it says for your Drupal root.
> 0 votes

# Answer
I had created this tutorial (Using Drush to Install Drupal 7 from Scratch) back in 2015, try it, should work for you. I just tried it in my Siteground Shared Hosting, and it worked for me (screenshot below).

Follow the instructions below to get started.

1. Firstly, create a Database for your New Drupal Installation and note the login credentials.
2. Open your terminal and change directory to your Document Root and enter the commands below:

The Web Directory/Document Root will depend on the OS you are using: Linux/Ubuntu:

**Linux**: var/www/html/

**Windows** (XAMPP/WAMPP): C:\xampp\htdocs or C:\wamp\htdocs 7.x.

**Note:** here '**x**' is the version number. Right now it's 7.35 so i enter drupal-7.35.

```
drush dl drupal-7.x

```

Now in your terminal change directory:

```
cd drupal-7.x

```

and enter the commands below:

```
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://root:your_db_password@localhost/your_db_name

```

**Note:**

1. The Drupal **username** and **password** seem to always end up as **admin/admin** no matter what I set them to. So, I suggest just using those and then changing them after you login to your new site.
2. Also if you are using Linux/Ubutnu make sure to assign the apache-user to the directory 'files' located at 'sites/default/files.' You can do that using the command below:

sudo chown -R www-data:www-data sites/default/files
> 0 votes

---
Tags: 7, drush, installation
---


# Question
Title: files missing in web/ folder when using composer.lock file
I have run into an unexpected problem with a fresh install of drupal 8.

Initial setup

```
$ git clone https://github.com/drupal-composer/drupal-project dp
$ cd dp
$ composer install

```

This works fine, installs everything. I now repeat the same thing, and use the composer.lock file from the above.

```
$ git clone https://github.com/drupal-composer/drupal-project dp2
$ cp dp/composer.lock dp2/
$ cd dp2
$ composer install

```

This time, however, the web/folder just has folders in it, no files. In fact, a diff between the two folders shows a number of missing files including in sites and sites/default.

I thought the composer.lock file was used to simply lock the versions of the modules down.

What am I missing here?

# Answer
After some investigation, I found the culprit. The composer project uses drupal scaffold to place these files. However, this does not seem to be getting executed when the .lock file is already in place when you do the `composer install`

To resolve this, it was as simple as running the following command

```
$ composer drupal-scaffold

```
> 2 votes

---
Tags: 8, composer
---


title: Create template file for views block

text:
# Question
Title: Create template file for views block
There is a lot about theming custom blocks, but what about blocks created by views?

My views block has id: block-views-posts-listing-block,

I try many ways for naming template file, ex: block--block--views-posts-listing-block.tpl.php, but I can't find correct file name.

# Answer
> 20 votes
Edit your view. and Under the "Advanced" settings of your Block details, click on `"Theme: Information"`. A list of options of template files will be displayed.

for example, if your block has a name "posts listing", see possible names listed by "Theme Information" option:

```
* Display output: views-view.tpl.php, views-view--posts-listing.tpl.php, views-view--default.tpl.php, views-view--block.tpl.php, views-view--posts-listing--block.tpl.php
* Style output: views-view-unformatted.tpl.php, views-view-unformatted--posts-listing.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--block.tpl.php, views-view-unformatted--posts-listing--block.tpl.php
* Row style output: views-view-fields.tpl.php, views-view-fields--posts-listing.tpl.php, views-view-fields--default.tpl.php, views-view-fields--block.tpl.php, views-view-fields--posts-listing--block.tpl.php
* Field Content: Title (ID: title): views-view-field.tpl.php, views-view-field--title.tpl.php, views-view-field--posts-listing.tpl.php, views-view-field--posts-listing--title.tpl.php, views-view-field--block.tpl.php, views-view-field--block--title.tpl.php, views-view-field--posts-listing--block.tpl.php, views-view-field--posts-listing--block--title.tpl.php

```

**for example**: your block has the name *posts listing*, and has style *unformatted*, then "Theme Information" suggest the name `views-view-unformatted--posts-listing--block.tpl.php` (this is only one of several names). you can copy the original `views-view-unformatted.tpl.php` template file (located in /modules/views/theme) to your current theme directory, and rename this file with the name suggested :`views-view-unformatted--posts-listing--block.tpl.php`. then make the changes inside your template file. If this template does not allow make your wanted changes, seek other templates according your needs.

In the end, if you add a new template, rescan template files list:

> Important! When adding, removing, or renaming template files, it is necessary to make Drupal aware of the changes by making it rescan the files on your system. By clicking "Rescan template Files" button you clear Drupal's theme registry and thereby trigger this rescanning process. The highlighted templates (in your template list above "Rescan template Files" button) will then reflect the new state of your system.

Also Theme Developer Module http://drupal.org/project/devel\_themer suggested by Oswald could be useful to detect possible template/s to change specific elements according your criteria. I do not recomend this module enabled in productions enviroments (in my case, even I have disabled the module in test enviroments, because seems to have conflicts with views, but when it has been necessary, has been very useful)

# Answer
> 18 votes
For those seeking the answer in D7, according to Theme Developer(aka devel\_themer), you can create a tpl override for a view's block using the convention:

> **block--views--**{view's machine\_name}**-block**

Therefore in the example give you will get

> **block--views--** *post-listing* **-block.tpl.php**

Without the spaces (I couldn't edit this properly to allow it all to be inline.

# Answer
> 7 votes
At the end of half an hour changing tpl names, here is my final conclusion:

```
block--views--[view-name]-[display-name].tpl.php

```

\[view-name\]-\[display-name\] part can be found like noTxt said or joining with a '-' the id name of the view and the id name of the view display, the -block at the end isn't correct.

# Answer
> 6 votes
# In Drupal 8

The fields template would be:

> ### views-view-fields--\[view-name\]--block-1.html.twig

# Answer
> 1 votes
`block--views--[view-name]-[display-name].tpl.php` should be changed to `block--views--[view-name]-[machinename].tpl.php`.

You will find the machine name from your views advanced section where it is written other

# Answer
> 1 votes
The file name patterns describe above works UNLESS your view name + display name is longer than a certain amount of characters!! I was caught by this and could not find why a template file ending in ...`block.tpl.php` was working and the following display ...`block-1.tpl.php` was not working.

It turns out that Views replaces the machine name with an MD5 hash if the name is too long. If you want to be sure of the template name you should be using, add `$conf['theme_debug'] = TRUE;` in your settings.php and then look at the page source. if you find something like `block--views--d131dd02c5e6eec4`.... you'd better shorten the machine name of the view (if you manage do to that... It's not the human-readable name). Or else you need to use a template file with that silly name.

see also

Views Block's machine name is being "hashed" (?)

and

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

# Answer
> 0 votes
Check this page https://www.drupal.org/node/1089656, and information about underscores which views uses:

> Also one more example with Views, if you have a block created by views with a view name "front\_news" and display id "block\_1" then the theme hook suggestion would be: block--views--front-news-block-1.tpl.php (notice, when you have underscores in a display id or in a view name - you have to transform them in to a single dash)

# Answer
> 0 votes
For blocks inside panel panes, the solution provided by noTxt and other is not working. The syntax would then be (no underscores!):

```
panels-pane-block--views-[view-name]-[display-machine-name].tpl.php

```

Thanks to user3074436 for providing the $conf\['theme\_debug'\] setting in order to figure out this exceptional theme overriding case

# Answer
> 0 votes
You are on on D7 \>= 7.33 you could display theme\_suggestion directly in the page as HTML Comments using :

in `settings.php`

```
$conf['theme_debug'] = TRUE;

```

Here is the complete documentation https://www.drupal.org/docs/7/theming/overriding-themable-output/working-with-template-suggestions

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


# Question
Title: How to remove duplicate view results from multiple blocks on same page in Drupal 8
I have multiple view blocks with different info on same page of same content type. I want to remove the duplicate results. I want one result to appear only once on whole page.

How can I achieve that in Drupal 8 ?

Thanks

# Answer
> 1 votes
Try Views Exclude Previous, check screenshots bellow

---
Tags: views, 8
---


title: Custom Access Permissions

text:
# Question
Title: Custom Access Permissions
I need to build a facebook model privacy settings for user. Access permissions must be set to users who are "Public" and "Connected", which the latter is from User Relationship module.

eg: User must have permission settings such as who must view his profile, his nodes, user connections, also some views which are related to user.

Can anyone suggest an idea how can i implement this.

# Answer
Just use the Group module, and create a content type like "Connected Users". And then create a "group" for each user (using something like the user's name as its label), of group type "Connected Users".

Tune the permissions which come with the Group module (which are different from standard Drupal permissions!) to fit your needs.

Possibly you also want to use all sorts of integrations with modules such as the Rules module or the Views module (the Group module is entirely entity based, so those kind of integrations or virtually unlimited).

Voilà ...

PS: This answer applies for either Drupal 7, or Drupal 8.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Notice: Object of class stdClass could not be converted to int in drupal_write_record()
I'm building a new Drupal 7 and brought over the user table at the beginning of the project from another Drupal 7 site. All has been good with that except that when users save their profile, they get the following error, which I believe is related to our custom Avatar builder module. I am wondering what I can do to suspend the error message so that it doesn't show for now during our testing phase.

> Notice: Object of class stdClass could not be converted to int in drupal\_write\_record() (line 7340

Here is the section of code from the .module that I believe that relates to this error:

```
/**
 * Implements hook_user_insert().
 */
function my_avatar_selection_user_insert(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture;
    drupal_write_record('my_avatar_selection_usage', $usage);
  }
}

/**
 * Implements hook_user_update().
 */
function my_avatar_selection_user_update(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture;
    $has_rows = (bool) db_query_range('SELECT 1 FROM {my_avatar_selection_usage} WHERE uid = :uid', 0, 1, array(':uid' => $account->uid))->fetchField();
    if ($has_rows) {
      drupal_write_record('my_avatar_selection_usage', $usage, 'uid');
    }
    else {
      drupal_write_record('my_avatar_selection_usage', $usage);
    }
  }
}

```

The module works by saving the data from jcarousel into the data field of the user table and when the profile is saved, it creates a graphic that looks like the options the users selected. As far as I can tell, there are no issues with saving the avatar, it just generates this error. I took this module from the old website 7.50 so maybe there is a component I don't need on the new site 7.54.

# Answer
The error is caused from the fact `$account->picture` is an object, and `drupal_write_record()` is trying to convert it to an integer, since the *my\_avatar\_selection\_usage* defines *fid* as an integer value. See the following code used from `user_save()`, which the function invoking `hook_user_insert()`.

```
  // Process picture uploads.
  if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
    $picture = $account->picture;

    // Omissis

  }

```

As you see from that code, the correct code you should be using is the following one.

```
/**
 * Implements hook_user_insert().
 */
function my_avatar_selection_user_insert(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture->fid;
    drupal_write_record('my_avatar_selection_usage', $usage);
  }
}

/**
 * Implements hook_user_update().
 */
function my_avatar_selection_user_update(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture->fid;
    $has_rows = (bool) db_query_range('SELECT 1 FROM {my_avatar_selection_usage} WHERE uid = :uid', 0, 1, array(':uid' => $account->uid))->fetchField();
    if ($has_rows) {
      drupal_write_record('my_avatar_selection_usage', $usage, 'uid');
    }
    else {
      drupal_write_record('my_avatar_selection_usage', $usage);
    }
  }
}

```
> 2 votes

---
Tags: 7, users
---


title: Create a new user on Webform submission

text:
# Question
Title: Create a new user on Webform submission
I have a Drupal 8 website with an application form built with Webform. I would like to be able to auto create a user when the webform is submitted using details from the webform, so the person filling in the application can log-in and check the status of their application. I've seen several options online but all are for Drupal 7 and the modules used are not available for Drupal 8.

Any ideas?

# Answer
> 1 votes
You can write your own WebformHandler to do so. Just extend WebformHandlerBase and write your code into the `postSave()` function. Here is a little example: https://gist.github.com/mharmuth/0ab021d5b65e4cab7c6efec951fc59e9

This class has to be stored in your custom module in the directory `your_custom_module/src/Plugin/WebformHanlder/CreateUserHandler.php`

After creating this handler, you will be able to add it in your webform under "Email/Handlers".

Hope this helps ;)

---
Tags: webforms
---


# Question
Title: Migrating site from MariaDB to MS SQL 2012
I'm trying to migrate the site from a linux+mariadb platform to IIS+MS SQL platform. Could someone please tell me what is the best way to do this?

What I've done so far:

It's a Drupal 8 site so the Migrate and Migrate D2D modules are useless.

# Answer
> 0 votes
So I managed to migrate the DBs in the following manner:

1. Install MySQL on the target machine.
2. Load the MariaDB in MySQL. Since it is supposed to be a drop-in replacement, this should go smoothly.
3. Create an empty database in MS SQL 2012.
4. Use the SSMA to migrate the DB into MS SQL 2012.
    * The migration will throw a whole bunch of warnings at you. Most of these have to do with truncation due to data-type incompatibility. Don't worry about these. Refer to the schema for the DB that Drupal created when it was installed in MS SQL for reference. For the most part, the data-types would be over compensated, e.g. `int` becomes `bigint`, etc. So you don't really need to do anything, but check anyways.
5. Once the DB has been migrated, change the credentials in `settings.php` to use the new database.
6. Clear caches on the newly migrated site and ensure everything works.

# Answer
> 0 votes
I recommend giving this tool a try. I have used it in the past (to do MSSQL -\> MySQL) to setup a datasource for a legacy migration. In your case, you don't need a migration, you just need the db to be in MSSQL format. This is a great litmus test that might save you hours and hours of time.

https://dbconvert.com/mysql/mssql/

It's reasonably priced and worth a shot. If it works fine, you'll move right along.

# Answer
> 0 votes
If this module ever gets updated to a Drupal 8 version, it could be an option: https://www.drupal.org/project/dbtng\_migrator

It's actually a fairly small module. What the module attempts to do is use the installed modules schema definitions in D7, apply the Schema(s) to the destination DB type and then just grab and insert all the rows from the existing drupal db into the newly created database tables.

The issue queue notes there are some issues with likely dbms vendor specific issues.

**EDIT**

While the above Drupal tool exists to migrate a database from 1 dbms platform to another, it currently relies on Drupal7. Similar tools exist in other languages as well. A relatively popular tool which should handle most-nearly any database popular commercial database can be found here:

---
Tags: database, migrations
---


# Question
Title: Random order at three-column Slick Slider
I want to show random content on a slick slider which has three a three column layout (three content elements next to each other) on each slide.

If I set the views' sort criteria to RANDOM it will randomize the slides itself but not the content (the content and order on each slide remain the same).

Is there a way to randomize the content of each slide aswell?

# Answer
> 0 votes
I already found the solution:

The randomize option has to be enabled in the slick options instead of the view's sort-criteria. We can either define a optionset to use it in different views (the optionsets have to be set at *Configuration -\> Media -\> Slick*) or we override the default-optionset in the view configuration itself (*View -\> Edit -\> Format -\> Settings next to Slick Carousel*).

---
Tags: views, 8
---


# Question
Title: How to increase a scheduled time using a new field and rules component scheduler
I am working on **Drupal 7** on a custom content type that is called **Event**.

Each created Event is programmed to be displayed for **1 hour** before been deleted. I am using **rules component scheduler** for that and it **works well**.

**Now I need to be able to increase that display duration**.

I already created a numeric field called **duration** that take the value of the duration from the user. That value that I want to add to the initial display duration.

I need to use that duration field in the **Scheduled evaluation date**. But rules denied using the **+** with an identifier.

Can anybody help ?

**How do I increase the duration of a tasks that has already been scheduled on node creation. How do I do that using a field that take the value to add?**

# Answer
> 1 votes
What you'll have to do to get this to work, consists basically of these steps:

1. Create a new rule using event "After updating a node of content type *Event*, in which you add a Rules Condition to check that the value of the duration field was changed (I suppose you know how to write such Rules Condition).
2. The Rules Actions to be performed in this new rule to be created, consist of these 2 Rules Actions (in the order specified):

* Delete the scheduled Rules Component that got scheduled when the node (Event) was created. That way the node will not get deleted as originally planned. For way more details on that, refer to my answer to "How to delete a scheduled task using Rules Scheduler?". Make sure to understand that it is extremely important, for this to work correctly, that you usve a unique identifier of the scheduled rule ... using the node *title* for it is asking for trouble (what if 2 nodes have the same title???), which is why I always make the node's `nid` part of such identifier.
    * Schedule the same Rules Component you already have (to delete the Event later on) AGAIN, using your "duration field".

What this really means is that your implementing logic that reads something like so "***Don't delete this node (Event) after one hour yet, instead give me X more time (as indicated in your duration field) from now on (= the moment the updated node (Event) is updated with that duration field update)***".

---
Tags: nodes, rules
---


title: Saving 'sub' from Identity Provider

text:
# Question
Title: Saving 'sub' from Identity Provider
I need to associate `sub`, which is received as part of `$userinfo` in `openid_connect_save_userinfo`, but I don't see it as part of the claim options. I also don't see that it's stored elsewhere.

I am using the openid\_connect project.

I'm wondering if I'm missing something in configuration and maybe I need to do something custom.

# Answer
> 0 votes
The association is stored in `openid_connect_authmap` and there is a service: `openid_connect.authmap` to access it.

Without DI: `\Drupal::service('openid_connect.authmap')
 ->getConnectedAccounts(\Drupal::entityTypeManager()->getStorage('user')->load($userid))`

---
Tags: 8, authentication-authorization
---


# Question
Title: How can I have token support in the field formatter class?
I have a content type with, among other things, a status field and an image field.

I would like to have an image field with the field formatter class set to \[node:field\_status:entity:name\] (non-alphanumeric characters replaced by underscores as part of token generation), such that the image CSS class varies, depending upon the status of the node.

Using the class, I could then use CSS to apply an overlay image like 'Open', 'In-Progress' or 'Closed', over the top of the image based on the class being 'Open', 'In\_Progress' or 'Closed'.

Is this something that can be done?

I am happy to 'hack' a copy of the field formatter class to do the job if this is not something that would likely end up in the core module.

Is there a different way I should use to achieve what I want?

# Answer
> 1 votes
Yes, you can extend the formatter class and add token support to it, like for example LinkFormatter::viewElements() does this for the link title. But for this simple task I would use the node template.

To add a node specific class you copy node.html.twig from the base theme to the template folder of your custom theme, add a name suggestion for the content type to the file name and add the class to the attributes:

*node--custom-content-type.html.twig*

```
{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'clearfix',
   'node--field-status-' ~ node.field_status.entity.name.value|clean_class,
  ]
%}
{{ attach_library('classy/node') }}
<article{{ attributes.addClass(classes) }}>
...

```

---
Tags: entities, tokens
---


# Question
Title: Hide some part of node when the field_countdown timer is zero
I create a field with field\_countdown. Now I want hide some part of my node text when the timer is zero.

For this when I use this code:

```
{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    Show
{% else %}
    Hide
{% endif %}

```

Work but not currectly. And in first page send me an error.

> The website encountered an unexpected error. Please try again later. TypeError: DateTime::\__construct() expects parameter 1 to be string, array given in DateTime-\>\__construct() (line 519 of vendor\twig\twig\lib\Twig\Extension\Core.php).

In second way I create a field like my field\_timer and just show secondes and after my timer show zero IF command work but in this way I add a field and it's not good.

How can I do this with other codes in Drupal 8 ?

# Answer
You might use twig `without` method. It will print all configured content to be rendered without the selected fields/properties.

```
{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    {# Show #}
    {{ content }}
{% else %}
    {# Hide - print the content without the field_timer #}
    {{ content|without('field_timer') }}
{% endif %}

```

For some cacheability issues it is recommended to always print content.
> 0 votes

---
Tags: 8, entities
---


title: Goto page in webform or submit

text:
# Question
Title: Goto page in webform or submit
I've got a Drupal 8 webform with a multi page wizard. I know that it is possible to "jump" to a specific page if I implement `hook_webform_submission_form_alter()` and add my own submit function to change the formState `current_page` to my desired page. But I want to check a value from a previous page and if the value is value\_a I want to submit the form. If it is value\_b I want to go to page b and if its value\_c I want to go to page c.

```
$pages = $formState->get('pages');

if ($formState->get('type') === 'value_b') {
    $pageName = 'page_b';
    gotoStep($pageName, $pages, $formState); // this is my custom function to go to the desired page
} else if ($formState->get('type') === 'value_c') {
    $pageName = 'page_c';
    gotoStep($pageName, $pages, $formState); // this is my custom function to go to the desired page
} else {
    // SUBMIT FORM. HOW TO DO THIS?
}

```

# Answer
> 1 votes
I switched to the latest dev release ob the webform module and could skip the wizard pages depending on previous values without having to code anything. Thanks for the tip @jrockowitz ;)

---
Tags: webforms
---


title: Users can't log in sometimes

text:
# Question
Title: Users can't log in sometimes
Drupal 7.5, PHP 5.6.27 Debian 8, remote host.

We are running into a problem where some people can't log in some of the time and sometimes it works if they try multiple times. Users have reported the issue with different browsers and only a small percentage of people seem to be affected. Please note that I can only reproduce the error on occasion, and very inconsistently.

Watchdog simply shows that a session is opened for the user, even if the front page shows that they are not logged in.

**Edit: Users can usually log in if they enter the wrong password first!**

**Things I've tried:**

* changed cookie\_domain from www. to .
* made sure rewrite condition allows https
* cleared Drupal cache
* we have no external caching
* added redirect from port 80 only to default-ssl.conf
* Users can't always log in with a one-time log in link generated with `drush uli "[username]` (the site will ask them to log in)
* creating a custom login module to set a new custom session suggested here
* added some cookie configurations to the sites/default/settings.php file as suggested in this post
* installed the website on a different environment with PHP 5.5 and different settings.php .htaccess and php and mysql configurations.

**Known Workarounds:** May or may not provide clues.

* Sometimes if we change a user's password, they can get in that way
* If a user enters the wrong password first on purpose then logs in, they are able to log in
* Sometimes we can provide a one-time log in link for users to get in, but that doesn't always work

**Edit:** I've managed to recreate the issue on a local development environment with different settings files. I removed all the settings files information from my original post since I know now that they are not relevant.

# Answer
> 3 votes
That can happen if the site is redirecting to a different domain or to a secure/non-secure protocol upon login. I.e. with/without www or to http/https. If so, you could set a base domain and cookie domain in settings.php, and/or enable www/non-www redirect in `.htaccess`.

It also seems there may be a problem with PHP 5.6.1.
https://www.drupal.org/node/2723927
https://www.drupal.org/node/2379019

# Answer
> 3 votes
I believe there is some kind of caching in play here. I've found that I can successfully log in with the demo user provided by generating unique login URLs. Each unique login URL I create has worked for me exactly one time and then no longer works after that. This strongly suggests that something is caching pages based on their URL and dynamic backend functionality (PHP) is no longer taking effect on subsequent attempts to log in via that URL.

For example.. I could not log in via `/user/login`, but when I manually switched that to `/user`, I was able to log in once, but after logging out, I couldn't log in via that URL anymore. I tried appending a series of `?itok=asdf` query parameters to the login URLs and each would work once. Adding numbers at the end of the query string did not appear to work, so `?itok=asdf1` worked, but then trying `?itok=asdf2` did not, but `?itok=asd` did.

I've already burned `/user/login/a` and `/usr/login/b` with further testing. To test this yourself, I suggest coming up with a unique alphabetical prefix and then alphabetically appending to that, e.g.

```
/user/login/prefix
/user/login/prefixa
/user/login/prefixb

```

... etc

Note again that in my testing each URL is working exactly once and "never" works again.. you must keep coming up with new ones to repeat the test.

As stated above, this strongly suggests something is caching pages based on the URL.

# Answer
> 0 votes
If I can make a guess correctly, the users might have forgotten or entered a wrong password for 5 times which in turn will block access for over 6 hours. Post down the cool down period they'll be able to access. For immediate access, drupal developers need to clear there IP from the flood table in database.

---
Tags: 7, users, cookies
---


# Question
Title: Trying to get fullPage.js implemented, but how to add data-attributes?
This is such a great script called fullPage.js

I managed to load the js file and css file and even with the Void Menu Module, managed to call anchor links, but I'm struggling with the data attributes part of the implementation of this cool code! Any help is greatly appreciated! How do I get data-attributes to work in Drupal 7.25? I mean, I need to add them to the menu, so that the html looks something like this:

```
<ul id="menu">
    <li data-menuanchor="firstPage"><a href="#firstPage">First slide</a></li>
    <li data-menuanchor="secondPage"><a href="#secondPage">Second slide</a></li>
    <li data-menuanchor="3rdPage"><a href="#3rdPage">Third slide</a></li>
    <li data-menuanchor="4thpage"><a href="#4thpage">Fourth slide</a></li>
</ul>

```

Just want to add it to the Main Menu in Drupal. Any idea how? Am trying to implement this on my homepage and using the Adaptive Sub-Theme with Display Suite Module installed, if that helps any.

Have added the following to template.php, but it makes no difference at all:

```
function MY_THEME_NAME_menu_link(&$variables) {
  $variables['element']['#attributes']['data-menuanchor'] = substr($variables['element']['href'], 1);
  return theme_menu_link($variables);
}

```

What am I doing wrong here?

# Answer
Now there is contributed module that will let you add custom attributes per menu item, you can find it here: Menu Links Attributes
> 0 votes

---
Tags: routes, hooks
---


title: Get the value from module to template

text:
# Question
Title: Get the value from module to template
I want to pass the value from module to page tpl file in drupal.I have created a custom module 'one\_time\_popup'.I have created a sample soutput and tried to pass it and print in page.tpl.php after footer section.but doesn't shows any thing.What I did wrong.I'm a newbie

```
function one_time_popup_menu(){
$items['oneTimePopupData'] = array(
'title' => 'One time Popup',
'page callback' => 'one_time_popup_user_login',
'type' => MENU_CALLBACK,
'access callback' => TRUE,
);
return $items;
}
function one_time_popup_user_login(&$edit, $account){
 ...
$output='value from one time popup module!';
return theme('photo_order',array('results' => $output));
}
function one_time_popup_theme() {
 return array(
'photo_order' => array(
  'template' => 'page',
  'variables' => array(
    'results' => NULL,
  ),
 ),
 );
}

Tpl file(page.tpl)
<?php echo $results; ?>

```

# Answer
```
<?php
/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items = array(
      'custom_menu_item' => array(
        'title' => 'Hello world',
        'page callback' => '_page_hello_world',
        'access callback' => TRUE,
      ),
    );
  return $items;
}

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  $theme = array();
  $theme['mymodule_template'] = array(
    'template' => 'mymodule-template',
  );
  return $theme;
}

/**
 * Preprocessor function for 'mymodule_template'.
 */
function template_preprocess_mymodule_template(&$vars) {
  $vars['hello'] = 'hello!';
}

/**
 * Page callback.
 */
function _page_hello_world() {
  return theme('mymodule_template');

}

```

A $hello variable is available in your template at path /custom\_menu\_item
> 0 votes

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


title: How to enable free tagging?

text:
# Question
Title: How to enable free tagging?
I'm using Drupal 8 and I would like to allow free tagging my website. There should be a field on the node edit page for tags that the user can add new or existing tag(s) to the page.

What field should I use and how must I configure it?

# Answer
I do not know what a *free tagging cloud* is, but I can help you with setting up a free tagging field.

On your entity (content type), add an **entity reference field** that references **taxonomy terms**. Optionally you can limit to a specific vocabulary. Also select the checkbox to create new items if they do not yet exist.

Then on the manage form display tab of the content type, make sure that you select the **Autocomplete (Tags style)** as the Widget for your created field. This should give you a free tagging text field.

(You can use the Article content type of a clean Drupal site as example)
> 3 votes

---
Tags: nodes, taxonomy-terms, entities
---


title: How do I add a media image field?

text:
# Question
Title: How do I add a media image field?
I have installed these modules:

When I try to add an image field, I have no widget for Media like there was in Drupal 7.
I also tried to add a reference to a media, but it doesn't seem to work.

What am I doing wrong?

# Answer
What you got can do what you want, but it requires configuration and without a UI it's quite hard.

You might want to try adding the file browser module, which uses Dropszonejs to create a nice file browser widget. I have tested it out and it seemed to work just fine, but it wasn't quite mature enough for what we wanted to do at the time.
> 1 votes

# Answer
You have to add new references field (other) and select media. Now you can select media or create per Entity browser :)
> -1 votes

---
Tags: 8, media
---


# Question
Title: DateTime field value is automatically adjusted for the timezone set in Drupal
I have a DateTime field in a content type. I set the value as 00:00:00 for the H:m:s. My timezone is set to Europe/Bucharest. Whenever I get the field the value changes to 21:00:00.

Obviously Drupal is adjusting to fit my timezone. I assume, I'm not sure.

I don't want any sort of adjustments to be made. I want the time I've entered.

How can I get the non-adjusted time or disable Drupal adjusting the time?

# Answer
I am not sure if you can disable it completely, but by changing the site's default timezone to the same timezone as your server, and preventing users from setting their own timezone you should be good.

Both can be configured on /admin/config/regional/settings
> 0 votes

---
Tags: 8
---


# Question
Title: What is the difference between a JOIN and a RELATIONSHIP in hook_views_data_alter()
What is the difference between these two as implemented on `hook_views_data_alter()`? Why choose one over the other?

I did notice that in setting up a `relationship` between `mytable1` and `users` tables, the Views UI gave me the option to add the `mytable1.uid` field under the relationship section, that way allows me to add `users` fields into the query.

What am I supposed to notice on the views-UI when I implement a `join` on a table? My implementation is as follows:

```
mymodule_views_data_alter(&$data){

    $data['mytable1']['table']['join']['users'] = array(
        'left_field' => 'uid',
        'field' => 'uid',
    );

}

```

I did this without a relationship setting, so I can observe the exclusive effect of each(`join` vs `relationship`)

# Answer
From my experience, a join is always done when the query is executed. This means that you can utilise the fields on the joined tables without adding a relationship in the view. When a join is used, I don't think the views information tied to that table is pulled in. For example, you won't be able to add relationships tied to that table.

A relationship is a choice that the user can make on the view. They can choose to add the relationship (from the section on the right side of the view). When a relationship is added, the views information tied to that entity is also pulled in. For example, you will be able to add relationships linked to that table.
> 0 votes

---
Tags: 7, views, hooks
---


# Question
Title: Using modules with almost similar functionality together on production site
I have 2 modules with similar/alternative available and I have to use both. Those are Entity Reference and Search API.

Now the situation is that there are few modules which require References and Search modules as a dependency. It is a need and I have to use it.

Can I use all these modules at the same time on a production site?

Is there any possibility of clash or site crash?

# Answer
> 2 votes
Yes, there's always a possibility that modules will be incompatible with other modules that do the same thing.

There's also the possibility that modules whose functionality is completely unrelated will be incompatible with one another. Such is the nature of a modularly extensible system.

The only way you'll know is if:

1. The documentation for one or more modules list their known issues with other modules, or
2. You thoroughly test the two modules while both installed on a single site

---
Tags: 7, entities, installation
---


title: Why cannot I install this module?

text:
# Question
Title: Why cannot I install this module?
I installed Drupal 8 distribution in Acquia Drupal. I am trying to install the Panels module after downloading the archive file from drupal.org.

I am not able to select the Panels module to install it.
Is there any other additional module to install, apart from the *Layout Discovery* module?

# Answer
> 1 votes
If you go through the panels module README file. It clearly says the below:

```
dependencies:
  - ctools
  - layout_discovery
  - drupal:system (>= 8.3.x)
test_dependencies:
  - page_manager

```

Make sure you have the above modules pre-installed for Panels.

For further help you can follow here: https://www.ostraining.com/blog/drupal/panels-drupal-8/

Else, revert back for further help.

# Answer
> 1 votes
Since you copied the module files by downloading its archive file, you didn't get also the third-party modules necessary to the Panels module.
For the branch 8.x-4 of the Panels module, the only third party module required is the Chaos tool suite (ctools) module you can download, for example, from https://www.drupal.org/project/ctools/releases/8.x-3.0. Every version higher or equal to 8.x-3.0 is compatible with the 8.x-4 branch of the Panels module.

The Layout Discovery module listed as dependency in panels.info.yml is a Drupal core module, in the same way the System module is, so you don't need to download them, as they are core modules available in the latest 8.3.x Drupal version.

If you plan to run the tests that come with the Panels module, then you need also the Page Manager module, which is now separated from the *Chaos tool suite* module.

Since the Panels module has its own composer.json file, if you copied the Panels module with Composer, you would also get its dependencies copied.

---
Tags: panels
---


# Question
Title: What is better for performance: Many entity types with one bundle or one entity type with many bundles
I am using the ECK module to build custom entities. When using custom entities, the decision must always be made: shall I create a number of entity types or shall I create one entity type with a number of bundles.

From a usability perspective, the latter is obvious since, just as the node system, all entity types can easily be connected in views. It gets harder when different entity types must be used in views.

Apart from that, I assume that there must be a benefit from using multiple entity types. It has something to do with memory that drupal carries around, but it is not clear to me what exactly makes a difference.

I am aware of the benefit of using entity properties instead of fields. However, most of my entities use fields that cannot be replaced by a property.

So the question is: should I in general aim for using more entity types (each of which automatically create one bundle) or should I not worry about performance impact and create all bundles under one (generic) entity type.

# Answer
I don't have experience with ECK.

But in general I would say:

* Use entity bundles, if you need different configurations of fields and displays.
* Use entity types if you need different behavior/functionality, different urls for admin pages, different access logic, etc.

Entities of different types are harder to use together or interchangeably. E.g. an entityreference field can only reference entities of one type. And Views can only list entities of one type.

Performance / memory: With multiple entity types, the total information about all entity types will be bigger. With bundles, the bundle information for one single entity type will be bigger. So some operations might be faster with fewer entity types and more bundles, some operations might be faster with more types and fewer bundles.
> 1 votes

# Answer
This might not be the answer you want as it does not cover performance, but I think that you should choose what makes sense.

The Drupal entities system is about 'families of things'. Think of it as Classes in object oriented programming. An entity is a base class and a bundle is a sub-class that has access to the properties of its parent.

If all the types of entities have no shared fields/properties, create them as different entities. If they share properties, create them as bundles and put the shared properties in the entity. (Or use a combination of entities and bundles if it makes sense.)

But you can use other comparisons too. If you for instance have multiple types of documents (invoices, orders, notes, etc.) that all have different data, it could still make sense to make them as bundles of a 'document' entity.

With respect to memory, I think that ECK creates all entities as a type of EckEntity and then performs some magic to label it differently (please correct me if I am wrong). So you should not need to worry about loading of different classes, it is just the ECK classes.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to place a library in DRUPAL_ROOT/libraries?
In Drupal 8, when I declare a library in a `.libraries.yml` file, it seems the library files have to be located INSIDE the module or the theme folder with the `.libraries.yml` file.

For instance, if a MYMODULE module contains this `.libraries.yml` file:

```
form-alter-css:
  version: 1.x
  css:
    theme:
      css/form-alter.css: {}

```

The file `css/form-alter.css` has to live at `DRUPAL_ROOT/modules/MYMODULE/css/form-alter.css`.

Instead, for shared libraries, I'd like to place the files in `DRUPAL_ROOT/libraries`, like we did in Drupal 7. But how?

I have tried entering an absolute path in the `.libraries.yml` file (e.g. `/libraries/css/form-alter.css`) but it doesn't work. Any ideas?

# Answer
> 2 votes
In drupal 7 the shared libraries were provided by a contrib module. Because a lot of modules had this as a dependency, it was very common:

Libraries API

I don't know, if this will be used this often in drupal 8, you can follow the development here:

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

So at the moment you are stuck with the libraries in \*.libraries.yml, when you don't want to use the dev version of the Libraries API.

The libraries in \*.libraries.yml were not designed for libraries in a shared directory. But they have one very useful feature, you can borrow a library from another module. There are a lot of useful packages already in core modules, like jquery ui elements. If you define a library in one of your modules, they also become available for all other modules. But the files will remain local to that module, which defines the library.

# Answer
> 0 votes
Actually, it's pretty straightforward in D8. To set it up, create a folder named libraries in your root install folder, and add your external libraries there. Covering this is more detail, is a listing here.

---
Tags: 8, theming
---


# Question
Title: Rendering plain text instead of formatted data
In my custom module (in Drupal 8), I am using a form field (in a custom form) to use CKEDITOR with the following code which loads the editor fine.

```
$form['full_detail_text'] = array(
  '#type' => 'text_format',
  '#format' => 'full_html',
  '#title' => t('Full Detail'),
  '#rows' => 5,
);

```

The following code saves the posted data in the database.

```
$query = db_insert('my_table')
  ->fields(array(
    'full_detail_text' => $form_state->getValue('english_copy_text')[value],
    'date' => REQUEST_TIME,
  ))
  ->execute();

```

I am using a view page display to render this output, but the output for this field is displaying data as plain text (no formatting) along with HTML code instead of formatted data same as in the editor.

Is there a configuration setting I need to adjust or perhaps `hook_views_pre_render()` to transform this field's data from plain text to HTML markup?

# Answer
I have achieved above by not using any hook except following steps.

STEP 1:

$query = db\_insert('my\_table') -\>fields(array( 'full\_detail\_text' =\> check\_markup($form\_state-\>getValue('full\_detail\_text')\['value'\], 'full\_html'), 'full\_detail\_format' =\> $form\_state-\>getValue('english\_copy\_text')\[format\], 'date' =\> REQUEST\_TIME, )) -\>execute();

STEP 2:

MY\_MODULE.views.ins file...

Add following code to the table.field so as it renders output as markup/html.

'field' =\> array( // ID of field handler plugin to use. 'id' =\> 'markup', ),

This solution applies to any html data which should be rendered on view display.
> 0 votes

# Answer
I believe you can use `check_markup` to render the text in the specified format. In your example, you'd want to also save the format, something like:

```
$query = db_insert('my_table')
  ->fields(array(
   'full_detail_text' => $form_state->getValue('english_copy_text')[value],
   'full_detail_format' => $form_state->getValue('english_copy_text')[format],
   'date' => REQUEST_TIME,
  ))
 ->execute();

```

Then when you go to render it in the `hook_views_pre_render`

```
$rendered_markup  = check_markup($full_detail_text, $full_detail_format),

```

For more info, see: https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check\_markup/8.3.x
> 1 votes

---
Tags: wysiwyg, input-formats
---


# Question
Title: How to render html tags in field collection items?
How is it possible to render also the html tags of a field collection item? If i do something like this in a textfield (Full html) of an item:

```
<div class="test">TEST</div>

```

I also get this in frontend, with no rendered html tags.

Node Theme:

```
<div id="accordion" class="panel-group">
{% for details in node.field_cv %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="panel-toggle " data-toggle="collapse" data-parent="#accordion" href="#content">
<span>{{ details.getFieldCollectionItem().field_cv_title.value }}</span>
</a>
</h4>
</div><!-- /.panel-heading -->
<div id="content" class="panel-collapse collapse">
<div class="panel-body">
{{ details.getFieldCollectionItem().field_cv_details.value }}
</div><!-- /.panel-body -->
</div><!-- /.content -->
</div><!-- /.panel -->
{% endfor %}
</div>

```

Thanks for helping!

# Answer
> 0 votes
When you use Field Collection you get nested templates. So start with the outer div container in the node template:

```
<div id="accordion" class="panel-group">
  {{ content.field_cv }}
</div>

```

This produces a new set of templates, which you can see when you switch on Twig Debug. The next level is the field template:

*field--field-cv.html.twig*

```
{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes }}>
      {% for item in items %}
        <div{{ item.attributes }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}
    {% for item in items %}
      <div{{ attributes }}>{{ item.content }}</div>
    {% endfor %}
  {% endif %}
{% else %}
  <div{{ attributes }}>
    <div{{ title_attributes }}>{{ label }}</div>
    {% if multiple %}
      <div>
    {% endif %}
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
    {% if multiple %}
      </div>
    {% endif %}
  </div>
{% endif %}

```

and inside you'll find the field collection templates:

*field.collection.html.twig*

```
{%
  set classes = [
    'field-collection-item',
    'field-collection-item--name-' ~ field_collection_item.name|clean_class,
    'field-collection-item--view-mode-' ~ field_collection_item.view_mode|clean_class,
  ]
%}
<div{{ attributes.addClass(classes) }}>
  <div class="content"{{ content_attributes }}>
    {{ content }}
  </div>
</div>

```

Which you all can use for the custom html markup.

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


# Question
Title: How to create rule to redirect an admin after log in to an admin specific node?
I have different roles for users of my Drupal 7 site. I have added a rule that whenever an authenticated user logs in they are directed to a node (say node/90). This works fine: both admin and authenticated users are redirected.

However I want that the admin be redirected to a different node say `node/25`. So I added a new rule and selected under condition that user role is administrator and in action also forced a redirect. However the admin still redirects to `node/90`. Why so and how can I achieve my use case?

As suggested by NikhilM, I have created a custom module for it and the .module file has

```
    <?php

function redirect_ad_help($path, $arg) {
  switch ($path) {
    case "admin/help#redirect_ad":
      return '<p>' . t("Redirect") . '</p>';
      break;
  }
}
function redirect_ad_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('node->97');
 else
  drupal_goto('node->69');
}

```

I also tried doing `$edit['redirect'] = 'node/97';` instead of `drupal_goto()` but I am taken to the home page only and not to the desired node.

# Answer
> 4 votes
My guess would be that your rule weights are not as they should be. If your rule that matches the admin role fires *first* and your rule that matches all authenticated users fires *second* then admins will always be redirected to node/90.

Check on the weights. In your case, you want the more specific rules (the one for admins) to fire second. So you need to make its weight larger than the more general rule.

Does that make it work for you? I don't think you should need a custom module for this...

Also - disable the custom module while you're testing this out, to make sure the two are not interfering.

# Answer
> 1 votes
You can do that with hook\_user\_login

```
function hook_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('node/25');
 else
  drupal_goto('node/90');
}

```

replace `drupal_goto('node->97');` with `drupal_goto('node/97');`

Give it a try let me know the result.

# Answer
> 0 votes
Even though the currently accepted answer may have helped to solve the issue in the question, I think it is not 100% accurate (not correct, maybe even a bit misleading). Moreover there is an alternative solution also. Read on for more details ...

# About using Rules Weight

To indicate a "*weight*" for a custom rule, you use the field in the rules UI that looks like so:

Note what is written below that weight field, i.e "***`Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight`***".

Let's apply this to what's suggested in the currently accepted answer:

* There are 2 rules, which both seem to react to the same event (= "User has logged in").
* By changing the weights of both rules, the rule with the lower weight is executed first, and the one with the higher weight afterwards. Quote from the accepted answer:

> ... you want the more specific rules (the one for admins) to fire second. So you need to make its weight larger ...

That's indeed "a" way to get it to work (to meet the specs as in the question). However, it does also mean that BOTH rules are executed, for anybody (not just admins ...) who performs a login:

* The 1st rule for authenticated users gets executed for anybody who performs a login (note: so also for admins ...). That is, the redirect to `node/90` gets executed.
* Authenticated users that **do not have** the admin role, do not satisfy the Rules Condition, so the Rules Action of the 2nd rule for admin does not execute.
* Authenticated users that **do have** the admin role, do satisfy the Rules Condition, so the Rules Action of the rule for admin does execute. That is, the redirect to `node/25` gets executed also.

The result of this is that for a use that has the admin role, actually 2 redirects are performed: first to `node/90` (as per the 1st rule), followed by a redirect to `node/25` (as per the 2nd rule). For those who don't believe (or get) it: just add a Drupal action like "Show a message on the site" in both rules (for admins you'll get both messages).

# Alternative to using Rules Weight

Apart from redundant Rules logic that gets executed (as explained above), using Rules Weights to get things to work (= implement the appropriate execution sequence) has some challenges, which I try to avoid whenever possible.

In this case (= scenario in the question), an alternative solution appears to be to use the Conditional Rules module. Have a look at this rule (in Rules export format) which uses this module, and which also implements the very same logic as described in the question:

```
{ "rules_redirect_each_role_to_separate_page" : {
    "LABEL" : "Redirect selected roles to selected pages",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } },
            "DO" : [ { "redirect" : { "url" : "node\/25" } } ]
          },
          { "ELSE" : [ { "redirect" : { "url" : "node\/90" } } ] }
        ]
      }
    ]
  }
}

```

After you enabled the Conditional Rules module, just use the Rules UI to import the above rule in your own site, enable the rule, and see what happens ... No need for "Rules Weight", and only using a single rule (to see the entire Rules logic in a single screen when using the Rules UI). And for users that do have the admin role, there is no (repeat: no) redundant redirect to `node/25`.

What is more: imagine that you'd have to implement a redirect that depends on (say) 5 roles, so that you need to redirect to one of 5 pages. All it's take is to extend the IF/THEN/ELSE logic with 3 more appropriate redirects (instead of tuning the Rules Weights for 5 different rules ...).

---
Tags: 7, users, rules, redirection
---


# Question
Title: D8 - Access Webform submission values programatically
I have a webform whose results (some specific fields) I want to display in a table in a view. I am able to achieve that using the Webform Views Integration module. The view displays the output as

```
<label>Field Name</label>
Field Value

```

I want it to be displayed as

```
<p>Field Value</p>

```

Although it can be done via CSS using `label{display:none;}`, is there any way to do it out of the box or using modules?

Also, I want to overwrite the default webform submission layout which I can achieve using the answer here. But when I try to access the elements of the webform submission using `{{html.fieldName}}` or `{{data.fieldName}}`, it again prints out the label with it. I tried the `nolabel` filter but it does not work.

# Answer
> 0 votes
You need to apply the patch from this issue.

---
Tags: theming, 8, webforms
---


title: Webform custom composite

text:
# Question
Title: Webform custom composite
Could someone advise on how to adopt the working composite example that comes with Webform in Drupal 8?

https://www.drupal.org/node/2824714 suggests it can be done.

I've copied the example from modules/webform/modules/webform\_example\_composite folder. Does this need to go into the webform root folder with other example or root module folder?

I realise that the functions and iterations of webform\_example\_composite need to be renamed.

I also tried altering the pr-existing example that comes with Webform, without success.

# Answer
Someone very kindly posted an example https://www.drupal.org/node/2883734. Module creator also suggested here https://www.drupal.org/node/2824714 that documentation is being updated.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to notify users when a new comment is posted in the same page as they did?
I have a Drupal 7 website and I display comments on a content type.

What I want, is for every user to have a boolean field in their profile, to declare if they want to be notified when a new comment is posted at the content type that they posted.

I tried the Comment Notify module, but it shows its options right before you post your comment, and doesn't have a use with user profile/field.

I have already achieved a similar notification, for the user to be notified when the administrator replies to one of the user's comments.

I managed it using the Rules module, before a comment is posted, with these Rules Conditions:

* Entity has field (`comment:parent:author`) and Data Comparison, to verify a relevant boolean at the user profile.
* Data Comparison, for the (`comment:author:roles`) to be administrator.

Although, I can't seem to achieve the requested rule.

I know I have to do a search for every commenter at the same node, before a comment is posted, if they have the boolean enabled at their profile, but I can't create it with Rules.

To sum up, I have a content type (projects) and I have created about 50 of them. If some user X posts a comment on one of the projects and has the boolean enabled, then if anyone else comments on the same project, user X will be notified by email.

Any help?

# Answer
> 4 votes
Have a look at this rule (in Rules export format), which does what you're asking for:

```
{ "rules_notify_commentors_about_new_comment" : {
    "LABEL" : "Notify commentors about new comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "users_that_commented" : "Users that commented" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "comment:node:comments" ] },
          "ITEM" : { "current_comment_item" : "Current comment item" },
          "DO" : [
            { "list_add" : {
                "list" : [ "users-that-commented" ],
                "item" : [ "current-comment-item:author" ],
                "unique" : "1"
              }
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-that-commented" ] },
          "ITEM" : { "current_comment_author" : "Current comment author" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : {
                      "data" : [ "current-comment-author:field-accept-boolean" ],
                      "value" : "1"
                    }
                  },
                  "DO" : [
                    { "mail" : {
                        "to" : [ "current-comment-author:mail" ],
                        "subject" : "New comment to node with id [comment:node:nid]",
                        "message" : "There is a new comment added to the node with id [comment:node:nid]",
                        "language" : [ "" ]
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

The only additional module needed is the Conditional Rules module, while it does use a few of the more advanced techniques available in the Rules module.

If you're familiar with reading/digesting Rules in Rules export format, I'd hope the rule is self explaining. If not here is a summary of the above rule:

* Rules Event: obvious ... after saving a new comment.
* Rules Conditions: feel free to add whatever fits (eg limit to selected content types only, like "*Projects*" in this specific question).
* Rules Actions:

+ Add a variable "`users_that_commented`" (= a list of users).
    + Loop over all existing comments, and for each comment author, add that author to the list of users (= `users_that_commented`). Note the "unique" that is turned on (we do not want duplicates in that list of users).
    + Loop over the list of users (= `users_that_commented` ... again, which we just created and populated). And for each user in that list, do your thing, in this case "send an eMail", provided the field `field_accept_boolean` is TRUE (which you can check if you have the Conditional Rules module enabled). The "To" value is crucial here, the body, the from, the title, etc is up to your own imagination. If you don't want to use the Conditional Rules module, you could also rework the Rules Action withn the last Rules Loop to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

If you want, just import the above rule in your own site (using the Rules UI), after you enabled the Conditional Rules module, and after replacing the field name of `field_accept_boolean` to fit the machine name of your own field.

That's really all it takes ... a Rules variable, Rules lists and loops, and Conditional Rules.

PS: There is one minor improvement of this rule I can think of (if perfect is not good enough) ... After anybody finds out what that may be, and after the question details are corrected about that also, I'd be happy to update my answer (= change 1 detail in the rule) to also implement that.

# Answer
> 2 votes
You can achieve what you want with Flag and Rules. To notify users, you can use the Message module. Here is a possible outline to make things work:

1. Create a node Flag *Follow*.
2. Create a Message type *New comment*.
3. Create a Rule that launches when a user commented on a node:
    * Check that the node's content type is *Projects*.
    * Fetch all users who flagged the node with *Follow*.
    * Loop through this list and create a *New comment* message for every user in the list.
    * (Bonus: depending on the text in your notification, you may want to set some of your message's fields. e.g. If you use Entity Reference, then you can refer to the user who commented and use his/her username in the message, for example.)
4. Create a second Rule that launches when a user commented on a node:
    * Check that the node's content type is *Projects*.
    * Verify that the commenting user checked the checkbox for receiving notifications.
    * Let the commenting user flag the node with *Follow*.

Assuming that the above steps are clear enough, I will not add an export of the Rules in question. By the way, if you want to notify users with an email, then you can forget about the Message module and simply replace the action(s) in the loop of the first Rule by "Send an email".

---
Tags: 7, rules, emails, comments, notifications
---


# Question
Title: How to change client session variables during a functional browser test?
I have a session variable, that once set changes block output of the system branding block. Normally this variable is intercepted from the query string by an inbound path processor, however that is a different test. In this test I just want to make sure the output is as expected.

So I set up my test as follows:

```
class ConfigOverrideCacheTest extends MyLabelTestBase {

  protected function setUp() {
    parent::setUp();

    $this->tokenOwner= $this->drupalCreateUser(['my permission']);
    $this->drupalLogin($this->tokenOwner);
  }

  public function testNotoken() {
    $this->drupalGet('<front>');
    // Check site name is Drupal.
    $this->assertSession()->elementTextContains('css', '.block-system-branding-block', 'Drupal');
  }

  public function testToken() {
    // Set session variable.
    \Drupal::service('session')->set('my_session_key', 'value');

    $this->drupalGet('<front>');
    // Check site name is NOT Drupal.
    $this->assertSession()->elementTextNotContains('css', '.block-system-branding-block', 'Drupal');
  }

}

```

This second test keeps failing, and the output is the same as in the first test. Which I suspect to be because it is set in the testrunner session, rather than the actual testing session.

How so set (or synchronize) session variables from the testrunner to the site that gets tested?

# Answer
Referring SessionTest, there is a test-module (session\_test) in place, which get's enabled:

```
  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('session_test');

```

And then called by GET request to set the session value:

```
 $this->drupalGet('session-test/set/' . $value_1);

```

> I guess this procedure makes it really independent from the runner ..

So - make your module with one callback in .routing.yml, setting your session value in your controller. Your method afterwards could look like this:

```
public function testToken() {
  // Set session variable.
  $this->drupalGet('session-set/my-session-key/value');

  $this->drupalGet('<front>');
  // Check site name is NOT Drupal.
  $this->assertSession()->elementTextNotContains('css', '.block-system-branding-block', 'Drupal');
}

```

And, don't forget to enable the created module ;)

---

For completness, here the (above linked) SessionTest routing.yml:

```
session_test.set:
  path: '/session-test/set/{test_value}'
  defaults:
    _title: 'Set session value'
    _controller: '\Drupal\session_test\Controller\SessionTestController::set'
  options:
    no_cache: TRUE
    converters:
      test_value: '\s+'
  requirements:
    _access: 'TRUE'

```

and Controller:

```
public function set($test_value) {
  $_SESSION['session_test_value'] = $test_value;

  return ['#markup' => $this->t('The current value of the stored session variable has been set to %val', array('%val' => $test_value))];
}

```
> 1 votes

# Answer
I am not sure if the storage you use to save the `my_session_key` attribute is shared between the testrunner and the site that gets tested, and that could explain why the test fails.

Why not test exactly the case of the inbound path processing, e.g.:

```
public function testToken() {
  $options = [
    'query' => [
      'param' => 'value',
    ]
  ];
  $this->drupalGet('<front>', $options);
  // Check site name is NOT Drupal.
  $this->assertSession()->elementTextNotContains('css', '.block-system-branding-block', 'Drupal');
}

```

Good luck in any case!
> 1 votes

---
Tags: 8, testing, sessions
---


# Question
Title: How to show thumbnail for image when edit the node Drupal 8
I need to add thumbnail for field image when I edit node

Field settings and type: Could you please explain How to do it. Thanks.

# Answer
I resolved that issue.

Me steps:

* go to image style and create new image style (/admin/config/media/image-styles).
* go to View modes (/admin/structure/display-modes/view)
* find Media section and create new view mode for media (/admin/structure/display-modes/view/add/media)
* go to Media bundles (/admin/structure/media).
* edit Image and go to Manage display (/admin/structure/media/manage/image/display)
* click edit to your view

Now we can configure Paragraph content type or Content type
> 1 votes

---
Tags: entities, media
---


# Question
Title: Syntax error or access violation: 1067 while installing module
I am getting error while installing custom module. please let me know where am i doing wrong.

```
function product_enquiry_schema() {
  $schema['product_enquiry'] = array(
    'description'=>'product enquiry',
    'fields'=>array(
      'id' => array(
        'description'=>'primary key value',
        'type'=>'serial'
      ),
      'product_id'=>array(
        'description'=>'product\'s id',
        'type'=>'int',
        'default'=>0
      ),
      'email'=>array(
        'type'=>'varchar',
        'length'=>100
      ),
      'message'=>array(
        'type'=>'varchar',
        'length'=>255
      ),
      'status'=>array(
        'type'=>'int',
        'default'=>1
      )
    )
  );

  return $schema;
}

```

# Answer
You need to set the default value of id column or simple replace the above code with the following one:

```
'id' => array(
        'description'=>'primary key value',
        'type'=>'serial'
        'unsigned' => TRUE,
        'not null' => TRUE,
 ),

```
> 1 votes

---
Tags: database
---


# Question
Title: Is it possible to render a twig template for "later use"?
I have been asked to create a custom module that outputs a node's content in a way that it will be easy to print or export to pdf.

I came accross this question and this is litteraly what I'd like to do, but I can't manage to adapt it to Drupal. I've seen quite a lot of potential solutions, but I don't know if they'd help.

Here is what I did so far:

```
// My module's route is '/pdf/node/{nid}

$route_match = \Drupal::service('current_route_match');
$node = $route_match->getParameter('nid');
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$result = $node_storage->load($node);

$response['title'] = $result->getTitle();
$path = DRUPAL_ROOT . '/modules/custom/mymodule_pdf/templates/node.html.twig';

// It would look like so:
$template = $this->get('twig')->render($path, 'title' => $response['title']);

```

So far, the twig file just contains the following:

```
<h1>{{ title }}</h1>

```

So `$twig` would contain `<h1>The node's title</h1>`

And all I'd need to to is to put the $twig content as my future pdf's content, but this is the easiest part.

Is this possible to do this?

# Answer
Normally you don't render twig templates directly, but build the content in a render array and use the render service:

```
public function nodeExportPdf(NodeInterface $node) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $build = $view_builder->view($node, 'full');
  $html = \Drupal::service('renderer')->renderPlain($build);
  ...
}

```

This will use the node template configured for the view mode you specify in the view builder. In this example `full`, but probably you want to create a custom view mode for the pdf.

When you are in a controller you get the route parameters in the function arguments. How to build the route for this see https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Drush make: simplexml_load_file(): I/O warning : failed to load external entity "" Project.php:74
I'm facing a very strange issue with Drush wget and OpenSSL on my mac book (MacOSX Sierra).

When I launch drush make site.make command (which should theoretically download the all modules) it fails with the following error:

```
Failed to get available update data from https://updates.drupal.org/release-history/workbench_og/7.x
simplexml_load_file(): I/O warning : failed to load external entity "" Project.php:74

```

I tried

```
wget https://updates.drupal.org/release-history/rate/7.x

```

and I got the following message:

```
https://updates.drupal.org/release-history/rate/7.xResolving
updates.drupal.org... 151.101.113.175
Connecting to updates.drupal.org|151.101.113.175|:443... connected.
OpenSSL: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Unable to establish SSL connection.

```

Same message with flags:

```
wget https://updates.drupal.org/release-history/rate/7.x --no-check-certificate

```

Here I found exactly the problem that I have but, even if reinstalling openssl and upgrading the version (current version is OpenSSL 1.0.2l 25 May 2017) the problem persists.

Did someone has the same kind of issue? And, in case, how did you handle it?

Thank you in advance!

# Answer
This workaround fixed my issue:

In **drush.inc**

```
if ($use_wget) {
  drush_shell_exec("wget --no-check-certificate -q --timeout=30 -O %s %s", $destination_tmp, $url);
} else {
  drush_shell_exec("curl --insecure --tlsv1 --fail -s -L --connect-timeout 30 -o %s %s", $destination_tmp, $url);
}

```

so weird anyway...
> 1 votes

---
Tags: drush, ssl
---