title: hook_nodeapi is not working in D8

text:
# Question
Title: hook_nodeapi is not working in D8
As per the api the **`hook_nodeapi`** should be called before saving the node .But its not calling the function at all when i try to save the node . How could i solve this ?

```
/**
 * hook_nodeapi, this function used to intercept the node before doing any
 * action on it
 *
 */
function module_name_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    echo 'in hook_nodeapi';exit;
    call_fn_on_save($node, $op);
}

```

# Answer
`hook_nodeapi` was in Drupal 6 (which is not supported now) and has been removed starting from Drupal 7. In Drupal 8, if you want to do something when Node/Entity has been created/updated you can check respective `hook_entity_[HOOK]` or `hook_ENTITY_TYPE_[HOOK]` provided by Entity API. A complete list of all hooks provided by Entity API in Drupal 8 Core can be accessed here.
> 4 votes

---
Tags: nodes, 8, hooks
---


# Question
Title: how to pass the query parameters as default values in buildForm?
```
public function buildForm(array $form, FormStateInterface $form_state) {
    // in D7 it was : $params = drupal_get_query_parameters();

$form['search_api_fulltext'] = array(
'#type' => 'textfield',
'#title' => $this->t('Faites une recherche'),
  // in D7 it was: '#default_value' => isset($params['search_api_fulltext'])?str_replace('+', ' ',$params['search_api_fulltext']):'',
);
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Recherche'),
'#button_type' => 'primary',
);
return $form;

}

```

# Answer
there might be a better method as suggested in the comments. I replaced

```
    $params = drupal_get_query_parameters();

```

by

```
    $params=\Drupal::request()->query->all();

```
> 1 votes

---
Tags: forms, 8
---


# Question
Title: Add attributes to a template based on current node
I need to add a style attribute to the .region-content tag in order to set a field-dependent background image.

How do I do this? I have the node in page.html.twig in the page.node variable, but not in region.html.twig, and there doesn't seem to be a way to transfer it from one to the other at that level.

Edit:

This seemed like a good first attempt:

```
function [THEME]_preprocess_page(&$variables) {
  $variables['page']['content']['#context']['node'] = $variables['node'];
}

function [THEME]_preprocess_region(&$variables) {
  if ($variables['region'] == 'content') {
    var_dump($variables['context']);
  }
}

```

Unfortunately, that doesn't work - the context variable is still an empty array. How do I transfer context from one theme element to one of its children?

This could be done with a global\* variable or something, but that looks horrendously inelegant.

Edit: Well, preferably a call to a function with a static variable, but that still seems like a bad hack.

# Answer
In Drupal 8 you can get the node object from the routing system:

```
function [THEME]_preprocess_region(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
}

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to configure the CORS module for multiple domains?
I have JSON content I want to deliver to multiple domains. I have installed the CORS module. I have configured to deliver to one domain like this:

```
*|<mirror>,http://www.other-domain.com

```

This works. However, I want to configure for a list of domains and can't work out how to configure that. The following doesn't work:

```
*|<mirror>,http://www.other-domain.com,https://www.and-another.com

```

Nor does

```
*|<mirror>,http://www.other-domain.com
*|<mirror>,https://www.and-another.com

```

How do I configure this?

# Answer
> 1 votes
Upon further investigation, this seems to be an issue with the CORS module, and has been patched, so hopefully fixed in future versions.

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

---
Tags: javascript, 8
---


# Question
Title: Taxonomy autocomplete returns "connection reset"
I have an autocomplete issue on an otherwise functional Drupal 8 site. I'm hoping someone has either found and fixed this problem before, or can steer me on how to diagnose it myself.

When editing a node, taxonomy autocomplete fields appear to hang - the spinner keeps going round forever. However, looking at the Network inspector, the lookup has returned "Connection Reset".

Further information:

* Other kinds of autocomplete work on the site (e.g. node lookup when adding a redirect)
* I am logged in as an admin user with full permissions to everything
* The vocabulary is not empty
* The autocomplete field is set to "create if term doesn't exist".
* The form saves fine on submit, either creating a new term or working out which term to link to if I enter the exact text correctly
* I am on the second-latest version (8.1.9)
* Accessing the lookup URL directly from a separate tab gives "This site can't be reached / the connection was reset"
* PHP error log - empty
* Drupal "recent errors" log - empty
* Behaviour same in Chrome and Firefox
* Linux server, Windows client for browsers

The URL being accessed looks like this: http://\[mysite.co.uk\]/entity\_reference\_autocomplete/taxonomy\_term/default%3Ataxonomy\_term/UhDfSC7PJL0Sf6NxfMCVY27CaUM15rrS-gVsL6eD66E?q=\[search\_term\_here\]

**EDIT:**

As requested, here's the list of contributed modules:

* *Protected Pages*
* *AT Theme Generator*
* *AT Tools*
* *Admin Toolbar*
* *Admin Toolbar Extra Tools*
* *Adminimal Admin Toolbar*
* *Chaos Tools*
* *Chaos Tools Views*
* *Chaos Tools Blocks*
* *Bigpipe*
* *Calendar*
* *Calendar Datetime*
* *Devel*
* *Feeds*
* *Audiofield*
* *Computer field*
* *Datetime*
* *Image*
* *Simple Google Maps*
* *Image Effects*
* *IMCE File Manager*
* *Backup & Migrate*
* *Blog*
* *Coffee*
* *CookieConsent*
* *Entity*
* *Exclude Node Title*
* *Libraries*
* *Masquerade*
* *PathAuto*
* *Profile*
* *Redirect*
* *Redirect Import*
* *Scheduler*
* *Special Menu Items*
* *Token*
* *Twitter Block*
* *Typed Data*
* *User Display*
* *Supercache*
* *Rules*
* *Security Review*
* *Honeypot*
* *Google Analytics*
* *Flood Unblock*
* *Superfish*
* *Views PHP*
* *Views Slideshow*
* *Views Slideshow Cycle*
* *Views templates*

# Answer
So after much frustration, I've finally got to the bottom of this. The answer is not within Drupal, but rather in my cPanel setup. I'll post the answer here because it may save someone else the headaches I've had.

The problem was that my cPanel hosting had xVarnish enabled. I'm not sure if it was suddenly added by a package upgrade, or if the behaviour changed, or if its effect only kicked in after a certain time span, but I certainly didn't switch it on! In any case, disabling xVarnish not only fixed this problem but also an "access denied" on image styles that had cropped up too.
> 0 votes

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


title: How to make a map black and white?

text:
# Question
Title: How to make a map black and white?
I created a view (using Views) which shows node locations in a map using Location and Gmap modules.

How can I make map black and white?

# Answer
Add a `class` name for node locations field, for example "`nodeLocation`"

and in `style.css`

```
.nodeLocation{
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
}

```
> 0 votes

---
Tags: views, google-maps
---


# Question
Title: How can I install modules using the FTP method?
I got a error when trying to install modules. What should I set up for the FTP? I just learned Drupal. Who knows what happen? I am using Drupal 7.7.

# Answer
> 6 votes
As kalabro said:

Make sure the folder /sites/default is OWNED by the user that executes the drupal scripts.

On most Ubuntu installations, this is the user Apache user www-data.

```
chown www-data sites/default

```

# Answer
> 4 votes
Updating modules using that method works only if the server running Drupal also runs a FTP server; in that case, you need to enter the username and the password to connect to the FTP server. The server is normally "localhost" as both the web server and the FTP server are running from the same IP; if that is not the case, then you should change "localhost" with the name of the server (e.g. ftp.example.com).

If you are running Drupal on your local computer, as when you use it as testing site, then if you don't have a FTP server on your computer, you cannot use that way to update modules; in that case, you just copy the files on your computer, after you download the archives containing the updated versions.

# Answer
> 2 votes
Do not make www-data own /sites/default or any other folder except for /sites//files or /files once the site is live. The "install module" feature within drupal should only be used during site development, when the site is not live. The server should not be able to write to /sites/all or /sites/default or any other folder (except files) as this is a security risk. Again, it may seem convenient to do it that way, but having the server write to any folder except files is a very bad plan. You may be pwned.

# Answer
> 1 votes
I have run the following command and it workes wonder!!

```
sudo chown -R www-data sites/default

```

# Answer
> -1 votes
In case, if you've access to `/sites/all/modules` directory then you can also prefer directly uploading the `module-name.tar.gz`:

* extract the zip copy the directory to `/sites/all/modules/`
* In web-site, navigate through `admin-bar -> modules`
* check the module in the list
* Save configuration

This should install the new module.

---
Tags: updating
---


# Question
Title: Override html.tpl.php by content/node type
I'm trying to build a new template for PPC landing pages. The template design is very different than the main template, therefore I'm trying to override html.tlp.php for a specific content type.

The content type machine name is "landing\_page".

I've created the following:

html--landing\_page.tpl.php (everything in the header and footer) page--landing\_page.tpl.php (everything in the content area)

I got Drupal to read page--landing\_page.tpl.php, but can't get it to read html--landing\_page.tpl.php instead of the default html.tpl.php.

I've already tried the code at Override html.tpl.php per node type, but it doesn't work even after clearing the cache multiple times.

Here's what my preprocess\_html function in template.php looks like:

```
  function bartik_preprocess_html(&$variables) {

  $node = menu_get_object();

  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
  }

 /* if ($vars['node']->type == 'landing_page'){
     $vars['theme_hook_suggestions'][] = 'html__landing_page';
  }
*/

  if (!empty($variables['page']['promo'])) {
    $variables['classes_array'][] = 'promo';
  }

  if (!empty($variables['page']['triptych_first'])
    || !empty($variables['page']['triptych_middle'])
    || !empty($variables['page']['triptych_last'])) {
    $variables['classes_array'][] = 'triptych';
  }

  if (!empty($variables['page']['footer_firstcolumn'])
    || !empty($variables['page']['footer_secondcolumn'])
    || !empty($variables['page']['footer_thirdcolumn'])
    || !empty($variables['page']['footer_fourthcolumn'])
    || !empty($variables['page']['footer_fivecolumn'])
    ) {
    $variables['classes_array'][] = 'footer-columns';
  }

  drupal_add_js(path_to_theme().'/js/jquery.actual.js');
  drupal_add_js(path_to_theme().'/js/custom.js');

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}

```

# Answer
> 2 votes
replace

```
$vars['theme_hook_suggestions'][] = 'html__' . $node->type;

```

with

```
$variables['theme_hook_suggestions'][] = 'html__' . $node->type;

```

# Answer
> 0 votes
If you are specifically trying to load a different CSS file then you should use the hook\_css\_alter instead in a module file as it would be the preferred method. In this case simply use the same theme but just change the CSS file involved. If you need different regions overwrite the page.tpl.php file.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_css\_alter/7

```
function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
}

```

---
Tags: theming
---


# Question
Title: Creating a Redirect from old url to root
I'm trying to create a 301 redirect from a link from my old site format(because links are coming in from this URL).

The URL I'd like to redirect is like this:

http://www.example.com/Default.aspx?id=index

I'd like to simply have the above url redirect to the homepage:

http://example.com

I've tried several options, but nothing seems to be working. Any help?

# Answer
Assuming this question is about D7, you can use the Rules module for this, with a custom rule that looks like so:

```
{ "rules_redirect_some_path_to_the_frontpage" : {
    "LABEL" : "Redirect some path to the frontpage",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "Default.aspx?id=index",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path is no longer in use, you will be redirected automatically to the homepage" } },
      { "redirect" : { "url" : "[site:url]" } }
    ]
  }
}

```

If you have the Rules UI module enabled, you should be able to just import the above rule, then "enable" it, and that's all you'd need to do.

What this rule actually does:

* Check if the current path is `Default.aspx?id=index`
* If that's indeed the path, then a redirect to your frontpage will be performed.

**Note**: feel free to adapt the first Rules Action (to display a message), or if you don't want such message at all, just remove that Rules Action.
> 1 votes

---
Tags: redirection
---


# Question
Title: How to Change the Format of the Email Template Sent with Webforms
Ok, so I have a customer that has a ridiculously long form that individuals need to complete to apply for funding, but the email that is getting sent to our customer as well as each individual is not easy to read at all.

I have already installed MailSystem and MimeMail, so it is set to send in Full HTML, but it's still not that clear.

Is it possible to change the format so that the answer/response to each field is located below the field label? If possible, is this something that is relatively easy to do?

What about adding a line break between each field (label and response) so they aren't all one long list without any space to help distinguish between each one?

Any assistance with this would be GREATLY appreciated! We have a ton of nonprofit customers that all have similar forms and it would be very beneficial to have this option.

If you need any further clarification, just let me know.

Thank You!!

Nicole

# Answer
> 1 votes
Go to: `node/%nid/webform/emails/%mid` and there is a fieldset (E-MAIL TEMPLATE) where you can define your own email template (per mail account) by using all available tokens and by writting pure html (like `<p>, <strong>` etc) within the text-area. Don't forget to select "Custom Template".

Read more

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


# Question
Title: How to do social links with icons as a link field in a block?
I have a footer that contains a simple contact information and underneath is a social follow set of links.

I created the block type, with the thought that the top part (Connect) is a WYSIWYG.

My second thought was to make the Follow Us just a link field with 5 values, but I want to add a little flexibility and for theming concerns, I need to know what link goes with which service.

Can I either do this with the link field, or can I reference a menu somehow and attach it to this block type? As a menu, I can rig up menu attributes. But if there is a more practical way, I would like to know how to do it.

I do not want to hard code it because they might change URLs or want to reorder the list of services at any time.

# Answer
> 0 votes
I had a similar task, for me was better creating a **Custom Block Type**, named 'Social networks' with one field of type 'Link'.

In this field you can configure how many links you can handle (remember once you create one block of this type, you'll cannot change this value).

Once this **Custom Block Type** was created you can configure 'Manage form display' and 'Manage display' if you need.

Now you'll be able to create a **Custom Block** of type 'Social Networks' that provide a couple of links that you can set/edit, rearrange and use proper template per block, and place where you want.

This was the solution found to not use any piece of code.

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


# Question
Title: How to migrate data from custom user account fields to a single new field?
For my Drupal 7 User Accounts I have 5 separate fields (Field Type: Boolean, Widget: 'Single on/off checkbox') used to indicate comms preferences.

Without losing any data I want to migrate these fields to single field (Field type: 'List', Widget: 'Check boxes/radio buttons') but I am not sure how to achieve this?

# Answer
> 1 votes
# Step 1: Create a Rules Component

Have a look at this example of a **Rules Component** (in Rules export format):

```
{ "rules_search_and_replace_values_in_some_user_account_fields" : {
    "LABEL" : "Search and replace values in some user account fields",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "user" ], "field" : "field_accept_boolean" } },
      { "data_is" : { "data" : [ "user:field-accept-boolean" ], "value" : "1" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "user:field-accept-list" ], "value" : "yes" } },
      { "drupal_message" : { "message" : "Boolean field converted to list field for user with id \u0022[user:uid]\u0022 and name \u0022[user:name]\u0022." } }
    ]
  }
}

```

Some more details to further explain the above above example:

* This Rules Component will be used in the subsequent step.
* In my case I have a boolean field with machine name `field_accept_boolean` (values `true` or `false`, of course) and a list field with machine name `field_accept_list` (values `yes`, `no`, `later`).
* If `field_accept_boolean` = ***true***, then the value of the field with machine name `field_accept_list` will be set to ***yes***.

Note that I also added the Rules Condition `Entity has field` to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of the fields to match the machine name of your fields, and then you can simply import this Rules Component in your own environment.

After you did this, you can navigate to `admin/config/workflow/rules/components` in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***User identifier*** and hit the ***`Execute`*** mode. Depending on the user id you selected (if it has that field, and if the Rules Condition is satisfied), your user will be updated.

After you're confident your rule works perfect for all variations of your users, move on to the next step below.

# Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your **users** to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

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

# Step 3: 2nd iteration

With the previous Step 1 and Step 2, all users who have `field_accept_boolean` = ***true*** will have their `field_accept_list` will be set to ***yes***.

If appropriate, just adapt your rule in Step 1 (or clone it to a 2nd Rules component) so that all users who have `field_accept_boolean` = ***false*** will have their `field_accept_list` will be set to ***no***. Then repeat Step 2 (with this updated Rules component).

After doing so, ask yourself if there could be any users with a value for that `field_accept_boolean` which was never assigned either value. For those users, you may want to use yet another variation of Step 1 and Step 2, to have their `field_accept_list` will be set to ***later***.

Of course, you could have multiple fields similar to `field_accept_boolean`, which you might either migrate to the same `field_accept_list` (maybe with another value?), or a yet another field. For all thee variations it's just a matter of tuning the Rules component in Step 1, and then performing Step 2 again.

# Step 4: Straight forward variations

There are dozens (hundreds?) of straight forward variations of this question that can also be solved using the above combination of VBO and Rules. To just mention 1 of them, have a look at my answer to "How to bulk delete selected content/nodes?" ...

Happy VBO-ing while Rules-ing!

# Answer
> 0 votes
You can use "Feeds" -\> https://www.drupal.org/project/feeds to export all the data you need and import it again in the structure you want.

---
Tags: 7, users, entities, migrations
---


title: How to cache block for logged in user?

text:
# Question
Title: How to cache block for logged in user?
I have a block, created with a custom block plugin (extending BlockBase), that shows on every page, and I want to cache its data, to speed up performance.

I have added cache tags to the build() function:

```
$build['#cache']['tags'] = $cache_tags;

```

But the build() function is still executing on each page load. I guess because the cache tags are for render cache, not data cache.

Is there a built in way to cache the data in the build() function for a block for logged in users?

Or do I have to add custom caching in the build function, like this:

```
if ($cache = \Drupal::cache()->get($cid)) {

```

https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x

# Answer
> 3 votes
Blocks are cached by default. A block class with this build method:

```
public function build() {
    return [
      '#markup' => 'Block content',
    ];
  }

```

gets cached indefinitely or as long as you set in cache max-age.

If you add cache tags to the block that doesn't change whether the block is cached or not. The cache tags are used to invalidate cache items, not to store them. That is what cache keys are used for.

If the block gets cached, this is for logged in users, because the cache for anonymous users doesn't cache blocks, only pages.

# Answer
> 2 votes
One way to configure cache for a block is implement `getCacheTags` and `getCacheContexts` in your Block.

To cache per user, you can use this code:

**PHP Code:**

```
public function getCacheTags() {
  if ($user = \Drupal::currentUser()) {
    return Cache::mergeTags(parent::getCacheTags(), array('user:' . $user->id()));
  } else {
    return parent::getCacheTags();
  }
}

public function getCacheContexts() {
  return Cache::mergeContexts(parent::getCacheContexts(), array('user'));
}

```

Remember to import `Drupal\Core\Cache\Cache` in your Block class.

Copy this code to your Block and clear cache.

---
Tags: 8, caching
---


title: exposed filter dropdown by year

text:
# Question
Title: exposed filter dropdown by year
I am looking for a way to produce a dropdown filter by year of drupal 'post date'. i was able to produce somewhat of this result with an exposed criteria but that requires updating.

Is there a way i can just make the sort criteria exposed with dropdown of years?

this is what i have so far

```
if ($form_id == 'views_exposed_form_clone_of_post_by_date_block'){
  $year_filter = array();
  $years = array();
  $counter = 0;
  for ($i=date("Y");$i>=2009;$i--){
    $counter++;
    $years[$counter]=$i;
    $dstart = $i."0101";
    $dend = $i."1231";
    $year_filter[$counter] = array('title'=>$i,'operator'=>'between','value'=>array('type'=>'date','value'=>$i,'min'=>$dstart,'max'=>$dend));
    $form_state['input']['edit_created']['#options'] = $years;
  }

```

# Answer
> 4 votes
How to produce a dropdown filter by year of post date isn't as immediately obvious as you might think - but it doesn't need any custom code when using Drupal 7 with views.

Within your view add a new filter. You might think you need to choose 'Content: Post date' but this will **not** give you the options you need. You should **actually choose** 'Date: Date (node)'. For data selection form element choose 'select' to create your dropdown. Set Filter granularity to 'year'. Give a starting year e.g. '-10 years from now' and an ending year e.g. '+ 0 years from now'. Then in 'date fields' you select where the date(s) are drawn from, it is here that you choose the 'content: post date'.

It is worth noting that other date fields are exposed here, so you are not limited to the post date.

# Answer
> 0 votes
Bit old question, but in case someone else is looking for the "Date: Date (node)" filter: This filter will be only available if you enable **date\_views** module.

---
Tags: views, forms
---


# Question
Title: CommerceKickstart; Slideshow content/pages disappear if I add a Product Reference field under Slideshow Content Type
I am trying to add the "Add to Cart" button into a Slideshow. The problem is as soon as i add a Product Reference field under the Slideshow Content Type, if i than go to Content\>Manage Content the Slideshow Content Type/pages are no longer visible. At this point to add a new slideshow image/content i have to go to Products\>Add a Product. Somethings not functioning right. Im pretty sure theres something that im doing wrong but i cant figure it out....

# Answer
> 0 votes
if you want an slideshow that will display products you may want to create an slideshow that will display "product displays" and add to it an relationship with the products entity, then grab from there stuff like "add to cart" button, images, prices etc.

fields in the view may be in form of :

* \[product\_display\] - title
* \[product\_ref\] - price
* \[product\_ref\] - img
* \[product\_ref\] - commerce line item "add to cart"

# Answer
> 0 votes
Im pretty sure thats what I've been doing..... Ok so i started over.

1. I duplicated the Slideshow View (renamed it "Slideshow(Product)"
2. I created a new content type ("Slideshow(Product")
3. In "Slideshow(Product)" View i did the following:

3a. RELATIONSHIPS : Content: Product

3b. FILTER CRITERIA: Content: Type (= Slideshow(product)), Content: Published (Yes)

3c. FIELDS: Field: Title (Title), (Products referenced by field\_product) Commerce Product: Images (Products referenced by field\_product) Commerce Product: Add to Cart form (Add to Cart form)

In: Content types \> Slideshow(product) \> Manage display All required fields are Enabled (not Hidden)

Where am i going wrong here?...... :/

I remember reading a thread where a person wanted to do exactly the same thing as i am trying to do and all he did(according to him) was add a Product Reference field in the original Slideshow(at least thats what he said he did, and apparently it worked...

---
Tags: views
---


# Question
Title: Add language filter at admin/structure/block/block-content
I'd like to add a language selector in the form that filters. I've added it though a hook form alter:

```
$form["#info"]["filter-language"] = [
  "operator" => "type_op",
  "value" => "language",
  "label" => "Block language",
  "description" => ""
];
$language_options = [];
foreach (\Drupal::languageManager()->getLanguages() as $lang_code => $language) {
  $language_options[$lang_code] = $language->getName();
}
$form['language'] = [
  '#type' => 'select',
  '#title' => t('Block language'),
  '#options' => $language_options,
];

```

# Answer
That page is a view.

That means, you can simply edit the view and add fields, filters and so on in the UI. You can get there by finding the contextual links icon and clicking "edit view" or by going to "/admin/structure/views/view/block\_content/edit/page\_1".
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to get a specific field in a table layout in Views templates
This is my first time using a table to display a Views template. How do you access a specific field so you can reorder them one by one yourself? I have 3 fields I want to place but I want one of the fields `field_house` to come out first, followed by `field_door` and `field_table`. I'm also asking so I can wrap each one in their own class making it easier to layout.

# Answer
@Chaulky it should be pretty easy to make the changes suggested by @enhance.

* Take the views table template and copy it to your theme.
* Make the edits to your copy of the template as per @enhance's directions.
* Since you mentioned adding classes, you could either add the classes in the template or in the views interface.
* Save it as views-view-table-YOUR\_VIEW\_NAME.tpl.php.
* Clear caches, at least twice if once didn't do it.
* Continue theming and enjoy.
> 1 votes

# Answer
I'm late to this thread, but incase someone comes across it, here is example code that works.

I removed the code I didn't need from the Views tpl, and added the fields within the foreach loop.

```
<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
  <tbody>
    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <td class="views-field views-field-title">
          <?php print $row['title']; ?>
        </td>
        <td class="views-field views-field-field-website-url">
          <?php print $row['field_website_url']; ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Exporting nodes except for specific fields
I'm wanting to transfer a set of content from one drupal site to another - the field structure etc is the same but there are a couple of requirements:

1) I need to be able export only nodes of a specific content type. 2) I need to be able to exclude certain fields from being exported.

I've had a look at a few modules - Node Export, Backup and Migrate - but these don't appear to handle the exclusion of certain custom fields.

Could anyone point me in the right direction of a module that can do this?

Thanks!

# Answer
> 1 votes
Use feeds -\> https://www.drupal.org/project/feeds for custom export / import of nodes, users, taxonomy terms or simple database records

# Answer
> 0 votes
https://www.drupal.org/project/feeds Use feed module for import/export node and user.

---
Tags: nodes, migrations, importing-exporting, backups
---


# Question
Title: Is there a way to load content of each tab in the view using AJAX?
I've created View to display my content and I'm using Quicktabs module https://drupal.org/project/quicktabs to format the output of this view into the tabs.

Is there a way to load content of each tab in the view using AJAX? I can't see any option.

# Answer
I had a similar problem. The following code worked perfectly for me.

```
jQuery(".quicktabs-wrapper ul a").click(function(e) {
    e.preventDefault();
    jQuery(this).parents('.quicktabs-wrapper').find('.quicktabs_main  .quicktabs-tabpage').addClass('quicktabs-hide');
    showId = jQuery(this).attr('id').replace("-tab-", "-tabpage-");
    jQuery('#' + showId).removeClass('quicktabs-hide');
    jQuery(this).parent().siblings('li').removeClass('active');
    jQuery(this).parent().addClass('active');
  });

```
> 0 votes

---
Tags: views, ajax
---


title: Modification of email template

text:
# Question
Title: Modification of email template
I am working on a site where I changed the "email template" email to be sent on registration request to the user. How can I change the "email template" email sent to the site administrators?

I am using Drupal 7.

# Answer
It's also worth looking at the Mail Editor module. It makes the job of managing email templates easier and in combination with Token gives you more options for customizing emails.
> 1 votes

# Answer
Go to admin/config/people/accounts, Under **Emails** click Account Activation and then change as per your requirement. Use html and css for customization. See the below image

(or)

Use the second option below:

All the emails are being sent from the system and the content is editable as we want. To stylize the emails, use html mail module http://drupal.org/project/htmlmail

This module allows you to theme emails leaving the system as you would theme a normal Drupal site, and replaces the outgoing emails with those HTML versions per your settings.

hope it helps you!!!
> 2 votes

# Answer
I know this is pretty old, but if someone got into this issue please take a look at

User registration notification Module

This will help you out.
> 0 votes

---
Tags: forms, users
---


title: Same tpl.php for multiple blocks

text:
# Question
Title: Same tpl.php for multiple blocks
I have 14 blocks added through Drupal interface, for all of them I was override tpl.php file because I need some changes there (like `block--block--1.tpl.php`).

What I want to do is to create just one tpl.php file and apply it for all these blocks. So, if I need to change something someday, I change it just in one file instead 14 files.

How I can accomplish that in Drupal 7?

# Answer
As per template suggestion for Drupal 7, we have a general format as:

> block--\[region|\[module|--delta\]\].tpl.php
>
> base template: block.tpl.php
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> block--module--delta.tpl.php block--module.tpl.php block--region.tpl.php "module" being the name of the module and "delta", the internal id assigned to the block by the module.

Now, in order to override and define your own suggestions apart from these, you can provide new template suggestions in your theme template.php file file using template\_preprocess\_block as:

```
function mytheme_preprocess_block(&$variables) {
    $variables['theme_hook_suggestions'][] = 'common_block_template';
}

```

Now you place(create) this common-block-template.tpl.php file in your themes templates folder and it will be default template for all your blocks and don't forget to clear drupal cache.

**Note**: This templates will be applied to every block present in your Drupal 7 website i.e. user login block, content block etc.. So make sure you do define logic as per your page requirements as for example if you want to limit this template suggestion for just a uri name `mypage`, then

```
function mytheme_preprocess_block(&$variables) {
 if (current_path() == 'mypage') {
  $variables['theme_hook_suggestions'][] = 'common_block_template';
 }
}

```

**UPDATE:** To target delta (with numeric values & to avoid custom module block) the were created using Drupal 7 site building block module:

```
function mytheme_preprocess_block(&$variables) {
    $block = $variables['elements']['#block'];
   if (is_numeric($block->delta)) {
      $variables['theme_hook_suggestions'][] = 'common_block_template';
    }
 }

```

If you need to target just block which has delta of 1 then:

```
function mytheme_preprocess_block(&$variables) {
    $block = $variables['elements']['#block'];
   if ($block->delta == 1) {
      $variables['theme_hook_suggestions'][] = 'common_block_template';
    }
 }

```
> 2 votes

# Answer
Try `block--block.tpl.php` instead.
> 0 votes

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


# Question
Title: How do I show a 403 error page when the server returns a 403 error code?
I use the nginx config file from https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/

It has return 403 and deny all on some file.
Ex. When I visit `/core/CHANGELOG.txt`, nginx returns default 403 Forbidden page.
I want it to display **drupal 403 error page** not nginx white default 403 page.

I have tried adding `error_page 403 /403` but it returns

> # Not Found
>
> The requested URL "http://mysite/core/CHANGELOG.txt" was not found on this server.

# Answer
> 0 votes
From @googletorp and my google I found this solution

I added `error_page 418 = @blablabla; return 418;`.

```
location ~* \.(txt|log)$ {
    allow 192.168.0.0/16;
    deny all;
    error_page 418 = @blablabla; return 418;
}

location @blablabla {
    rewrite ^ /blablabla break;

    proxy_pass       http://localhost;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
}

```

This will return to 404 page as `/blablabla` is not found.

# Answer
> 0 votes
What you need to do is to configure nginx to serve a drupal page that generates a 403 page. There are severals ways to do this.

The easy solution is to route the traffic to Drupal (the index.php file), which would generate a 404 since the page doesn't exist in Drupal.

I think doing

```
location ~* \.(txt|log)$ {
  try_files @rewrite
}

```

should accomplish this for `.txt` and `.log` files. It should try to serve the file from Drupal. By default this will be a 404, but you can add the a route for specific files and return 403 instead.

---
Tags: 8
---


# Question
Title: Twig add attribute with value in a variable
**Using Drupal 8**

I want to print out a field's content into the `src` attribute. I have the following template for my view:

```
<div class="videoWrapperHD">
     <iframe width="560" height="315" src="{{ rows[0].content | raw }}"
      frameborder="0" allowfullscreen>
     </iframe>
</div>

```

But the iframe gets filled with my own site's "*Page Not Found*" page instead of the Youtube Video because Twig prints out a whole lot of debug comments before and after printing the variable `rows[0].content`.

Is it possible to disable the debug comments for a specific field? I don't want to have to be disabling/enabling debug to make sure it works as expected. Because **it works** if I disable Twig debugging (the comments aren't printed so the URL prints out fine) but it's tiresome to be enabling/disabling to check work.

I also tried using `{{ attributes.setAttribute('src', {{ rows[0].content }} ) }}` , but no dice.

Another failed attempt was:

```
{% set iframe_src = rows[0].content %}
<div class="videoWrapperHD">
    <iframe width="560" height="315" {{ attributes.setAttribute('src', iframe_src) }}
     frameborder="0" allowfullscreen></iframe>
</div>

```

My last idea was this:

```
{% set url = rows[0].content | raw %}
{% set iframe_src = 'src=' ~ url %}

<div class="videoWrapperHD">
   <iframe {{ iframe_src }} ></iframe>
</div>

```

But it prints out **src=Array**

**SOLUTION**

The answer is in another question, I'm pasting it here in case that one gets deleted. The author of the following answer is @4k4

`field.content` is the rendered field. And in views that means it is no longer a render array, but the finally rendered markup. So this is very problematic to use it as a class name, not only because of twig debug.

Better use the row data, where you find the entity object with the field data from the database. Use clean\_class to escape it for using it as a class name:

```
{{ row._entity.field_myfield.value|clean_class }}

```

# Answer
I'm pretty sure the nested braces here are an error - inside a `{{ }}` expression, variables don't need to be enclosed again:

```
 {{ attributes.setAttribute('src', {{ rows[0].content }} ) }}

```

But for the real answer: This template isn't the culprit - the `content` is already rendered separately, passing through its own template which adds the comments.

See Get Views field value in Twig template, where the recommended way of getting at the unrendered field value is via the `_entity` object.
> 1 votes

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


# Question
Title: A change in the production site affects test and staging sites and vice versa
I have a production site like www.example.com and I use 2 subdomains test.example.com and stage.example com for testing and staging purposes. Each of these 3 versions of the site uses it's own database. The user and password is the same for all 3 databases, but of course the database names differs. I have checked and double checked that the correct database names are set in the settings.php file for the 3 sites, respectively.

Nevertheless, when I do a content change in one of these 3 site versions, that same change becomes immediately visible in all 3 sites.

I have tried to turn off all my caching modules, like Boost and Memcache and Content.

**EDITED**: I have now narrowed it down to a caching problem. If I flush all cache in the site that shows the wrong content, it reverts to the right content. So content changes ends up in the right database. But as I said, even though I have all caching turned off, and all caching modules are disabled, all content changes in one site are immediately reflected in the 2 other sites (until I flush all cache in these 2 other sites).

Does anyone have an idea about where to look? Some common caching in the server environment?

# Answer
> 1 votes
What you're describing can happen when you link several sites up to the same cache system, but give the same prefix for each of them in settings.php (or don't provide a prefix at all, which is essentially the same thing).

I'm not 100% sure, but disabling the memcache module might not stop it being used if you're declaring its use in settings.php, which you most likely will be.

It might not be the cause, but it definitely could result in exactly the situation you find yourself in. Check settings.php in each of the sites, and see what the state of those prefixes are. If this *is* the problem, providing different prefixes for each site will fix it straight away.

---
Tags: 7, caching
---


# Question
Title: How to cache custom controller markup for logged-in users?
How do we set up a controller so the rendered output is cached?

Blocks are cached for logged in users by default, and the build function doesn't even run once the block is cached for logged in users.

I have some custom controllers for landing pages where I would like to cache the output for logged-in users.

I guess I could put everything within those controllers in a block or in several blocks, but is there a relatively simple way to make a controller behave like a block and not even run the build function once it is rendered for a logged in user?

# Answer
> 2 votes
One thing that you can do is the same as the entity view builder is doing, use a #pre\_render callback.

If you look at \Drupal\Core\Entity\EntityViewBuilder::viewMultiple(), you can see it doesn't really do anything except prepare the render array and add a #pre\_render callback to the whole thing.

The reason for that is that the pre\_render callback will only be called on a cache miss. So you return your array with the cache keys/tags/contexts/max-age, the renderer service will attempt to load from the render cache. On a cache hit, it will return the previously cached HTML, on a miss, it will call the pre\_render callback and you can do the things you want to do there.

# Answer
> 1 votes
You can make any render array or part of it cachable by setting cache keys. See this example from the entity view builder:

```
// Cache the rendered output if permitted by the view mode and global entity
// type configuration.
if ($this->isViewModeCacheable($view_mode) && !$entity->isNew() && $entity->isDefaultRevision() && $this->entityType->isRenderCacheable()) {
  $build['#cache'] += array(
    'keys' => array(
      'entity_view',
      $this->entityTypeId,
      $entity->id(),
      $view_mode,
    ),
    'bin' => $this->cacheBin,
  );

```

The variable cacheBin is set to `'render'`.

You can choose your own schema for the cache keys, dependent on the data you build the render array with. The cid to store the cache item is the result of the keys and has to be unique.

---
Tags: 8, caching, page-controller
---


# Question
Title: in ckeditor plugin, why isn't my getConfig returned array affecting editor?
I'm including the wordcount plugin to CKEditor in D8. I'm including some configuration (`maxWordCount`) through the configurable interface. The issue I'm having is that no matter what I return from `getConfig` there's no affect on the editor.

```
class WordCount extends CKEditorPluginBase implements CKEditorPluginContextualInterface {

  public function isEnabled(Editor $editor) {
    return TRUE;
  }

  public function isInternal() {
    return FALSE;
  }

  public function getFile() {
  return drupal_get_path('module', 'ckeditor_maxlength') . '/wordcount/plugin.js';
  }

  public function getConfig(Editor $editor) {
  // just return a hardcoded maxWordCount.
    return [
      'maxWordCount' => 10,
    ];
  }

  public function getButtons() {
  // No buttons needed.
  }
}

```

To be clear the counter works as expected, but I don't seem to be able to override the default configuration.

Inside the core ckeditor module the `getConfig` function has this notation:

```
* @return array
*   A keyed array, whose keys will end up as keys under CKEDITOR.config.

```

When I inspect `CKEditor.config` in the console I don't see the configurations, and infact, the `wordcount` plugin is buried in `CKEditor.plugins.externals`.

# Answer
> 0 votes
It turns out I was just formatting the array improperly. In order to return the configuration to my `wordcount` plugin I did this:

```
 return ['wordcount' => ['maxWordCount' => '10']];

```

---
Tags: wysiwyg, plugins
---


title: Drush install on Redhat 7 Errors PHP

text:
# Question
Title: Drush install on Redhat 7 Errors PHP
Installing drush is never the same on every linux system apparently. I'm on redhat 7 and and I just setup php 5.6 and installed composer, but I can't do a composer install on the fresh git repo of drush.

I'm getting the following error:

```
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

      Problem 1
        - Installation request for d11wtq/boris v1.0.10 -> satisfiable by d11wtq/boris[v1.0.10].
        - d11wtq/boris v1.0.10 requires ext-posix * -> the requested PHP extension posix is missing from your system.
      Problem 2
        - Installation request for phpunit/phpunit 4.6.6 -> satisfiable by phpunit/phpunit[4.6.6].
        - phpunit/phpunit 4.6.6 requires ext-dom * -> the requested PHP extension dom is missing from your system.

```

It's complaining about phpunit not being installed. So I went ahead and installed it:

> PHPUnit 5.6.2 by Sebastian Bergmann and contributors.

And I still get the same error when doing a composer install.

Can someone please explain why this always happens? You try to install something and it complains something isn't installed. You install that thing, but it still complains. Or better yet, you install something and it complains that something isn't installed and you install that thing and it complains some other thing isn't installed. Wasn't these package managers suppose to solve these dependency issues?

# Answer
The errors are pretty self-explanatory:

> The requested PHP extension posix is missing from your system
>
> The requested PHP extension dom is missing from your system

You need to install those extensions because packages that drush depends on in turn depend on them.
> 2 votes

---
Tags: drush
---


# Question
Title: How to create a User Feed using the modules Message and Flag?
What I'm trying to do is in theory easy : `**User** flagged **Article**`. But I'm having hard time figuring out how to build a user feed like this with Message and Flag modules.

I looked a little bit at the Message UI to create a message type, but can't seem to find a "`Flagging user`" token. The only related flag token I've found is **Users who flagged the entity with flag flag** which prints all users that liked an article like this:

**User A, User B, User C** flagged **Article**

What I really need is to print a message for every flag, like this:

* **User A** flagged **Article**
* **User B** flagged **Article**

And finally show everything in a view to the Article author.

Any suggestions?

# Answer
If you'd add the Rules module (on top of the Message and Flag module you're already using), you can get this to work by using the "Replacement tokens" as part of your "Message type" configuration.

If you're not familiar with these *Replacement tokens*, you can learn about it the answer to **What's the purpose of "Replacement tokens" of a Message type?** This answer also includes a sample rule which is similar to what you'll need: it makes the value of token `flagging-user` available to the Message type.

Some more details to resolve this specific question here:

1. Add a Replacement token in your Message type, and call it (say) `@user_who_flagged` (or `%user_who_flagged` if you prefer).
2. Use that `@user_who_flagged` (or `%user_who_flagged`) token anywhere you want in the message you're trying to produce.
3. Have Rules create your message (of the message type you're using), which you can do like so:

* Rules Event "Article gets flagged".
    * Rules Action "Create an entity" (corresponding to your Message type, and use a variable like (say) `entity_created` for that).
4. Add an appropriate Rules Action to pass the value of the "Replacement token" (which is used in the Message type as detailed above):

* which looks like `entity-created:arguments:user-who-flagged`, and
    * in which you pass the value `flagging-user` (***that's the clue to make it work*** ...).
5. Should you want to include additional info in your message about the actual Article (like nid, content type, title, author, whatever), then just create an additional Replacement token for each of them, and a similar Rules Action for each of them also.

With the above approach you'll have your messages created with the custom content you want. Those messages are Drupal entities, so creating an appropriate view from it is straight forward.

For anybody not familiar with the (great) Message module yet (which is poorly dcumented ...), here is your chance to get a first impression about it ... Below is an export of "a" message type that you could use to get started (by simply importing it in your own site). It actually works together with the example rule in the related question. This message type has machine name `user_following`, and uses a replacement token like `@following_user` (adapt both to fit your needs, eg change `@following_user` to `@user_who_flagged` to use what I suggested above):

```
{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

```

**Notes**:

* (to avoid confusion) `[message:user:name]` in the message type sample above is the user **to** which the message is targeted, not the flagging user!
* (if you still don't get the clue of all this) using Rules it's possible to make data originating from any module (such as the Flag module) available as tokens to the Message module.
> 2 votes

# Answer
If I understand your question correctly, this is how you need to set things up:

1. Create message and flag types you want to use.
2. Create a new rule that will be triggered when "A node/user/whatever has been flagged, under '\[your flag\]'".
3. Add action: Create new entity, select message and fill in the details.
4. To target the "flagging user" just use `[site:current-user]` token. This is invoked when the flagging action is taking place, meaning that the current user is the one you need.

Hope this helps.
> 0 votes

---
Tags: 7, flags, notifications, message-subscribe
---


# Question
Title: How to set page/content title/header from a controller
I have a custom route and module that outputs content to a page.

I want to also have a page/content title/header on the page. I've figured out how to set the browser title, but I can't figure out how to add the headline title.

When creating a basic page with no custom template, the headline is part of that html. I want to replicate this.

Here is what I have in my controller:

```
return array(
    '#title' => 'This sets the browser title',
    '#markup' => 'This is the html output',
);

```

I've been banging my head on this for a few days now... help!

I've already tried setting `$variables['title']` in `theme_preprocess_page_title`, but that doesn't seem to get called. I've also tried it in `preprocess_page`, but that does nothing.

To clarify - I am wanting to change the text that is by default displayed in `<h1 class="page-header">` from within my controller.

# Answer
You set the title in the route in the `_title` parameter:

```
mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title: 'Page title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

```

Or you can use a route callback:

```
mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title_callback: '\Drupal\mymodule\Controller\MyController::title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

```

And then put the title callback in the controller class, which receives the same parameters as the controller, so that you can determine a title on that information.
> 5 votes

---
Tags: 8
---


# Question
Title: How to show translated taxonomy terms in term listing in content listing style
I have question about translation of taxonomy terms in Drupal 8. Let's assume this configuration:

New created vocabulary, vocabulary language - not specified, terms language - not specified, show language selector, enable translation.

With this config, I should be able to translate new created taxonomy terms, if I select specific language while creating one. So I create taxonomy term in English language. Then I go and translate that term by clicking the "translate" tab in this term. I fill all values and save the form. Term is now translated to another language.

And now comes the difference - when I do the same approach with content, in content overview I see all nodes - original, and also translated. When I do this with taxonomy terms, in vocabulary listing I see only taxonomy term which was created first (so in my example the English one) - see the image.

How can I achieve the same behaviour as in content listing? I am expecting, that all terms will be listed here (as in content overview), or at least, when in specified language, terms with this language set should be shown (e.g. in English only links in english translations, if they exists). Taxonomy terms and nodes are all entities, so I would expect the same behaviour while translating them... Or is this a bug?

Thanks

# Answer
> 0 votes
Yes, it kind of is a bug.

The page is I think one of the the only two lists (the other is comments) that is hardcoded and *not* a view.

Views have configurable behavior to show show the entity in the best translation, or show the default translation.

You can replace this list with a view yourself, just create a view that lists terms on that path. Views doesn't support a few features of that UI however, specifically, that is the drag and drop hierarchy and weight handling. if you don't need that, fine. If you do, you might need to look for contrib modules that offer such features, I'm not sure if there are some for Drupal 8.

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


title: Serving an image programatically

text:
# Question
Title: Serving an image programatically
I want to serve an image programatically and execute custom code, something usal and simple in plain php.

```
<img src='test.php?image=1234.jpeg' />

```

Then you just serve the image in "test.php" and execute your custom code.

However I have not idea how to achieve this in Drupal.

The code should be in a module of course, but, how to I create a path equivalent the one above, that execute that custom code in my module?

Another solution could be to trigger a rule each time an image is download but that is too heavy. Even another could be something like URL alias to a content, and on display rewrite the output of that content? Is this possible?

# Answer
You should be using hook\_menu() to create a custom page from code. The `hook_menu()` allows to define a *URL* and *page callback* which will be called when user hit the url. Check the example below:

```
/**
  * Implements hook_menu().
  */
function [MODULE_NAME]_menu() {
  $items['MODULE_CALLBACK'] = array(
    'title' => 'My Custom URL',
    'page callback' => '_MODULE_NAME_page_callback',
    'access arguments' => array('access content'),
  );

  return $items;
}

function _MODULE_NAME_page_callback() {
  $image_name = (!empty($_GET['image']) ? $_GET['image'] : '');

  // Write code here.
  $data = $image_name;

  return $data;
}

```

The `_MODULE_NAME_page_callback()` callback will be called when user hit the URL as `sitename.com/MODULE_CALLBACK?image=imagename.jpg`.
> 0 votes

---
Tags: media, uri
---


# Question
Title: There aren't any releases for module "commerce_tax"
I am using drupal-vm and drupal console, and following the instructions for installing drupal commerce on an existing site (drupal-vm made me a drupal 8 site) here: http://docs.drupalcommerce.org/v2/install.html specifically, the command was: drupal module:install commerce\_product commerce\_checkout commerce\_cart commerce\_tax

I received the error in the Title, here's the whole output:

drupal module:install commerce\_product commerce\_checkout commerce\_cart commerce\_tax One or more modules "commerce\_tax" are not available, running download process to get those modules Getting releases for module "commerce\_tax"

\[ERROR\] There aren't any releases for module "commerce\_tax"

\[ERROR\] Invalid module name: commerce\_tax

Installing module(s) "commerce\_product, commerce\_checkout, commerce\_cart"

\[OK\] The following module(s) were installed successfully: "commerce\_product,
commerce\_checkout, commerce\_cart"

// cache:rebuild

Rebuilding cache(s), wait a moment please.

\[OK\] Done clearing cache(s).

# Answer
> 0 votes
You're getting the error because commerce\_tax is not included in Commerce 8.x-2.x branch, because of which Drupal Console is not able to find the module.

---
Tags: commerce
---


# Question
Title: How to get field value of form before submit?
I am trying to get the value of `group_name` field once data entered by user before submitting the form. Then only I can access the db, where the entered data is exist in db or not using query. If exists, it shows the data of that id (selected group name id) on the below fields dynamically. Here is my code:

```
   public function buildForm(array $form, FormStateInterface $form_state) {
     $form['group_name'] = array(
       '#type' => 'textfield',
       '#title' => $this->t('Name of Group (e.g. name of school, organization, business, etc.)'),
       '#validated' => TRUE,
    );

   /******get the entered group name here********/

    $form['gi_additions_changes'] = array(
       '#type' => 'textfield',
       '#title' => $this->t('If any additions or changes need to be made to your group info above, please let us know'),
       '#validated' => TRUE,
    );

    $form['add_group_name'] = array(
       '#type' => 'textfield',
       '#title' => $this->t('Name of Group (e.g. name of school, organization, business, etc.)'),
       '#validated' => TRUE,
       //'#default_value' => ($get_form_data) ? $get_form_data->group_name : ''
    );
  return $form;
 }

```

# Answer
> 1 votes
If I'm not wrong, you want to update the other fields based on `group_name` entered by user. To achieve this you can use AJAX API provided by Drupal 8 Core.

If you don't know how to use/work with AJAX API, you can have a look at Examples for Developers module which provides working examples for many of the functionality. To see AJAX API Example, you can install "**Form API Example**" Sub-Module from Examples Module. Feel free to go through Examples Module code for any help you need.

---
Tags: forms, 8, ajax
---


# Question
Title: What is the difference between the $config and the $settings variables in settings.php?
In the settings.php file of Drupal 8 installations, there are two different types of variables; $settings and $config. In Drupal 7 we used only $conf variable.

What's the difference between $config and $settigns variables in D8?

# Answer
Settings are for early-bootstrap (you can't store the database credentials in the database) and environment specific things, like the path to the public file system. Things that are not meant to be exported/deployed.

That means in almost all cases in modules, you want to use the configuration API.
> 9 votes

---
Tags: 8, configuration
---


# Question
Title: Absolute exact LIKE string condition in db_select
My query:

```
  $query = db_select('file_managed', 'f');
  $query->join('field_data_field_drupalcon', 'v', 'v.entity_id = f.fid');
  $output = $query
    ->fields('f', array('fid'))
    ->condition('v.bundle', 'video', '=')
    ->condition('v.field_drupalcon_value', '%'.db_like($keywords).'%')
    ->orderRandom()
    ->execute();

```

In the condition I would like to return an absolute exact match to the keyword, so for example if my field value is 'DrupalConDublin' I would not see that where my keyword value is just 'DrupalCon'.

# Answer
If you want to get exact matches, you might want to use another operator instead of "LIKE".

For a single value, you might use the following (with the '=' operator):

```
->condition('v.field_drupalcon_value', $keyword, '=')

```

For several keyword values, you might use the 'IN' operator:

```
->condition('v.field_drupalcon_value', $keywords, 'IN')

```

(in that case, `$keywords` must be an array of values).

You can find more information about conditional clauses in the DB API documentation: https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses
> 1 votes

---
Tags: database
---


# Question
Title: How to add another option to promote an article content to?
Take a look at my screenshot.

How can I make another option to promote my article contents to? Like promote my content as Affiliate Slideshow or to Slideshow?

# Answer
form\_alter will allow you to add another option

eg

```
hook_form_alter(&$form, &$form_state, $form_id){

     $form['my_field]['#options'][] = array('id' => 'value');

}

```

however, that in itself will not promote it, just allow you to set a value that can be picked up by a view or other means
> 0 votes

---
Tags: 7
---


# Question
Title: How to add a line break between each components in Email template in Webforms
I have the Webform 7.x-4.13 version module enabled.

I have a Webform node with more than 30 form components. In Email Settings, I have created a custom email template where I used the token: \[submission:values\].

Then I test the webform submitting a message. The problem is that \[submission:values\] print out the components values in a very plain way, no break line between the title and the value for each component. How can we add a line break between each components in an email.

I tried using "Send e-mail as HTML" option as well.

Can we do this using CSS/theme? If yes, Please tell me the procedure.

Thank you in advance.

# Answer
You can add every form component individuell with a syntax like \[submission:values:field\_key:label\] \[submission:values:field\_key:nolabel\] Please check the Tokens in your email settings or the following link https://www.drupal.org/node/2490648

You can also modify the webform-submission.tpl.php file and adjust it for your email.
> 1 votes

---
Tags: webforms, emails
---


# Question
Title: View filtered by a Date field's value being in "last month" shows July content on July 31
A View is filtered by a Date field's value. The Date field's month must be last month in order to match the filter.

On every day except July 31 it would return results from last month. It should have returned results matching June. We have tried "-1 month" but that didn't work either.

Why on July 31 does it jump ahead a month?

# Answer
Try to use 'last day of last month' or 'first day of last month'.
> 1 votes

# Answer
You can do this by adding "-1 months" relative value. you can get any month records just need to use + - no. of month to get previous or next months data.
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: How to get notifications in a new window when using the Mentions module?
I am using the Mentions module to be able to tag other users in a posts.

I also installed the Rules module and made a new rule which sends email and shows a message on site if the logged in user is mentioned in a blog.

But I need notifications like this to be displayed in a new window.

How can I achieve that?

# Answer
> 0 votes
You could also use the Message module for this. So that you expand the rule you already have (or clone it in a variation of it) to have the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).

Here is a blueprint of what you'd need:

1. Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes. I'd imagine that the message text you'll want to use is similar to the eMail or messages your existing rule already produces.
2. Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples, which are related to these variations of using Mentions:
3. Make sure to also add a Rules Action to pass any relevant tokens from Statuses, via Rules, as *Replacement tokens* that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
4. Use Views to display the created messages in the format you prefer.

---
Tags: 7, rules, notifications
---


# Question
Title: How to make Posts/Blogs mentioning a user appear in the user's profile?
I'm using Drupal 7 and I created a simple page where users are able to create challenges and tag people in their posts. For tagging I used the Mentions module and it works fine, I'm able to visit tagged person's profile.

Now I'm trying to add all the posts/blog entries that are associated with that user to the user's profile. So that every time the user is mentioned, that post would appear on the user's profile.

Is that possible to do? If yes, what would be a possible approach?

# Answer
> 0 votes
### Step 1

Use the Message module to create "Messages" each of those mentions, similar to what is detailed in the answer to "How to get notifications in a new window when using the Mentions module?".

### Step 2

Perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

1. Create a flag (using the the Flag module).
2. Create a view 'Messages by user'.
3. Use Rules to flag/unflag messages.
4. Trigger the Rules Component to mark messages (using the VBO module).
5. Create notifications about Unread Messages (using the "Menu Badges" module).

**Notes**:

* Consider Step 5 as a bonus: whenever a new message gets created, the user gets a shiny notification in the format of an iOS-like (red) badge with the number of unread mesages.
* No custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).

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


# Question
Title: add field to bundle through hook_entity_bundle_field_info
I am trying to add two fields to one of the node bundles.

I define the fields in this function:

```
function concertbeheer_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions){
    if($entity_type->id()=="node" && $bundle == "concert")
    {
        $concert_fields['laatste_uitvoering'] = \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
                ->setLabel('Laatste uitvoering')
                ->setRequired(TRUE)
                ->setDisplayConfigurable('view', TRUE)
                ->setDisplayConfigurable('form', FALSE)
                ->setDisplayOptions('view', array(
                    'label'=>'inline',
                    'type' => 'datetime_plain',
                    'weight' => '999',
                ));
        $concert_fields['eerste_uitvoering'] = \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
                ->setLabel('Eerste uitvoering')
                ->setRequired(TRUE)
                ->setDisplayConfigurable('view', TRUE)
                ->setDisplayConfigurable('form', FALSE)
                ->setDisplayOptions('view', array(
                    'label'=>'inline',
                    'type' => 'datetime_plain',
                    'weight' => '999',
                ));

        return $concert_fields;

    }

}

```

but the documentation on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_entity\_bundle\_field\_info/8.2.x says I also need to provide a fieldStorageDefinition through hook\_entity\_field\_storage\_info()

I can actually configure the visibility of the fields but when I save something to them it isn't saved in DB. Probably because of the lack of a FieldStorageDefinition

But I don't know how to get started on that and, as usual, there seems to be no documentation available on how to do it

# Answer
This code example would set up a basic storage definition:

```
function mymodule_entity_field_storage_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $definitions['my_bundle_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setName('my_bundle_field')
      ->setLabel(t('My new bundle field'))
      ->setTargetEntityTypeId($entity_type->id());
    return $definitions;
  }
}

```

You can look up examples in `field.storage.*.yml` files from a config export.

If you don't find the right examples there, you can configure a field in UI and then export the storage of this field to get a blueprint for the storage definition you need in this hook.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Is it possible to insert blocks into content using the paragraphs module?
I have a node (basic page type) with a lot of text (several paragraphs `<p>` of text).

Within two `<p>` tags I have to insert a block (generated with views oder other modules like Nodeblock).

How can I insert the existing block directly between the text of my node? Is it possible to do this with the "Paragraphs" module?

If not, why not?

If not, which other modules allow me inserting blocks directly into the node text?

# Answer
> 2 votes
you can install the Viewfield module, create a view, then create a Paragraph with a field of type Viewfield which allows you to insert the view as content of the field.

---
Tags: 7, nodes, blocks
---


# Question
Title: How do I count multifield for body of block?
So I have a custom template for the custom block and I can print each one using the following code.

```
Body 1: {{content.body.0}}
Body 2: {{content.body.1}}

```

I need to know how many there are. I tried a whole bunch of variations of `{{ content.body | length }}` or `{{ content.body.getvalue | length }}` but nothing is working.

My goal is to add responsive grid support depending on how many bodies there are. How can I achieve this?

# Answer
Use this in your block.html.twig template:

```
 {{ content.body['#items'].getvalue|length }}

```

Although to access the individual items, it may be better to create a field template such as field--node--body.html.twig

then you can do

```
{{ items|length }}

```

in that template.
> 2 votes

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


title: How do I update HTML content

text:
# Question
Title: How do I update HTML content
We have a website that is linked to a drupal database. I need to update some HTML text and could not find the file on our server but did find the content in two tables in the drupal DB: dbo.field\_data\_body and dbo.filed\_revision.

I made the change in the db but this has not been relayed to the site.

Please advise

Thank you, Kai

# Answer
> 0 votes
I do not have admin access to drupal API but have access to the DB and IIS. I assumed that the content from these tables would export into an editable markup file but this does not appear to be the case. Can i do this without the drupal API?

Kai

---
Tags: updating
---


title: How to get path of image from file id

text:
# Question
Title: How to get path of image from file id
I have this output from my twig template dump:

```
/var/www/html/vendor/twig/twig/lib/Twig/Extension/Debug.php:56:
array (size=7)
  'id' => string 'views_block:about-block_1' (length=25)
  'label' => string '' (length=0)
  'provider' => string 'views' (length=5)
  'label_display' => string '0' (length=1)
  'views_label' => string '' (length=0)
  'items_per_page' => string '3' (length=1)
  'background' =>
    array (size=1)
      0 => string '136' (length=3)

```

So my file id (fid) is 136. I'd like to know a way to get this file's url **without** having to use a preprocess function.

Can this be done? Would I have to do a custom twig function to achieve this? If so where would I add the code to extend twig?

ex:

```
$twig = new Twig_Environment($loader);
$function = new Twig_SimpleFunction('function_name', function () {
    // ...
});
$twig->addFunction($function);

```

# Answer
So I decided to create a module to extend twig and get the file url from its fid.

get\_url\_from\_fid git project

Source of src/GetUrlFromFid.php

```
<?php
namespace Drupal\get_url_from_fid;

class GetUrlFromFid extends \Twig_Extension{

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName(){
    return 'get_url_from_fid';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions(){
    return array(
      new \Twig_SimpleFunction('get_url_from_fid',
        array($this, 'get_url_from_fid'),
        array('is_safe' => array('html'))
      )
    );
  }

  public function get_url_from_fid($fid){
    $file = \Drupal\file\Entity\File::load($fid);
    if(!is_null($file)){
      $uri = $file->getFileUri();
      return file_create_url($uri);
    }else{
      return false;
    }
  }
}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How can I rebuild node / view cache based on the contents of an entityqueue
I have

Content types:

* front\_banner
* news

Entity Queues:

* front\_banner -\> only ever contains one front\_banner node
* news -\> contains multiple news nodes

Views:

* front\_banner -\> displays rendered nodes (default)
* news -\> displays rendered nodes (teaser)

The front banner content type has a field in it that determines whether the text colour should be light or dark when display (sets a class in the twig template, works fine). The news content type also makes use of the front\_banner's overlay style field like so:

```
function mymodule_preprocess_node(array &$vars) {
  if ($vars['node']->bundle() == 'news'){

    // Set the overlay class (dark/light).
    $entity_subqueue = \Drupal::entityManager()->getStorage('entity_subqueue')->load('front_banner');
    $items = $entity_subqueue->get('items')->getValue();
    $front_node = node_load($items[0]['target_id']);
    $vars['overlay_class'] = $front_node->get('field_overlay_style')->getString();
  }
}

```

All of this works perfectly well, my problem occurs when I alter the front\_banner node or entityqueue: the cache is obviously not set to refresh for news items when that occurs.

**1. Which render cache do I need to rebuild?**

Is it the view cache? or the node's render cache? or both?

**2. How can I do it?**

I have tried creating my own cache tag and flushing it like so:

```
function mymodule_entity_presave(EntityInterface $entity) {
  $tags = ['entity_type:' . $entity->getEntityTypeId() . '.' . $entity->bundle()];
  Cache::invalidateTags($tags);
}

function mymodule_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($build['#node']->bundle() == 'news'){
    //dpm($build);
    $tags=['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
    $build['#node']->addCacheTags($tags);
  }
}

```

(`entity_subqueue:front_banner` tag is provided by the entityqueue module)

I cannot get the news node page itself to change the overlay style, nor can I get the view that displays news nodes to change the overlay style when the front\_banner node is saved.

---

**\[Edit 1:\]** I looked into Views Custom Cache Tags - this does allow me to state which tags I want to affect the views cache - I tried putting the two relevant tags in my view to no effect. Perhaps this means it's the node cache that is giving me grief?

# Answer
Every view that lists nodes is tagged with node\_list and will be invalidated when a node is added, changed or deleted, so you don't need to worry about adding your nodes to the view.

But you do need to add the entity\_subqueue tag to your view's cache tags, and you need to add the entity\_subqueue tag and banner content type to your news content type's build array. I haven't tested the way you're adding it, but I know you can add cache tags to a node in hook\_entity\_view:

```
  function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

      if ($entity->bundle() == 'news') {

        $tags = ['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
        $build['#cache']['tags'] = array_merge($build['#cache']['tags'], $tags);

      }
    }

```

I know this is similar to what you were doing, but need to add it to the build array, not the node object.

Then you need to add the entity queue to the build array of your view

```
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == 'news' || $view->id() == 'front_banner') {
    $view->element['#cache']['tags'][] = 'entity_subqueue:front_banner';
  }
}

```
> 4 votes

---
Tags: 8, caching
---


# Question
Title: How can I add a extra feature to repeating date field?
I have a content type named Tasks and it has a date field.

I use this date field for weekly tasks and I want to add a simple on/off checkbox for these dates.

For example I add a weekly task for 11 November 2016 and I pick repeting option to every week.

I want this;

# Answer
> 0 votes
Field Collection is exactly what you looking for. It allow you to create a group of fields, and then add this group of field as a field on your content-type (and made it repeatable as your date field).

In your case, you create a field collection constituted by a checkbox field, and a date field. Then add this field collection to your Tasks content-type and made it repeatable (Unlimited).

---
Tags: 7, datetime, entities
---


# Question
Title: Have users answer a question before viewing content
I did some research but cant seem to wrap my head around having the ability to do this.

I have a couple content types that are currently open to everyone but I would like to collect some information from anonymous users before showing them the content.

I am thinking in some way to utilize webforms in a block and have the questions show up there, what im not sure is how to hide or blur out the content that they are trying to view until they answer the form, as well as how to keep that content open until their next visit.

I am sure you have all seen websites/blogs that do this, to make you register for the site.

Any guidance to how to accomplish this would be very appreciated.

# Answer
> 3 votes
I'm not aware of a module that does this out of the box. But depending on your details there are a few ways to try to solve this problem.

One solution would be to create your form using Webform or Entity form (assuming your on Drupal 7 a contact form could be used in Drupal 8), place that form in a hidden block on the pages in question. On page load use JavaScript to put the form into a lightbox and set some kind of CSS effect over the rest of the page. When the user completes the form set a cookie so that on the next page load they aren't bothered by the popup. This is a common solution used by News papers trying to enable paywalls but it often means users can bypass the effect by disabling JS.

---
Tags: 7, views, webforms
---


# Question
Title: Multiple URL for one Drupal 8 website configuration
I want create one Drupal 8 website (one database) with changing contents depending of the URL the user used, I mean:

* If the user goes to the main URL `http://foo.com`, the main page of the website is loaded and contains some content generated for the `http://foo.com` URL
* If the user goes to the main URL `http://faa.com`, the main page of the website is loaded and contains some content generated for the `http://faa.com` URL

I can manage that with Apache settings. But how can I configure Drupal? If a user uses the URL `http://foo.com` and then, he goes to the subpage `/test`, the URL must become `http://foo.com/test`.
But, if a user goes to the site with the URL `http://faa.com` and then, he goes to the subpage `/test`, I want the base URL still `http://faa.com` (`http://faa.com/test`).

# Answer
> 2 votes
I've handled this situation very easily by setting two different Apache VirtualHost with the same DocumentRoot.

The thing you have to be very careful is the page caching of Drupal. I recommend you to read the Cache Context document on Drupal 8 who is very helpful for your situation. By passing the "url" cache context on your different render arrays, you will prevent the content of a URL to be displayed on the other.

Drupal routing system doesn't take the domain name. So there'll be no problem and a user who go on a subpage from a domain name will stay on this domain name.

# Answer
> 2 votes
This sounds like a perfect job for the Domain Access module.

---
Tags: 8, uri
---


# Question
Title: Drupal 8 update.php/selection - access denied
I wanted to update d8 from 8.0.1 to 8.0.2, but i couldn't run the update.php due to the error "Access Denied". Am logged in as user1 which should have all required privileges.Following the drupal 8 update guide I deleted core and vendor folders with all the files in the drupal root from the the 8.0.1 install, and replaced the same files and folders from the newly downloaded 8.0.2 version.

What could be the solution to this problem?

My Environment: OSX El Captain, nginx 1.8 using the latest config from nginx/drupal, PHP 7.0.2,

See window capture below:

Many Thanks

# Answer
After several frustrating days I figured the problem was from my configuration. The conf file has "fastcgi\_param SCRIPT\_FILENAME $request\_filename;" instead of "fastcgi\_param SCRIPT\_FILENAME $document\_root$fastcgi\_script\_name;"

Making this correction solved the problem.

Am grateful for all the support.
> 1 votes

# Answer
The most common cause of this is the apache user doesn't have permission to see the new Drupal source files. It most likely has nothing to do with the logged in Drupal user.

If you have shell access to the server, you can update the permissions with the following command (run from the Drupal directory):

```
chmod -R a+r *

```

This recursively adds read permission for all users without affecting other permissions.

If you don't have shell access, many FTP clients allow you to update the permissions on a group of files.

Hope this helps.
> 0 votes

# Answer
Another solution is try to open error log in /var/log/nginx/

I've discover that this is cause from SELinux. (If you're using CentOS)

Solution: nginx - Unable to open primary script

PS: For anyone who encounter this issue. :)
> 0 votes

---
Tags: 8
---


title: Cron error: file could not be created

text:
# Question
Title: Cron error: file could not be created
Cron seems to complete, but I get a message stating that a file could not be created.

Do you have any idea about what is causing this?

# Answer
You need to give the 777 directory permission to your temp folder. Like.... sudo chmod 777 -R /var/www/html/yoursite/sites/default/files/temp/

Please check images for more understanding. enter image description here

and command for give 777 permission to that directory like...
> 1 votes

# Answer
Sounds like a file permissions issue. Check this: https://drupal.org/node/244924
> 0 votes

# Answer
You can just change the temporary directory link found at sitename/admin/config/media/file-system to /tmp and save.
> 0 votes

---
Tags: 6, cron
---


# Question
Title: How to create bootstrap grid that is responsive in all devices
I created a bootstrap grid views block with 4 columns. When I visit the page in mobile device, I see one column grid. When I visit the page in tablet device, I also see one column grid plus blank to the right.

How can I make it more responsive? I am also confused how it should behave in my case.

# Answer
> 0 votes
What classes exactly did you use ?

The breakpoints used for the grid could be different depending of what device size you aim for your columns. The smallest size handled by the BS grid is for devices with **\< 768px width** by adding class `col-xs-*` (in Boostrap 3, for Bootstrap 4 it's up to 576px). Typically this is for some tablets & almost all smartphones in portrait mode.

If you only want set classes for superior size, it will automatically be stacked on extra small devices. For example, if you used `col-md-3` for each column, when the device width will worth \< 768px, all the columns will be stacked each under the others (which is often wanted on small width regarding layouts). But you can add `col-xs-6` too on each to have 50/50 columns on small devices.

See more Bootstrap documentation about the Bootstrap grid system : http://getbootstrap.com/css/#grid-options

---
Tags: theming
---


title: Override a template for only one route

text:
# Question
Title: Override a template for only one route
I want override the region default template. I did that with a hook theme from my module. I want override the region custom template but only for the front page. How can I do that?

# Answer
> 3 votes
You need to implement hook\_theme\_suggestions\_HOOK\_alter() in your theme. For *siderbar\_first* region it would look like follows:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_region_alter(&$suggestions, $vars) {
  if ($vars['elements']['#region'] == 'sidebar_first' && Drupal::service('path.matcher')->isFrontPage()) {
    $suggestions[] = 'region__sidebar_first__front';
  }
}

```

Now *region--sidebar-first--front.html.twig* can be used for theming sidebar on the front page.

---
Tags: theming, 8
---


# Question
Title: How do I change page callback for a particular menu?
There is already a menu defined in core module. I need to alter the page callback of this menu in another module. Similar to using `hook_menu_alter()` in Drupal 7, but since there is no `hook_menu_alter()` in Drupal 8, how do I define another page callback?

# Answer
> 3 votes
In Drupal 8 You don't have hook\_menu and the are changed to "Routers" now.

Drupal 8 has a new menu system, there is no hook\_menu and no hook\_menu\_alter anymore.

If you want to alter an existing route, it is a little bit more complicated in comparison to Drupal 7.

In your module you have to create a class file at YOURMODULE/src/Routing/CLASSNAME.php that extends RouteSubscriberBase:

```
/**
 * @file
 * Contains \Drupal\YOURMODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOURMODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get the route you want to alter
    $route = $collection->get('system.admin_content');

    // alter the route...
  }
}

```

You can take the RouteSubsciber class of the node module as an example.

To let your RouteSubscriber be recognized you also have to create a YOURMODULE.services.yml file in the root of your modules directory:

```
services:
  node.route_subscriber:
    class: Drupal\YOURMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

To get a better insight to the new menu system I would recommend the following articles:

D7 to D8 upgrade tutorial: Convert hook\_menu() and hook\_menu\_alter() to Drupal 8 APIs What Happened to Hook\_Menu in Drupal 8? Edit: the menu system has a different structure now, which has nothing to do with D7's menu system, so there is no such thing as a menu type anymore.

# Answer
> 0 votes
Thanks to the above answers for pointing me in the right direction, but I think the key part is missing - How to change the page callback! Though D8 might not use the phrase `page callback` we still have page callbacks - the `controller::method` which responds to a request.

**Step 1: Create a route subscriber**

Follow the official Drupal 8 documentation on and create a Drupal 8 Route Subscriber \- Paritoshik Paul's answer might help you in this step. Make sure you implement the `alterRoutes()` method and that it is working (you might have to clear cache).

At the end of this step, if you do a `die();` in the `alterRoutes()` method, the code execution should stop at the die when rebuilding cache.

**Step 2: Change the page callback**

Once the `RouteSubscriber::alterRoutes()` is confirmed to be working, you can change the page callback to your custom controller::method like this:

```
protected function alterRoutes(RouteCollection $collection) {

  // Change the page callback for Taxonomy Term pages.
  $route = $collection->get('entity.taxonomy_term.canonical');
  $route->setDefault('_controller', '\\Drupal\\YOURMODULE\\Controller\\YourController::yourMethod');

}

```

In the above example, I change the callback for a taxonomy term page. Of course, we will have to ensure that `YourController::yourMethod` actually exist. Refer official docs for how to create a basic controller.

Rebuild your cache and your page callback is changed!

---
Tags: 8, routes
---


title: How can I add color to drush output?

text:
# Question
Title: How can I add color to drush output?
I'm writing a drush command, and outputting the results in table format. Everything works fine, the command runs, the output is displayed where it should be. However, there is one column where I am putting "Ok", "Warning", "Error" and I would like to be able to add color to that (the way drush does for its own commands). Yet I have looked everywhere without success to find instructions about how to do it, and would welcome some pointers.

# Answer
> 8 votes
In Drush 8 you may access Symfony Console output object directly.

```
<?php

/**
 * @file
 * Contains example drush command.
 */

use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Implements hook_drush_command().
 */
function MODULENAME_drush_command() {
  $items['example'] = [
    'description' => 'Command description.',
  ];
  return $items;
}

/**
 * Callback function for example command.
 *
 * @see http://symfony.com/doc/current/console/coloring.html#using-color-styles
 */
function drush_MODULENAME_example() {
  $output = new ConsoleOutput();
  $output->writeln('<info>Green text</info>');
  $output->writeln('<comment>Yellow text</comment>');
  $output->writeln('<question>Black text on a cyan background</question>');
  $output->writeln('<error>White text on a red background</error>');
}

```

# Answer
> 2 votes
We should discuss this in the Drush issue queue. In Drush 8 and earlier, the code to support colored output exists in the logger only, and is not readily usable for other purposes.

In Drush 9, however, we are using the Symfony Console Output classes, so it should be possible to allow you to use the techniques in the Symfony Style Guide, or just wrap you text in `<info>` et. al.

Some minor enhancement may be necessary.

**Update**

I added an example to Drush 9 that demonstrates how to use a cell data render function to add color to table output when `--format=table` is used without having the same transformation applied when the format is json, yaml or similar outputs. Note that the same technique can be used in instances where you wish to reduce an array to a string (e.g. via `implode`) when it is output in a table, and leave it as an array in yaml/json formats.

If you just want to insert color into older versions of Drush, and you don't mind it also appearing in yaml / json output, you can just use the terminal shell escapes directly:

```
$red = "\033[31;40m\033[1m[%s]\033[0m";
$yellow = "\033[1;33;40m\033[1m[%s]\033[0m";
$green = "\033[1;32;40m\033[1m[%s]\033[0m";

```

This isn't a great solution, though. You could use the Symfony table helper directly, as the other answer suggested, but then you wouldn't be able to convert your command output to other formats at all.

Perhaps we could backport the Console output handling to Drush 8; however, I'm not sure how much of a priority that will be.

---
Tags: drush
---


title: Categories and brands

text:
# Question
Title: Categories and brands
I have a product catalog that I would like to categorise into different categories (and subcategories). I would also like to have a grouping of the products by brands (which of course are orthogonal to the categories).

The ideal thing is that a customer can search for products belonging to a category, and/or to some brand.

Until now I have only managed to create the main categories. I created also subcategories, but they do not get displayed in the products page, i.e. having something like

* CatA

+ Sub1
    + Sub2
* CatB

If I try to show all the products in `CatA` only those belonging directly to it (and not to `Sub1 or 2`) get displayed.

Of course I do not have any idea on how to implements the brands.

EDIT:

I've tried some options in the mean time. Regarding the brands, I understood it is a completely different taxonomy. I created it, and associated it with the products and I added a new search facet in the All Products page. Probably I'll need some more advanced stuff in the future, but for now it is ok.

Instead, I'm still struggling with the sub-categories problem. I watched the following discussion & video: https://drupalcommerce.org/discussions/9017/product-catalog-terms-and-nodes They do something similar to what I need, but I need to put some modifications. I do not need multiple pages to navigate the categories. I simply want that if a user navigates a page like `products/CatA` all the products in `Sub1` and `Sub2` are shown.

# Answer
> 0 votes
Commerce Kickstart is a 'canned' solution, so you're limited by what's been 'hard-coded' already. This is fine, you just need to make some leaps of faith to use their product for your purposes.

You can't use the hierarchical structure of 'indented' sub categories of a Drupal taxonomy as an expected subcategory in Commerce Kickstart. It just doesn't understand it (yet). Unfortunately, you can only use a single level of category for each taxonomy category term. In Kickstart 2 - that's called the 'Collection' taxonomy. So don't add subcategories there and expect them to be shown. In some ways, this saves you some headaches.

You need to make a separate (again, single level of depth) taxonomy term for subcategory. You also need to set it to be a taxonomy of product classification (the checkbox thing in the Edit of the taxonomy).

With both separate, single level of depth, taxonomies, you then need to add these term reference selection boxes to your 'Product Variation' (and NOT Content Type).

You then need to put your brand, set up the same way as the other two, mentioned above, in your 'Content Type' (NOT product variation).

You then need to set up all of your Display Views, in both Content Type (CT) and Product Variations (PV). Look at the 'Tops' CT/PV set up to match that setup for guidance.

In this way, the 'All Products' view will work to allow you to filter by all terms of category, subcategory, and brand... or what ever other classification you can think up.

---
Tags: commerce, taxonomy-terms
---