# Question
Title: Drush not recognized and internal or external command
When I update Drush to Drush 9.1.0, the following error now appears:

```
'drush' is not recognized as an internal or external command, operable program or batch file.

```

This issue has occurred on three different machines: two running Windows Server 2016 and one running Windows 10. I've read that it could be due to mismatched global and site Drush versions, but both versions are at 9.1.0. When I downgrade to Drush 8.x.x, it functions as normal. Both the global and site-specific Drush installs were installed with Composer. Are there any fixes for this error?

# Answer
Did you install Drush Launcher? This seems like a PATH issue -- your command lines doesn't know where to find Drush 9.

> To be able to call drush from anywhere, install the Drush Launcher. That is a small program which listens on your $PATH and hands control to a site-local Drush that is in the /vendor directory of your Composer project. If you skip this step, run Drush from Drupal root via ../vendor/bin/drush. In that case Drush's bash integration and custom prompt won't work.

from: http://docs.drush.org/en/master/install/
> 5 votes

---
Tags: drush
---


# Question
Title: Javascript translation broken - fixed after cache clear
I just encountered a problem with the javascript translation. I have a javascript file where I generate small UI elements using jQuery, and I wrap the label in the Drupal.t function. The site is multilingual NL/FR So e.g.:

```
$('input.button').val(Drupal.t('Dwork'));

```

For some reason the translation failed; I only got out what I put in: Dutch in this case. After clearing the Drupal cache everything seems to be back to normal. I assume somehow the generation of the french translation js file failed, but I'm unsure how this could have happened.

Anybody know what could cause this, or how to pro-actively refresh the cache?

# Answer
> 1 votes
You can refresh the cache with drush: drush cc css-js to clear only Javascript (the admin module allows you to do this from config), or you can just go to performance and clear all the cache.

It does seems like clearing cache is important in these cases: https://www.drupal.org/docs/7/api/localization-api/translating-strings-in-javascript

---
Tags: 8, i18n-l10n, caching
---


# Question
Title: How to recalculate uploaded files' sizes in KB and update the values in the database?
I use a shell command to look for all uploaded `JPEG` files above 500 K.B. (originals) and do JPEG compression on them. They get smaller in size, but Drupal still shows the originally uploaded file size. How to force a recalculation and update the database accordingly after JPEG optimization?

# Answer
> 2 votes
In Drupal 7 managed files have their `filesize` property updated upon saving in the `file_save()` function. So you can just load/save each resized files to have it updated in the DB accordingly.

```
//@TODO: Get list of $fids corresponding to resized-files
foreach ($fids as $fid) {
  $file = file_load($fid);
  // $file->filesize reflects old size
  file_save($file);
  // $file->filesize now reflects new size
}

```

---
Tags: 7, database, files
---


# Question
Title: How to remove link to personal contact form from tabs block?
I created a link to personal contact form in page content, and I want to remove it from tabs. How to do that without breaking functionality?

# Answer
> 2 votes
I didn't test the following example code though, but you will be able to remove tabs using hook\_menu\_local\_tasks\_alter() in a custom module (replace `mymodule` by the name of your custom module):

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  // Whether the personal contact form tab is present. You
  // can fine-tune your conditions here. The tab route was
  // taken from ./core/modules/contact/contact.links.task.yml.
  if (isset($data['tabs'][0]['entity.user.contact_form']) {
    unset($data['tabs'][0]['entity.user.contact_form']);
  }
}

```

As mentioned before, I did not really try the above code. You might have to check the contents of the `$data` array to find the right plugin id and correct position of the tab definition when visiting a user's page.

Also note, that the tabs information will be cached. So you will have to rebuild your caches for the changes to take effect and the above hook to being triggered.

The functionality will be kept, as the route behind the tab is still active when you alter the local tasks array only.

---
Tags: 8, emails
---


# Question
Title: Add views exposed filter programmatically
I used the below code in hook\_views\_pre\_view to add two exposed filter to a view, the first filter which provides available brand works perfectly but the second filter is not added at all, no error is logged though, any help on that?

```
  $available_brands = dpspec_get_available_brand_name($mid);

  $filter_options = array(
    'value' => $available_brands,
    'exposed' => TRUE,
    'reduce_duplicates' => TRUE,
    'type' => 'select',
    'required' => FALSE,
    'expose' => array(
      'operator_id' => 'field_brand_op',
      'label' => t('Brand'),
      'operator' => 'field_brand_op',
      'identifier' => 'sp_brand',
      'reduce' => TRUE,
      'vocabulary' => 'tags',
      'multiple' => TRUE,
    ),
  );
  $view->add_item($view->current_display, 'filter', 'field_data_field_brand', 'field_brand_tid', $filter_options);

  $available_colors = dpspec_get_available_color_names($mid);
  $options = array(
    'value' => $available_colors,
    'exposed' => TRUE,
    'reduce_duplicates' => TRUE,
    'type' => 'select',
    'required' => FALSE,
    'expose' => array(
      'operator_id' => 'field_color_op',
      'label' => t('color'),
      'operator' => 'field_color_op',
      'identifier' => 'sp_color',
      'reduce' => TRUE,
      'vocabulary' => 'tags',
      'multiple' => TRUE,
    ),
  );

  $view->add_item($view->current_display, 'filter', 'field_data_field_color', 'field_color_tid', $options);

```

# Answer
> 0 votes
OK the code is working fine, the only problem was that the color field was added to product, while views was set based on node, so when I added a relation to product, it started working.

---
Tags: 7, views
---


# Question
Title: How do I change jquery_update version for a custom theme?
There are two options in jquery\_update module's configuration: Jquery to be used in frontend theme, and Jquery to be used in admin themes. I set another theme to be used by a specific role (say, manager). How do I change jquery\_update version of that theme that is used by manager role. Is it possible to do this with template.php, if yes, how so?

I already followed a patch here, but I am not sure if I should apply that old patch.

# Answer
> 1 votes
No need for a patch, jquery\_update 7.x-3.0-alpha5 works great and it already includes functionality to specify jquery version per theme (as per this issue) on configuration page `admin/config/development/jquery_update`

For specifying a theme per role you can try any of the following modules role\_theme\_switcher Themes By Role (TBR)

---
Tags: 7, javascript
---


# Question
Title: How to get custom entity data in custom page
i have created Event entity, and I have custom page.

I want to load ALL Entity rows and then use it in my template.

This is the way everyone is prsenting, but i don't know how can i get NID value

`$events = \Drupal::entityTypeManager()->getStorage('event')->load($nid);`

Using Symfony i could do this like:

```
$events = $this->getDoctrine()->getRepository(Event::class)->findAll();

```

# Answer
> 3 votes
This is the solution

```
$storage = Drupal::entityTypeManager()->getStorage('event');

$nids = Drupal::entityQuery('event')->execute();
//Load all nids
$events = $storage->loadMultiple($nids);
//You can also use
$events = $storage->loadMultiple();

```

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


title: Wrong timezone in Views output

text:
# Question
Title: Wrong timezone in Views output
I'm using Services Views to create a JSON output of my Drupal site's nodes. These nodes has a start and stop date and time regarding an event. On the site, viewing the node, the time is correct, but in my Services view it is shown in UTC instead of my Drupal site's timezone (UTC +2).

I've seen other questions regarding this issue with a DB and site timezone being different, with all the issues it creates - especially in cases just like this. Eg.: http://dropbucket.org/node/559 and Drupal timezone and database and Printing the correct date value in a view

In this case, however, I do have a problem converting the value into the correct timezone and therefore the correct time.

I have the site set to UTC +2 (Sweden/Stockholm), users arn't allowed to have any other timezones, also the date field is set to save the date in the site's timezone, not the DB.

My view wont let me rewrite my output so I can't convert the date inside the view - nor would I like to run PHP in a view anyway.

Is there another way of converting, or at least changing the setting for the date save, so that this won't be a problem?

Cheers, Daniel

# Answer
I'm not exactly sure why you are having this trouble... Though in a quick attempt to test (in Drupal 7), it does seem a little screwy.

However, since you don't seem worried about other timezones and no need to convert timezones, it would seem easiest to set the "Time zone handling" on the field to "no time zone conversion" Then the views should pick up whatever date and time is there to begin with.
> 0 votes

---
Tags: views, datetime, services
---


title: What is the [random:hash:?] token?

text:
# Question
Title: What is the [random:hash:?] token?
I created a marketplace with two fields: a "Store Reference" field that the store owner fills, a "SKU" field I want to be unique and generated automatically.

On Drupal Commerce I want the SKU of my products to be generated automatically and made unique.

I want a sequence of numbers and random letters, for example a single SKU of 12 characters (number and letter).

There is a hash token in "Explore Available Tokens" and "Random". What is it used for?
Can it meet my needs?
Can it generate a unique code that will never be reused?

There are several store owners who can create products at the same time; the same SKU must not be generated.

>

# Answer
It's a token for generating a random string. When you look into the implementation, you can see it's the result of hashing 55 random bytes with your selected hashing algorithm (the `?` part of `random:hash:?`).

Will it meet your uniqueness needs? ***Yes.***

Since we're talking pseudo-randomness here and the fact that hashing algorithms can produce collisions, there's a *possibility* of the same string being generated but it's very unlikely (unless you have a massive number of SKUs being generated).

In the unlikely event that Commerce & the AutoSKU don't have the logic to prevent SKU collision (which should be there as its a unique attribute), you can always add more patterns in the token (e.g. UID) to lessen the collision possibility to effectively zero, for the number of SKUs needed by your store.
> 3 votes

---
Tags: 8, tokens
---


# Question
Title: Best way to approach users voting on and identifying content?
I am working on a Drupal 7 website, Double Enders, where users can view and add individual boats, categorizing them by design.

I already have several boats that have not been identified by their design. I am planning on using views to allow users to view the boats that do not have designs associated with them. I would like to also give users a drop-down menu with all the designs (which is a view that I use elsewhere in the site) and allow them to use this drop-down menu to identify/vote on what type of design the boat is, tallying their votes.

Looking through the voting modules, it does not appear that any of them allow one to use a view as the options a user can select between. Instead, they all seem to provide some variation on ratings or yes/no.

I am considering using the Voting API module to build the functionality myself. However, before I go down that road, I was wondering if I had missed a module that I could use or another way to get the functionality I desire. Does anyone have any suggestions, or am I right to proceed using the Voting API module?

# Answer
Have a look at Flag module. It supports adding fields to a flag, so a user could first flag a boat ("I can identify that design!") and then select one of the known designs on the flagging form.

Whatever you end up using, I'd like to read what you choose, and why!
> 1 votes

---
Tags: 7
---


# Question
Title: Drush 8 not working correctly on (LAMP) Ubuntu 16.04
I am running LAMP on Ubuntu 16.04. I have a drupal 7 installation and I have installed drush 8.1.3 via Composer version 1.5.2. I believe there is bug in php7.2 causing the error as discussed on Github, however even after I applied the recommended fix which is to update the pear/console\_table to the latest version instructed here, the problem still remains. I also followed the instructions on Super User to be absolutely sure that I have the most up to date version of pear installed as well (did not install PHPunit). And, FYI in accordance with the drush installation documentation found here, I also made the proper changes to my `.bashrc` file as well (below).

Whenever I run `drush status` I receive the following error:

\[**UPDATE:** This part of problem **SOLVED** by @GiorgosK answer below. Other problems persist due to Drush not find mysql socket\]

```
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
PHP executable         :  /usr/bin/php
PHP configuration      :  /etc/php/7.2/cli/php.ini
PHP OS                 :  Linux
Drush script           :  /home/webdevusr/vendor/drush/drush/drush.php
Drush version          :  8.1.13
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :

```

If I execute `drush sql-connect`

```
Unable to load class Drush\Sql\Sql                                  [error]
Drush\Sql\SqlException: Unable to find a matching SQL Class. Drush   [error]
cannot find your database connection details. in
/home/webdevusr/vendor/drush/drush/commands/sql/sql.drush.inc:541
Stack trace:
#0
/home/webdevusr/vendor/drush/drush/commands/sql/sql.drush.inc(221):
drush_sql_get_class()
#1 /home/webdevusr/vendor/drush/drush/includes/command.inc(422):
drush_sql_connect()
#2 /home/webdevusr/vendor/drush/drush/includes/command.inc(231):
_drush_invoke_hooks(Array, Array)
#3 /home/webdevusr/vendor/drush/drush/includes/command.inc(199):
drush_command()
#4
/home/webdevusr/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67):
drush_dispatch(Array)
#5 /home/webdevusr/vendor/drush/drush/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#6 /home/webdevusr/vendor/drush/drush/drush.php(12): drush_main()
#7 {main}

```

The contents of my `~/.bashrc` file, are as follows:

```
export PATH="$HOME/.composer/vendor/bin:$PATH"

export PATH=/bin:/usr/local/bin:/usr/local/mysql/bin:$PATH

# Include Drush bash customizations.
if [ -f "/home/webdevusr/.drush/drush.bashrc" ] ; then
source /home/webdevusr/.drush/drush.bashrc
fi

# Include Drush completion.

if [ -f "/home/webdevusr/.drush/drush.complete.sh" ] ; then
source /home/webdevusr/.drush/drush.complete.sh
fi

# Include Drush prompt customizations.

if [ -f "/home/webdevusr/.drush/drush.prompt.sh" ] ; then
source /home/webdevusr/.drush/drush.prompt.sh
fi

```

The result of `drush cc all` executed from within my drupal installation folder is:

```
No Drupal site found, only 'drush' cache was cleared.

```

Anyone know how to get drush to working for my local (LAMP) Drupal 7 installations?

thx

# Answer
> 1 votes
Recently run into a similar problem on my local environment after an ubuntu update and php 7.2 became my default version.

## make 7.1 or lower your default php version

I believe you should make php 7.1 the default or perhaps even a lower php version for Drupal 7 installation as not all modules are ready for php 7.2 (even some of Drupal 8 modules are not ready for php 7.2)

type this in your shell

```
$ sudo update-alternatives --config php

```

and this is what you will get

```
There are 4 choices for the alternative php (providing /usr/bin/php).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php7.2   72        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.0   70        manual mode
  3            /usr/bin/php7.1   71        manual mode
  4            /usr/bin/php7.2   72        manual mode
Press <enter> to keep the current choice[*], or type selection number:

```

Choose the appropriate version

## might need to update drush to a later version.

8.1.16 is out at this moment and might already have solved the problem you describe. Update using composer

## alternatively you can try to setup drush without composer

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

# make it executable
chmod +x drush.phar;

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

# go to that directory
cd ~

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

# edit the following file
nano .bashrc
# or
# nano .bash_profile

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

# use the alias you just setup
source ~/.bashrc;

```

## might want to specify site directory when you invoke drush

as you drush might have a messed up setup/aliases

```
drush status -r /path/to/site/rootdir

```

## doublecheck your settings.php

Does it include the correct database connections? Does the site actually run with those connection settings ?

## Look in your logs for any problems

in my system I can see apache errors like this

```
tail -50 /var/log/apache2/error.log

```

You might discover that some apache packages are missing or disabled just an example lets say mod\_rewrite is not enabled

```
sudo a2enmod rewrite
sudo service apache2 restart

```

or you might find that some package is missing like mysql-client

```
sudo apt-get install mysql-client

```

# Answer
> 0 votes
I recently ran into the same issue, and for us it turned out that Drush 8 relies on several packages being installed on the server. In our case, we needed mysql-client to be installed.

---
Tags: database, drush
---


# Question
Title: Bulk Generating URL aliases for taxonomy terms doesn't do anything
In D7, I've imported ~8000 taxonomy terms. All these need to have a url alias, based off their names.

I can check the 'Generate automatic URL alias' checkbox when editing each taxonomy term individually but I cannot go through and do this for all 8000.

I tried updating the paths with Bulk Generate. In the Patterns tab for my taxonomy term vocab I have set `[term:name]`. But when I hit Bulk Generate it doesn't update anything.

Would anyone know of a solution? An SQL query perhaps?

# Answer
You'll need to troubleshoot your own site configuration to understand what's not causing the path update on the bulk form. If you look at the flow of execution, you can follow

Ultimately, all the form is doing to update is using `pathauto_taxonomy_term_update_alias_multiple()` to load/save a group of tids in bite-sized chunks; if you fail to pinpoint the problem, you can use that function to do what you're already doing manually.
> 1 votes

# Answer
I ended up using the SQL:

```
UPDATE pathauto_state SET pathauto="1" WHERE entity_type="taxonomy_term";

```
> 0 votes

---
Tags: 7, taxonomy-terms, path-aliases
---


# Question
Title: Configure visibility of block based on URL parameters
Is it possible to display a block only on a URL without any parameters? E.g. on:

* my.site.org/search

but not on:

* my.site.org/search?q=term

When I configure a block ('/admin/structure/block/manage/myblock') and set visibility for pages at: '**/search**' (see the picture), then the block is displayed on the page '**/search?q=term**' as well.

# Answer
> 4 votes
You can use condition\_query it will give you an extra box where you can put query parameters like `q=term`

---
Tags: 8, blocks
---


# Question
Title: Why do Font size and font color button makes CKEditor disappear when I move it to the active toolbar?
When I move the Font size and color buttons from available to active toolbar CKEditor disappear - why?

Note: I did not get an answer for this question - but I managed to fix the problem halfway by moving the libraries to the www folder (The color button still makes it disappear)

# Answer
> 4 votes
After enabling CKEditor, you have to go into the filter format in the admin that you want to edit, and configure the toolbars to have the buttons and configuration that you desire. It is a bit extreme to call it unusable.

For font color, there is an add on module that provides that plugin integration, ColorButton.

For font size there is CKEditor Font Size.

For your original question, there is no way to drop-in a custom build of CKEditor and drop it into your site (that I know of). I suppose it *could* be possible if you use the Editor API and extend and provide it, but there is not a lot of reason to do so.

I am aware that ColorButton only has a dev release, but it is quite functional. I will work at fixing a couple of superficial things and tagging a stable release.

Where ColorButton and others expect to find the plugin:

Adding the buttons to CKEditor:

You can then override the list of colors in the option box with your own.

Also note that ColorButton requires PanelButton (a utility CKEditor plugin) as well. It also requires downloading and placing panelbutton in /libraries.

# Answer
> 1 votes
I'm not sure if you have found your answer but I had the same issue with the CKEditor disappearing when I tried to install the Color Button module. The instructions for the Color Button and Panel Button modules are a bit confusing. You need to install the Drupal modules into the /modules folder but you also need to download the .js libraries from these links below and put those folders into the /libraries folder:

http://ckeditor.com/addon/panelbutton
http://ckeditor.com/addon/colorbutton

Once the .js libraries were installed the CKEditor did not disappear and the buttons worked fine.

# Answer
> 0 votes
I used a patch to solve this issue: Listing down the complete steps below:

1. Install the prerequistes for color button- Panel button library and module, UI button library and float panel library.
2. Install color button module and copy its library.
3. Listing down the changes in the patch. Goto **/modules/panelbutton/src/Plugin/CKEditorPlugin/PanelButton.php** and update the path from`$path = '/libraries/panelbutton/plugin.js';` to `$path = 'libraries/panelbutton/plugin.js';`
4. Enable the icon in configuration-\>Text Editor.

---
Tags: 8, wysiwyg
---


title: How do I escape tokens in CKEditor?

text:
# Question
Title: How do I escape tokens in CKEditor?
For documentation purposes, I'd like to write an article with token in it, for example `[toc]`.

How can I can avoid it is processed as token, and replaced?

# Answer
I achieve it by adding brackets in ASCII code.
> 1 votes

---
Tags: 8, tokens
---


# Question
Title: Display comments according to the users roles
I try to create various tabs for my nodes, which show a specific field and the comments of the users according to their roles :

>

I would like that these tabs are pages, and not in Javascript tabs.

I tried with Views, I created a view of comments, I manage to create pages, to have comments according to the roles, but not to add the desired field (what must be normal because it is about a view of comments and not about contents) :

I could can possibly serve me as templates, with templates suggestions, create a template by page, but I do not know how in the template to display comments according to the roles of the users...

Would you know a solution?

# Answer
1. You are almost there. You just have to have new display for each role. See below.
2. Set the path as below, per role per display:

3. It will appear as below in node page:
> 0 votes

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


# Question
Title: How to add touch to jQuery slider field?
I am on Drupal 7 using the sliderfield module (https://www.drupal.org/project/sliderfield)

I want the field to be mobile and touch friendly.

The module recommends using the Jquery UI Touch Punch module to solve this (https://www.drupal.org/project/jquery\_touchpunch/issues/2797477) however it is not working.

Can anyone recommend an approach that will work with step by step examples?

An example could include adding code to a custom theme that can work without using the above referenced module.

# Answer
As per Bendev's comment

1) Install libraries module

2) In sites/all/themes/YOUR\_THEME/**template.php** add the following:

```
function YOUR_THEME_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = libraries_get_path('jquery.ui.touch-punch') . '/jquery.ui.touch-punch.min.js';
}

```

Replace YOUR\_THEME with the actual name of your theme.

3) Clear/Flush all caches.
> 1 votes

# Answer
You do not need a module to be able to create a slider field to fix the blocker of not having a standard field type "slider".

In order to be able to do it, you can programmatically create a field using the jQuery UI slider.

This can be done through the following process:

1. Add the slider library;
2. Select a field name;
3. Make sure the field doesn't exist;
4. Define / create the field;
5. Create the instance;

////See the code

```
drupal_add_library('ui.slider');
/**
 * Update hook to add a field to a node.
 */
function my_module_update_7000() {
  $field_name = 'field_slider';
  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field['#attached']['js'] = array(
        'field_name' => $field_name,
        "jQuery(document).ready(function() { jQuery('#my-element').slider(); });" => array(
            'type' => 'inline'
        )
    );
    field_create_field($field);

    // Create the instance.
    $instance = array( 'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Slider',
      'description' => 'The article slider.',
      'required' => TRUE,
    );
    field_create_instance($instance);

    watchdog('my_module', t('!field_name was added successfully.', array('!field_name' => $field_name)));
  }
  else {
    watchdog('my_module', t('!field_name already exists.', array('!field_name' => $field_name)));
  }
}

```

**To note:** Replace in the instance `'bundle' => 'article',` with the name of the content type you want it attached to. In this example is adding the field to the *Article* content type.
> 1 votes

---
Tags: javascript
---


# Question
Title: Render a node field inside page.html.twig
I have an image field on my content type (field\_hero\_image).

I don't want it to render in the node.html.twig file. However, I DO want to render it in the page.html.twig file. Specifically, I want to render it alongside the page title.

What code would I use in my page.html.twig file to access node level fields and render them?

(There is a similar question posted, but I was unable to use the answer provided there to solve my problem.)

This for Drupal 8 theming.

# Answer
After doing quite a bit more research, I was able to find enough pieces in other questions and on drupal.org to achieve what I wanted to do.

No pre-processing is needed for this answer, so no code needs to be added to your mytheme.theme file.
All of these variables are already accessible in page.html.twig by default.

To render a field's default value inside page.html.twig, you would typically use a Twig variable as in `{{ node.field_some_name.value }}`.

If you have an image field, and want to render the URL to the image stored in that field inside the page.html.twig template, you would use `{{ file_url(node.field_some_image.entity.fileuri) }}`.

Finally, if you want to render the title of a node inside the page.html.twig template, you would use `{{ node.label }}`.

I also learned how to use some Twig conditionals for my particular issue, but that is beyond the scope of this question/answer.
> 34 votes

# Answer
There are three handy methods for working with this, all of which save you time digging in complicated render arrays.

1. Using Display Suite (with submodule ds\_extras) you can assign to the hero region a block ("block region") which is a different display mode (i.e. just one containing the hero image). Thus you get two different display modes showing at once. Note that some preprocess hooks may not fire as you might expect if you do this.
2. The twig\_tweak module greatly simplifies such tasks and can give easier twig statements for field values. Take a look at the cheat sheet for some common uses: `{{ drupal_field('field_image', 'node', 1) }}` The function signature is: `drupalField($field_name, $entity_type, $id = NULL, $view_mode = 'default', $langcode = NULL)`
3. The twig\_field\_value module makes simpler twig statements. Per README.txt: `<img src={{ file_url(content.field_image|field_target_entity.uri.value) }} alt={{ content.field_image|field_raw('alt') }} />`

If I had known this earlier, it would have saved me a great deal of time!
> 5 votes

---
Tags: theming, 8
---


# Question
Title: How can I programmatically extend the registration form?
I'm trying to extend registration form programatically to add an additional field. I was following an example from Extend \_form in Drupal 8

* I created a new service that will redirect to the new form.
* I created a route subscriber to that will return the new form.
* I created a form class that will extend the form.

It works for the user login form but wont work on user registration form because it is an `_entity_form` and I guess it should be treated differently. I changed the router subscriber to match registration form but i get this error.

> Call to a member function getEntityTypeId() on null.
>
> if ($route = $collection-\>get('user.register')) {$route-\>setDefault('\_entity\_form', '\Drupal\form\_overwrite\Form\NewUserLoginForm');

Can anyone suggest please what's the right way to extend this form? I tried with the all known `hook_form_alter` but even like that I'm not sure how to save the new field content in the configuration files.

# Answer
> 5 votes
I had this same question and it doesn't seem to be answered anywhere so I'll give the answer that I figure out, hopefully this helps someone.

First you need to add the form to the entity do this in the module file in `hook_entity_type_build` something like the following sample:

```
/**
 * Implements hook_entity_build
 */
function MYMODULE_entity_type_build(array &$entity_types) {

  $entity_types['user']->setFormClass(
    'MYMODULE_register',
    'Drupal\MYMODULE\Form\myModuleRegisterForm'
  );
}

```

Create a new class src/Form/myModuleRegisterForm.php to extend RegisterForm:

```
namespace Drupal\MYMODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RegisterForm;

class myModuleRegisterForm extends RegisterForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    $form = parent::form($form, $form_state);

    // Change the form here

    return $form;
  }

}

```

Then load it in your controller

```
public function myModuleRegister {

  $build = [];

  $entity = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->create([]);

  $formObject = \Drupal::entityTypeManager()
    ->getFormObject('user', 'MYMODULE_register')
    ->setEntity($entity);

   $build['form'] = \Drupal::formBuilder()->getForm($formObject);

   return $build;
}

```

That pretty much covers it, obviously you need the route to point to the appropriate function in your controller but otherwise this should do it. Hope it helps.

# Answer
> 3 votes
The other answers focus on overwriting the route itself. If you don't care about changing the route, but just want to change the form markup, here's how to do it:

In your .module file:

```
function your_module_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setFormClass('register', '\Drupal\your_module\Form\NewRegisterForm');
}

```

This overrides the Annotations set in User.php

```
*   handlers = {
 *     "storage" = "Drupal\user\UserStorage",
 *     "storage_schema" = "Drupal\user\UserStorageSchema",
 *     "access" = "Drupal\user\UserAccessControlHandler",
 *     "list_builder" = "Drupal\user\UserListBuilder",
 *     "views_data" = "Drupal\user\UserViewsData",
 *     "route_provider" = {
 *       "html" = "Drupal\user\Entity\UserRouteProvider",
 *     },
 *     "form" = {
 *       "default" = "Drupal\user\ProfileForm",
 *       "cancel" = "Drupal\user\Form\UserCancelForm",
 *       "register" = "Drupal\user\RegisterForm"
 *     },
 *     "translation" = "Drupal\user\ProfileTranslationHandler"
 *   },

```

The one we're interesting in is the `"register"` key under `"form"`.

Then in your NewRegisterForm.php you don't need to implement \__construct or create, as these are inherited from `RegisterForm`. In my case, I just wanted to change the submit button text, so I have:

```
class NewRegisterForm extends RegisterForm {

  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form, $form_state);
    $element['submit']['#value'] = 'Submit';
    return $element;
  }

}

```

Hope that helps, took me a while to find why overwriting the route didn't do what I wanted.

# Answer
> 1 votes
I had problem with my class throwing an error :

```
Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId()

```

Then I found this code and I think that for Entity form you have to add `__construct` and `create` functions:

```
<?php
namespace Drupal\my_module\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\user\Entity\User;
use Drupal\user\RegisterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a user register form.
 */
class NewUserRegisterForm extends RegisterForm {

    public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, ModuleHandlerInterface $moduleHandler) {
        $this->setEntity(new User([], 'user'));
        $this->setModuleHandler($moduleHandler);

        parent::__construct($entity_manager, $language_manager, $entity_type_bundle_info, $time);
    }

    /**
     * @inheritdoc
     */
    public static function create(ContainerInterface $container) {
        return new static(
            $container->get('entity.manager'),
            $container->get('language_manager'),
            $container->get('entity_type.bundle.info'),
            $container->get('datetime.time'),
            $container->get('module_handler')
        );
    }

    public function form(array $form, FormStateInterface $form_state) {
        $form = parent::form($form, $form_state);
        $form['test'] = [
            '#markup' => '<p>Test extended form</p>',
        ];
        return $form;
    }
}

```

Code from David Duymelinck Thanks to him.

---
Tags: 8, forms
---


# Question
Title: How to create Stacked area charts instead of Basic area charts using the Charts module?
Anyone know how to create multiple **stacked** area charts vs multiple **basic** area charts in Drupal using the Views integration of the Charts module (and using Highcharts as the charting engine)?

I would like to create a (stacked area) chart as shown at http://www.highcharts.com/demo/area-stacked, as opposed to the (basic area) chart as shown at http://www.highcharts.com/demo/area-basic.

Also, I would like pop up information to work with multiple stacked charts as it does with single area charts. It works on the sites included above but does not work with charts created with Drupal Views.

# Answer
> 0 votes
### Stacking the charts

The most recent Charts version does not yet support "stacked" charts (of type Area, or Column, etc.).

However, have a look at the support issue (not bug!) about Stacking column/bar charts. Even though that issue is not about "Area", the approach should also work for Area charts. The clue is in comment nr 1 or nr 3 of that issue, i.e. this specific line: `$chart['#stacking'] = true;`. So if you succeed in passing that, you solved your question. This is what you can see in the example included there:

```
<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

```

Obviously, the above requires a custom module, since it's not possible "yet" to so via the Views UI.

You may also want to have a look at these somehow related feature requests, which possibly provide an alternative to what you're trying to get to work:

Once we'll have these feature requests committed, we'll have a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

### Popup information

Refer to "Combination chart without aggregation" for an online demo of a chart (with multiple stacked charts) that shows such popup information (perform a mouse-over for any of the data points to see them at work).

This demo sample using Google Charts as its charting engine (not the Highcharts as in your question). Since nowhere within the Charts module there is some option to specify like "add popup information", my best guess would be that, by default (without specifying any charting engine options about it), the default for Google Charts is that such charts are created **with** such popups, while for Highcharts they are created **without** them. As a quick debugging hint: temporary change to the Google Charts engine and revisit your same chart, to check if that makes them show up in that case. So that you know it's really a Highcharts related setting that's missing (and which differs from the default).

If it doesn't seem to work for the Highcharts library, then you'll have to find out what the specific charting engine option for this is to make it work (there are tons of options in each charting engine, nobody knows them all, at least not me). After you know the specific option(s), you could try to use an approach of passing these options as raw\_options, similar to stacking the charts.

Disclosure: I'm a co-maintainer of the Charts module.

# Answer
> 0 votes
The latest -dev version of Charts (D8) now supports this for Highcharts and Google when you use the Grouping field.

---
Tags: 7, views, charts
---


# Question
Title: How to create 3d charts using Charts module and Highcharts library?
I want to create 3d charts using the Charts module and with Highcharts as its charting engine (library).

How can I create such 3d charts?

# Answer
> 1 votes
In the latest -dev version of the Charts module (D8), there is a checkbox to enable 3D for Highcharts and Google.

# Answer
> 0 votes
There is no out-of-the-box answer to your question to make this work with the Charts module (disclosure: I'm a co-maintainer), at least not as of today (yet). But if you're willing (and able) to complete a few extra steps, you should get it to work. Use the details below as a guide.

You could use the approach as described in the issue about Pass library-specific options via existing #raw\_options, AFTER you apply the patch in comment nr 4 of this issue. If you're using the most recent dev version of the Charts module (which is stable and includes various patches on top of the rc1 release), then this patch is already available (no more need to apply it).

Be aware that this only works for Highcharts as of right now (waiting for a similar patch to become available for Google Charts also).

PS 1: know that there are so many options / features in either of the supported charting engines (libraries), i.e. Google Charts and Highcharts. Which is also why it's virtually impossible to support all those options out-of-the-box.

PS 2: I'm assuming this question is about D7.

---
Tags: views, charts
---


# Question
Title: Create chart for user count of user role using chart module(c3 lib) in Drupal 8?
I want to use chart module(c3 lib) of drupal 8 to show a chart of user count for different roles using views. E.g.

```
Role Name  Total user
a             5
b             10
c             13

```

I achieved above table using aggregation in views. I followed this guideline to create a chart but when I create chart attachment and add it to parent, the value of child replace the value in the parent chart.It should merge. Any help would be appreciable.

# Answer
This is an issue of needing to be sure that you first set the format of the attachment display to "This chart attachment (override)", and then adjusting the format settings. Don't forget to attach your "Chart attachment" display to the appropriate display.

I wanted to set the style plugin to do this by default (see this issue: https://www.drupal.org/project/charts/issues/2899035), but I am unable to find any documentation on how to do this programmatically.
> 0 votes

---
Tags: views, 8, charts
---


title: Group date field by day for chart

text:
# Question
Title: Group date field by day for chart
I have a custom database table with a datetime column that I have made accessible to Views. I want to create a line charts of number of rows per day but I can't get the View right.

With aggregation on I have a COUNT on my ID field and I'm trying to group on my date field by day (it currently has year -month - day - hour - minute - second). I have set the date format to d/m/Y and aggregation to group results together but they are still separate.

Obviously this makes for a pretty bad line chart

What I really want is

```
18/01/2017    23
19/01/2017    25
20/01/2017    19

```

I tried the Views Date Format SQL Field module (dev version too) but it doesn't seem to work as I don't get an option to format my date as SQL.

Is this possible in Views?

# Answer
I believe there is a way to do this by rewriting the field described in this issue: https://www.drupal.org/project/charts/issues/2915097. There is also grouping enabled now if you want to stack your charts. Please download the latest -dev version.
> 0 votes

---
Tags: views, charts
---


# Question
Title: Creating a duplicate button for multiple entry field collection field
I'm building a form for inputting people's travel plans, and as part of that, I need to capture who will be in what country on what days (see diagram for relevant section of the form)

Next to the Add Another Item button to allow me to add another top-level itinerary, I would like to add a 'duplicate last itinerary button' that would add another item to the itinerary list, but copy the contents of the last itinerary item into it. Ideally, the button would only copy the data in the section surrounded by a dotted line on the diagram (the itinerary leg content) and leave the traveler(s) field blank.

If there is a ready module to do this, that would be fantastic, but I'd be perfectly happy for a code-based solution or failing that, pointers to good info.

I've found How to pre-populate multiple "field collection" fields in node form which in spite of being closed seems like it may contain good information on populating the entries. I think I need to know how to do basically 3 things and what hooks make sense to accomplish them:

1. add a button alongside the other multi-entry field buttons
2. read the contents of the last itinerary leg field collection field in the list of itineraries.
3. add a new item, and populate the itinerary leg field collection fields with the values from step 2.

# Answer
I think you should be using the Replicate API for this purpose. The module provides an API to duplicate entity along with many hooks. It's targeted towards developers however there are several modules build on top of it.

With respect to your use case, there is an implementation for supporting field collections. I think it will be the closest solution for you what you.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: is there a module for instagram like YouTube Field?
I need a module that permit to my editor user to choice photo from instagram and linked them in a field of a content type.

I have found https://www.drupal.org/project/instagram\_feeds but I don't want to create feeds for every node.

Edit: and if possible a youtube module too. ("Youtube" module permit to write video's url, but not a graphical choise). Thanks.

# Answer
> 0 votes
Firstly user will have to authenticate to their Instagram account. Then the user can access his personal photos via the end-point `/users/self/media/recent`. You will have to write some code to achieve this. The authentication part can be achieved using the HybridAuth module. Then you'll have to implement your own interface to search content.

This is if you want the user to first see a list of photos and then choose from it. If you just want to embed from url, you can use this module along with the media module.

Its also important to note that Instagram API no longer permits public scope, and you can only search your own images.

With respect to youtube, Media module along with Media: Youtubemodule allows you to add youtube video from a link. You can then set the video player or thumbnail settings from the display settings. However, by default, there is not out of the box solution to search for youtube video graphically and then add it to Drupal.

However, adding this on top of Media Youtube field won't be very hard. Quick js around this form could solve the issue. See to quick js based youtube search below:

1. https://codepen.io/timivey/pen/jEXxZY
2. https://www.w3tweaks.com/youtube/search-youtube-videos-using-youtube-v3-api-using-jquery-ajax-call.html **(Click on Demo)**

You can use the Drupal Form Alter and Form attached options to add the necessary JS and CSS to the form.

---
Tags: 7, entities
---


# Question
Title: How to implement a cron job for every minute and every 5 minutes?
In D8 I programmed hook\_cron. I tested it several times but I cannot see any log in the watchlog.

The name of the module is nncbt. The code is placed in nncbt.module.

Any suggestions what I should do?

```
function nncbt_cron() {

    $last_run_per_minut = \Drupal::state()->get('nncbt.last_run', 0);
    // If 1 minutes passed since last time.
    if ((REQUEST_TIME - $last_run_per_minut) > 60) {

        \Drupal::logger('nncbt')->info('Runnning Cron every 1 minut log');

        // Update last run.
        \Drupal::state()->set('nncbt.last_run', REQUEST_TIME);

    }

    // Run the following every 5 minutes
    $last_run_per_5_minuts = \Drupal::state()->get('nncbt.last_run_5_minuts', 0);

    // If 5 minutes passed since last time.
    if ((REQUEST_TIME - $last_run_per_5_minuts) > 300) {

        \Drupal::logger('nncbt')->info("Runnning Cron every 5 minut log");

        // Update last run.
        \Drupal::state()->set('nncbt.last_run_5_minuts', REQUEST_TIME);

    }

}

```

# Answer
hook\_cron()

> The engine will then **call the hook whenever a cron run happens**, as defined by the administrator.

In other words, hook\_cron gets executed **after** a cron run happens. So if you have cron set to run once a day, then your hook\_cron script only gets executed once per day. So you need to set cron to run every 5 minutes or less.

A better alternative, I suggest you use a module like Ultimate Cron which allows you to schedule different cron run times for different cron tasks. This way, cron doesn't run every single task every 5 minutes and instead it runs your specific task only.
> 9 votes

---
Tags: 8, cron
---


title: Update Drush in Docker4drupal

text:
# Question
Title: Update Drush in Docker4drupal
I have to upgrade Drupal core to 8.4 with Composer. Drush version is 8.1.12.

I use Docker4drupal for my local development environment. How do I update Drush to 9 within my docker container setup, so I can upgrade Drupal to 8.4?

# Answer
> 1 votes
Assuming you're using the default `wodby/drupal:8-7.1-3.3.2` container image, the drush launcher is already installed in the PHP FPM container.

Thus, your next step is to update your Drupal 8 composer drush dependency via composer:

`composer require 'drush/drush:^9'`

When drush launcher executes under your web root it will pick up the version 9 that's installed in your `vendor` dir.

---
Tags: drush, upgrading
---


title: Running a Script with Job Scheduler API

text:
# Question
Title: Running a Script with Job Scheduler API
I am trying to use the Job Scheduler Module's API to automatically run a script every 6 hours but I'm having problems getting it working.

This is the code:

```
function jobbank_cron_job_scheduler_info() {
  $schedulers = array();
  $schedulers['custom'] = array(
    'worker callback' => 'custom_job',
    'jobs' => array(
       array('crontab' => '6 * * * *', 'periodic' => TRUE),
    )
  );
  return $schedulers;
}

function get_job_bank() {
  //Save the (long) job bank URL
  $jobBankURL = "https://www.jobbank.gc.ca/xmllite/en/?q=city_id:33821";
  $jobURL = "https://www.jobbank.gc.ca/xmllite/en/";
  $jobs = [];
  $jobInfo = null;

  //Get the XML data into an object
  $jobsInfo = simplexml_load_file($jobBankURL);

  //Send a message and exit if it fails getting the XML
  if($jobsInfo === false) {
    mail ('webmastercolin@gmail.com',
          'Job Central SM Job Bank CRONjob issue',
          'Getting the $jobsInfo XML data failed (line 9) at '.date('H:i:s \o\n F j, Y'));
    exit();
  }

  //Iterate through the objects
  foreach($jobsInfo->Documents->Document as $job) {
    //Get the job data from Job Bank
    $jobInfo = simplexml_load_file($jobURL.$job->jobs_id.".xml");

    //Grab just the information for the job and put it in the array
    $jobs[] = $jobInfo->Documents->Document;
  }

  //Encode the array as JSON
  $json = json_encode($jobs);

  //Send a message and exit if it fails encoding the JSON
  if($json === false) {
    mail ('webmastercolin@gmail.com',
          'Job Central SM Job Bank CRONjob issue',
          'JSON encoding the array failed (line 23) at '.date('H:i:s \o\n F j, Y'));
    exit();
  }

  //Save new data to json file, overwriting existing
  $writeResult = file_put_contents($base_path . 'sites/default/files/jobbank/job-bank-data.json',$json,LOCK_EX);

  //Send a message and exit if overwriting the file failed
  if($writeResult === false) {
    mail ('webmastercolin@gmail.com',
          'Job Central SM Job Bank CRONjob issue',
          'Writing to the JSON file failed (line 31) at '.date('H:i:s \o\n F j, Y'));
    exit();
  }

  //Send a message on success, we are done
  mail ('webmastercolin@gmail.com',
        'Job Central SM Job Bank CRONjob Success!',
        'JSON creation succeeded at '.date('H:i:s \o\n F j, Y'));
  exit();
}

```

I appreciate the help.

# Answer
> 1 votes
1. If you want to schedule it every 6 hours, then it's `'crontab' => '0 /6 * * *'`

The README.txt contains examples:

> ```
>  /* Declare scheduler. */
>
>   function example_cron_job_scheduler_info() {
>     $schedulers = array();
>     $schedulers['example_unpublish'] = array(
>       'worker callback' => 'example_unpublish_nodes',
>     );
>     return $schedulers;
>   }
>
>  /* Add a job. */
>
>   $job = array(
>     'type' => 'story',
>     'id' => 12,
>     'crontab' => '0 /6 * * *', // I changed this line.
>     'periodic' => TRUE,
>   );
>   JobScheduler::get('example_unpublish')->set($job);
>
>  /* Work off a job. */
>
>   function example_unpublish_nodes($job) {
>     // Do stuff.
>   }
>
>  /* Remove a job. */
>
>   $job = array(
>     'type' => 'story',
>     'id' => 12,
>   );
>   JobScheduler::get('example_unpublish')->remove($job);
>
> ```

2. `'worker callback' => 'custom_job'` it's bad practice to not include the name of your module in your callback. This is to prevent collisions. You should name it `module_name_custom_callback`. In your case it would be `'callback' => 'jobbank_custom_job'`
3. The Job Scheduler is only going to schedule it, not run it. It will get run whenever cron runs. So if you have cron run set to once a day, it will only run your scheduled task once a day. Therefore, you will have to set cron to run every 6 hours or fewer.
4. Alternatively, I suggest you use a module like Ultimate Cron which allows you to schedule different cron run times for different cron tasks. So you can set it to every 6 hours here.
5. This is the proper Drupal way to programmatically send e-mails How to programmatically send an email?

---
Tags: 7, hooks, cron
---


# Question
Title: How to make changes in HTML code and make them show up on site
I am working on a Drupal 7 site that is being manged via Github.

I am trying to change the HTML code on one page. The HTML that I am changing is in the \[appname\]/sites/all/themes/\[app\] folder. The HTML in this file is identical to what is on the page if I were to go to the \[siteurl\]/user/login then navigate to the page and press edit. However when I change the HTML on my local branch and push it up to github and then deploy it using heroku it doesn't actually change the page.

My question is how can I change to way this page is displayed in code instead of changing the page on the drupal website itself.

# Answer
Look into using the Features module. This way, you can convert any configurations that are stored in the database to code, push them up to the repository, and then pull and revert all the features on your test and production site. You can add template work as a custom feature as well. You should stray away from editing code in Drupal and lean toward creating custom themes, modules and features. I would be no where without this module.
> 0 votes

---
Tags: theming
---


title: Export with default_content

text:
# Question
Title: Export with default_content
I have been able to export the commerce\_store, commerce\_product\_variation and commerce\_product entities with the default\_content module and the drush dce (default-content-export) command, but when importing back, the products and the product variations are not linked together. What am I missing?

Has anybody managed to export products and import as default content in a drupal commerce 2.0 site?

# Answer
Commerce currently does not work correctly with default\_content. The commerce guys are looking into solutions for delivering default content.

AFAIK the next version of yaml\_content is gonna be able to play nicely with commerce. However as of now, the module has no commands for exporting content, only for importing.

default\_content - Question about architecture

yaml\_content - Content Export Support
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How to remove default div wrappers from fields output via custom field formatter?
I have a custom field and custom field formatter created in Drupal 8. I need to remove the default FIELD VALUE wrappers so that I can build an HTML table with the field values.

The field formatter is currently using a custom twig template, but I `<div>`'s are being rendered prior to the template, so I can't remove them there.

How can this be accomplished?

# Answer
The div wrapper you are looking for is probably in `field.html.twig`. Drupal provides a theme name suggestion for a custom field type automatically, so you can override this template by placing `field--myfieldtype.html.twig` in the theme templates folder.

If you want you can deliver a default template with the custom field module, like the comment module does for the comment field:

```
core/modules/comment/templates/field--comment.html.twig

```

Then you need to define a theme hook in *mymodule.module*.

Example from the comment module:

```
/**
 * Implements hook_theme().
 */
function comment_theme() {
  return [
    // ...
    'field__comment' => [
      'base hook' => 'field',
    ],
  ];
}

```
> 1 votes

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


title: routing.yml file doesn't work

text:
# Question
Title: routing.yml file doesn't work
I'm working on an existing Drupal 8 site. I'm changing anything in routing.yml.

In a routing.yml file I have the following.

```
user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

```

I want to change the controller's method to `\Drupal\user_profile\Controller\ProfileUpdateController::updateUser123()`, but after editing the route definition, the `ProfileUpdateController` class is still using the `updateUser()` method.

I removed all the cache tables from the database with the following SQL, but the controller is still not using the `updateUser123()` method.

```
TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;

```

How can I fix the issue?

# Answer
You're saying that you have this in your routing.yml file:

```
user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

```

You're still calling updateUser and not updateUser123

Your controller should be looking like this:

```
class ProfileUpdateController extends ControllerBase {

  public function updateUser123() {
  //your code here
  }

}

```

And now you'll need to call the method:

```
user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser123'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

```

Also I recommend clearing your cache with Drush. This will empty all caches and rebuild the data required for Drupal to execute the page request
> 0 votes

---
Tags: routes
---


# Question
Title: How to render a template declared in hook_theme directly in a twig template without preprocess?
Lets say I have a hook\_theme like this :

```
/**
 * Implements hook_theme().
 */
function mytheme_theme($existing, $type, $theme, $path) {
  return [
    'partial' => [
      'variables' => ['current_url' => NULL],
      'template' => 'partial'
    ]
  ];
}

```

Then in a node.html.twig, I want to call the template.

Currently I'm doing this :

```
{% include '@mytheme/partials/partial.html.twig' {'current_url': url('<current>')} %}

```

But the problem with this is that I never go into my

```
function mytheme_preprocess_partial(&$variables) {}

```

Also I can't benefit from the TWIG DEBUG mode.

Is there any way to do something like this :

```
{{ theme('partial', {'current_url': url('<current>')}) }}

```

Thanks for helping.

# Answer
> 1 votes
In D8 there is no theme() function, so if you want to render a template you use a render array for it. Put it in a twig variable and print it:

```
{% set partial = {
  '#theme': 'partial',
  '#current_url': url('<current>'),
} %}

{{ partial }}

```

As a side note, because of a security issue for Twig in Views you might be no longer be able to do this in Drupal 8.6 and are forced to use PHP in the near future. There is an ongoing discussion what to do about the code execution vulnerability without (hopefully) preventing such valid use cases, see https://www.drupal.org/project/drupal/issues/2860607

---
Tags: 8, theming
---


title: Open social date format

text:
# Question
Title: Open social date format
I'm working on a Open Social (Drupal 8) implementation. When adding an event you can submit the begin & end date. Is there any way to change the date format in these forms? I went through the whole system, found a lot of date format settings, non of them had any influence on this form.

# Answer
Ensure you have the Field UI module enabled.

If you go to `Structure > Content Types > Event > Manage form display` (`admin/structure/types/manage/event/form-display`) then you can change the form widget that is used there.

The `Date and time` widget which is the default has no configuration available. However, you can also use the `select list` widget which allows you to specify `Date part order` and `Time type`.
> 1 votes

---
Tags: datetime
---


# Question
Title: How to use CURDATE() and INTERVAL in Drupal Database object syntax
How to convert SQL query to Drupal Database object query. I have already tried many ways but I didn't get success.

```
# Get the records which are published in week
SELECT node.nid as nid
FROM node node
INNER JOIN field_date field_date ON node.nid = field_date.entity_id
WHERE from_unixtime(field_date.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE();

```

The above query is working fine in mysql.

# Answer
Try `db_query()` function: Solution -1

```

$query = 'SELECT node.nid as nid FROM node node INNER JOIN field_date field_date ON node.nid = field_date.entity_id WHERE from_unixtime(field_date.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()';
$result = db_query($query)->fetchAll();

```
Solution-2
```

$query = db_select('node', 'n');
$query->fields('n', array());
$query->innerJoin('field_date', 'fd', 'n.nid = fd.entity_id');
$query->where('FROM_UNIXTIME(fd.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()');
$result = $query->execute();

```
> 1 votes

---
Tags: nodes
---


# Question
Title: Overriding views-view-grouping.tpl.php when grouping by only one field
I have a view being grouped by one field. I'm trying to theme the groups as a whole (wrap divs around the whole thing, essentially) and I did so by overriding `views-view-grouping.tpl.php`. However, nothing happens. Out of curiosity I added another grouping and voilá, my template override is being picked up now. Only problem is, I don't need to group by two fields, just one.

Why is it doing this? Is there a separate override for single-grouped views? What is going on and how can I get Views to pick up my override of `views-view-grouping.tpl.php` when grouping by only one field?

# Answer
> 6 votes
I've had the same issue. At first I though it was connected to the current theme I was using, but after testing with a few different themes I discovered that not to be the case. I still do not understand that behavior.

As a workaround I've used views-view-unformatted--YOURVIEWMACHINENAME.tpl.php template where you can give a wrapper to a group in a single-grouped view. Here's what I had in the template:

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
    <?php
        //open group wrapper
        print '<div class="custom-class">';
    ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>
<?php if (!empty($title)): ?>
    <?php
  // close group wrapper
    print '</div>';
    ?>
<?php endif; ?>

```

You can even assign a custom class to each group by taking a certain field from $view object and transforming its value into a class name.

Of course, this method will only work for a single-grouped view. If the view will be grouped by more than one field, only the most inner group will be wrapped. Hope this helps.

# Answer
> 1 votes
The brilliant solution by Oksana-c also works great in Drupal 8 in Twig (views-view-unformatted--my-view--my-display.html.twig):

```
{#
/**
* @file
* Theme override to display a view of unformatted rows.
*
* Available variables:
* - title: The title of this group of rows. May be empty.
* - rows: A list of the view's row items.
*   - attributes: The row's HTML attributes.
*   - content: The row's content.
* - view: The view object.
* - default_row_class: A flag indicating whether default classes should
be
*   used on rows.
*
* @see template_preprocess_views_view_unformatted()
*/
#}
<div class="grouping-row">
{% if title %}
  <div class="grouping-title">{{ title }}</div>
{% endif %}
{% for row in rows %}
  {%
     set row_classes = [
       default_row_class ? 'views-row',
     ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
 {% endfor %}
</div>

```

---
Tags: views, theming
---


# Question
Title: Drupal 8 - Alter page attachments AFTER form submit
How do you add a library to page attachments (or perform any other alteration) only AFTER form submission?

**Long explanation:**

I have a very simple contact form which redirects to the frontpage after submission and displays a "Thank you" message.

I need to trigger custom JS events for Google AdWords integration after form submission. In theory this is very simple, just implement `hook_page_bottom` and attach library with custom JS code.

However, this library should only be attached after form submission and I can't figure out how to detect whether a page load comes from a form submission. My first attempt was to implement `hook_form_alter` and add a custom submit handler. However, this submit handler is only fired right after form submission, but not in the next page load, which means that my library doesn't get attached.

What is the Drupal way of this?

# Answer
> 1 votes
I see two ways of doing this.

**Options 1:** Make the form Ajax. Either by using Form API in Drupal or Jquery. Then in success function call your custom js event. Or else you could also do something like this:

```
 $('#some-form-123').submit(function() {
    _gaq.push(['_trackEvent', 'Contactform', 'Form submitted']);
  });

```

*The above code is an example, you need to use it for your event.*

**Option 2:** In Drupal set a cookie when the form is submitted. Then in page load, check if the particular cookie exists. If it does exist invoke your custom event and unset the cookie. Then, the cookie is only present if the form is again submitted.

**See the following:**

1. https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
2. https://github.com/jquery-form/form
3. https://github.com/js-cookie/js-cookie

# Answer
> 1 votes
My recommendation:

Alter the redirect value so that it contains a query parameter on the URL (after valid submit). Check for query parameters presence in hook\_page\_alter and then do you thing. This also has added benefit of keeping your JS outside of normal front page cache.

---
Tags: 8, forms
---


# Question
Title: How do I retrieve values from a webform?
I can see the values submitted in the `$_POST`, so I know they are there, but when I uses a submit handler to retrieve them, I get `NULL`. I'm fairly new to PHP so not sure if it's a simple syntax mistake or something more. Thanks.

```
function zendesk_forms_form_alter(&$form, &$form_state, $form_id){

  if ($form_id == 'webform_client_form_47') {

    $form['#submit'][] = "zendesk_forms_support_form_submit_handler";
  }
}

function zendesk_forms_support_form_submit_handler($form, &$form_state) {
  form');
  $ticket = array(
      'description' => $form_state['values']['description'],
      'subject' => $form_state['values']['subject'],
  );
  echo $ticket;

```

# Answer
> 0 votes
Try this:

```
$ticket = array(
  'description' => $form_state['values']['submitted']['description'],
  'subject' => $form_state['values']['submitted']['subject'],
);

```

# Answer
> 0 votes
I figured it out. Thanks to https://drupal.stackexchange.com/users/70895/geat for the advice of dumping the `['values']`. I was able to access the values by key.

```
$ticket = array(
    'comment' => array(
      'description' => $form_state['values']['submitted'][6],
      'subject' => $form_state['values']['submitted'][5],
    ),
  );

```

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


title: Redirect users to an external URL

text:
# Question
Title: Redirect users to an external URL
Is it possible to redirect users from a controller?

I tried using the following code, but it doesn't work.

```
public function hello() {
  $query = $db->select('coop.oad','x');
  $query->fields('x', ['oad_url']);
  $query->condition('x.oad_soc', $column_name,'=');
  $result = $query->execute()->fetchField();

  return new TrustedRedirectResponse($result);
}

```

# Answer
This should do it:

```
$redirect = new TrustedRedirectResponse($url);
return $redirect->send();

```
> 1 votes

---
Tags: 8, users, redirection
---


title: Adding class to module block

text:
# Question
Title: Adding class to module block
When I use the this code; `<?php $block = module_invoke('locale', 'block_view', 'language'); print $block['content']; ?>`, I get the following output. But I'd like to add another class to ul.

```
<ul class="language-switcher-locale-url"><li class="en first"><a href="/en" class="language-link" xml:lang="en">EN</a></li>
<li class="tr last active"><a href="/ru" class="language-link active" xml:lang="ru">RU</a></li>
</ul>

```

# Answer
Some trial and error but the following allowed me to get the right format;

```
<?php $block = module_invoke('locale', 'block_view', 'language'); $content =  $block['content']; $content = str_replace("language-switcher-locale-url","language-switcher-locale-url dropdown-menu",$content); print $content;?>

```
> 0 votes

# Answer
Have you tried rendering the content instead?

```
<?php print render($block['content']); ?>

```

That, combined with the Block Class module should at least allow you to add a class to the wrapper, which is the next best thing to overriding the theming of the actual UL.
> 0 votes

# Answer
## 1 Enable debugging

in your `sites/default/services.yml`

```
twig.config:
  debug: true

```

## 2 Clear cache

## 3 enable your browser's HTML comments

in chrome it is something like `Preferences > Elements > Show HTML comments`

## 4 find out the template used for this block

by looking in the inspector you can find suggestions on how to override this template

in my case there is a suggestion `links--language-block.html.twig`

## 5 copy original template

either from `core/modules/system/templates/links.html.twig` or from your themes template directory if you are subtheming

Paste into your theme's `template` directory and name it as suggested

## 6 modify the template

and `addClass` to `UL`

This

```
  <ul{{ attributes }}>

```

becomes

```
  <ul{{ attributes.addClass("my-class") }}>

```

## 7 clear cache again

in your inspector you should see your template and your class

To find out more about twig name conventions and using attributes in templates
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Drupal View Show Webforms NOT Submitted By Logged In User
I'm hoping someone can help me out with this because I have been stuck on this for days...

I have a bunch of webforms that each user needs to submit. I figured out how to show a view of the webforms the logged in user has submitted, but what I am stuck on is showing the webforms the user has NOT submitted in a view. So it would be a list of the webforms the user still needs to fill out.

There must be something small I am overlooking. I appreciate any ideas or help, thanks!

# Answer
Im not sure about this question: but here you go. Go to View and to ADVANCED\>RELATIONSHIP\> SElect USer. After that FILTER CRITERIA and add USER as well. NEXT, create roles and work around roles and users.
> 0 votes

---
Tags: users, webforms, views
---


# Question
Title: Add code to <head> for specific content type
What would be the best way to add code inside the tag of specific content type?

Display Suite is being used for layout and we are using a custom theme. Have created html.html.twig. If I add anything to the head tags of this file, of course, it shows on all the pages.

Can we create a separate template such as html--content-type.html.twig then add the code there?

If not what would be the Drupal way of adding this code to the head tags for only specific content type?

```
<script async
   src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
   <script>
     (adsbygoogle = window.adsbygoogle || []).push({
          google_ad_client: "ca-pub-3********",
          enable_page_level_ads: true
     });
</script>

```

# Answer
> 3 votes
## The quick way

and maybe some will call it **dirty** way would be to add in your `THEMENAME.theme` file

```
function THEMENAME_preprocess_html(&$vars) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    // You can get nid and anything else you need from the node object.
    $vars["content_type"] = $node->bundle();
  }
}

```

and then in your `html.html.twig`

```
{% if content_type == "page" %}
  <script> ... </script>
{% endif %}

```

## alternatively

you can just put it in a .js file and include like this

```
function my_module_preprocess_html(&$variables) {
  // To get around the issue of D8 core escaping inline js we cram our js
  // file into a twig variable for printing "raw" in "html.html.twig" like so:
  // {{ my_module_script|raw }}
  $variables['my_module_script'] = '<script type="text/javascript">' . file_get_contents(dirname(__FILE__) . '/js/script.js') . '</script>';
}

```

as described in this comment

## proper way is probably to

Define a library and then to attach it following this guide

---
Tags: theming, display-suite
---


# Question
Title: How to get nodes that do not belong to a particular user role
I am getting custom entity nodes using entity queries like below:

```
  $query= $this->entity_query->get('order_entity')
      ->condition('external_id', $data['external_id']);

  $order_nids2 = $query->execute();

```

I am trying to put a condition where I can get nodes which do not belong to a particular user role. How can achieve this?

# Answer
Nodes are only associated with author's nids (not user roles)

Thus you should do a query first to get the userids that match your selected user roles. Then use that array to filter out nodes with authors that belong to those user ids.
> 1 votes

---
Tags: 8, nodes, entities, database
---


# Question
Title: Drupal Commerce add to cart is no longer working for anonymous users
I just updated to Commerce Kickstart 7.x-2.52 and add to cart is no longer working for anonymous users. It shows the success add to cart message but nothing is added to the cart. If I log in it works fine. I’ve tried:

* I checked out and UID 0 is still in the DB
* Disabled honeypot module
* emptied the cache\_from table
* enabled “disable SQL rewrite” on the cart view
* check permissions for the anonymous user
* cleared the cache

UPDATED The order entity is being created but nothing shows in the cart.

# Answer
Commerce Kickstart added these lines to the */profiles/commerce-kickstart/.gitignore* which prevented new files from being added to git and thus not getting pushed to production.

libraries
modules/contrib
themes/contrib

https://www.drupal.org/project/commerce\_kickstart/issues/2937535
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Localhost Drupal Install on Linux shows file and not site
I am trying to set up a local Drupal install on my Linux 16.04 laptop install for learning/exploring Drupal.

I have made it through this install guide , completing all steps, but when launching my `http://my_example_drupal_site.localhost/web/` I am getting the below output.

Any idea why this is?

```
/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt files in the "core" directory.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

```

---

**Solved**

Followed this guide as suggested and got my install working.

Ran into two issues along the way. Turns out when setting up my Linux Box long ago, I had an entry in `/etc/hosts/` file that had a name for 'localhost'.

When pointing my browser at `localhost`, the default Apache "It Works!" page did not work. However when pointing to the name I had in `/etc/hosts/` it did work. But php file would not load and only showed "Index Of /" in the browser.

After more searching, I came to find I needed to load the mod in apache.

Trying:

```
a2query -m php7.0
No module matches php7.0

```

did not work, even though it was already installed which I discovered after trying to reinstall it

`php7.0 is already the newest version (7.0.25-0ubuntu0.16.04.1)`

Finally stumbled upon this answer in AskUbuntu and low and behold this worked for me, allowing me to enable the mod in apache

`sudo apt-get purge php*`

`sudo apt-get install php7.0-mysql php7.0-curl php7.0-json php7.0-cgi php7.0 libapache2-mod-php7.0`

I don't know how or why, but it worked for me.

# Answer
Just to get the question answered:

You missed the step about setting up Apache and PHP in the installation guide you read. In particular, you have to follow the How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 16.04 guide from DigitalOcean - linked to in the installation guide.
> 0 votes

---
Tags: drush, composer
---


# Question
Title: Forbid or autocorrect a certain term in a vocabulary
I am looking for a way to prevent a certain term to be created in a vocabulary. I don't know if there exists a contrib module with this functionality yet. Searches on Google did not deliver so far.

In fact, what I am trying to accomplish is this. In my native language we say "Brussel" but the English version is "Brussels". We have 20 editors and the one uses "Brussels" as a tag, another one uses "Brussel", which ends up with 2 seperate taxonomy overview pages. Yes, I could make it a guideline to use only "Brussel" as a tag, but overtime, they probably forget.

So is there a way that I can 'block' the use of "Brussels" as tag or autocorrect it to "Brussel" when they use "Brussels"?

Thanks for the help already!

# Answer
> 1 votes
The autocorrection scenario is one the use scenarios covered by the Synonyms module. It's a general purpose tool that works with taxonomy term references (tags) as well as other entities. It also has other integrations with projects that help with mitigating complexities with duplicate taxonomy terms (e.g. Term Merge).

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


# Question
Title: Login Form not respecting "?destination" parameter or any redirect methods
I have a destination parameter appended to /user/login using Redirect 403 to User Login. This presents users with the login page when they encounter a 403, allowing them to login and subsequently be redirected back to the page they were just on. For whatever reason, the redirect functionality that's built in is not working -- users are still directed to /user after logging in.

Within my `form_alter`, I have tried:

* Using `$form['#submit'][]` to set `$form_state['#redirect']`, which is ignored.
* Similar in `$form['submit']['#submit'][]`, along with `unset($form['#action'])` which I'm not familiar with but I read somewhere might be applicable.
* Using `drupal_register_shutdown_function('drupal_goto', $destination)` to set the redirect as a shutdown function which should execute after everything else and force a redirect.
* Setting `drupal_static_reset('drupal_get_destination')` before my shutdown function to try and reset any other redirects.

In all cases I have verified that my callbacks are running and that variables are being set as they should be, but nothing is working. Any ideas how to force this redirect or debug what is overriding it?

# Answer
> 0 votes
With the Redirect 403 to User Login module, you shouldn't have to add any hooks for the behavior to kick-in. You just need to enable the module and check its settings at admin/config/system/site-information

Here are some debugging suggestions:

1. Check for conflicting modules that serve similar functionality being enabled

* Redirect 403 to User Login
    * Login Toboggan
2. Disable custom modules and custom theme, and test redirect behavior. It should work out of the box. If not, try reinstalling the module.
3. Then, turn the custom theme and each custom module on one-by-one to identify which is causing the conflict. Once you've identified if it's in the theme or a custom module, search the hooks for any redirect behaviors.

# Answer
> 0 votes
Just to clarify what I did to fix this for anybody who might land on this in the future, the Login Destination module implements `hook_drupal_goto_alter`, which appears to override all other redirects. In order to override it, I had to implement my own version of `hook_drupal_goto_alter`, as well as make sure that my module weight was heavy enough to take precedence over Login Destination's implementation. To help set module weights, I used Modules Weight.

---
Tags: forms, users
---


# Question
Title: Drupal 7. Webform textarea with a html editor
I am using drupal 7.56 I used the webform module to create a custom form which contains a textarea.

I want to add a html editor to my textarea.

I tested webform\_html\_textarea but it's not what I need.

How can I configure CKEditor module for this issue?

# Answer
This is fixed by enabling **wysiwyg**, **ckeditor** and **webform\_html\_textarea**

Thank you
> -1 votes

---
Tags: 7, webforms, wysiwyg
---


# Question
Title: Template suggestions for file_entity.tpl.php
## Short version

My aim is to theme a file field in a view of node fields. In the view configuration, the field formatter is set to `Rendered file` and a view mode is selected. How do I suggest a template file?

## Long version

What I see is, theming of a file entity is done through file\_entity.tpl.php in `file_entity` module. I copied this file to my theme folder and tried following names:

```
file_entity--my-view-mode.tpl.php
file-entity--my-view-mode.tpl.php
file_entity--views--my-view-mode.tpl.php
file-entity--views--my-view-mode.tpl.php

```

None worked. So I tried to hook in some suggestions like below as `view_mode_templates.module` also does.

```
<?php
MYTHEME_preprocess(&$vars){
  $vars['theme_hook_suggestions'][] = 'file_entity__views__my_view_mode';
}
?>

```

This ends up loading that `file-entity--views--my-view-mode.tpl.php` but funnily I get an error like this:

> **Fatal error:** Only variables can be passed by reference in **blah/blah/file-entity--views--my-view-mode.tpl.php on line 71**

Which is actually this line:

```
hide($content['links']);

```

Funnier thing is if I comment that line out, I get a fatality masterkill WSOD with no error message.

If I try to do it like below, again as `view_mode_templates.module` does, it doesn't see the suggestion.

```
<?php
function MYTHEME_preprocess(&$vars) {
  if (array_key_exists('file_entity', entity_get_info())) {
    $vars['theme_hook_suggestions'][] = 'file_entity__views__my_view_mode';
  }
}
?>

```

So, does it maybe not suggest the theme suggestion in the correct place? Do I need to suggest this in something like `template_preprocess_file_entity(&$variables)` or `template_preprocess_entity(&$variables)`? Which don't have the appropriate `$vars['theme_hook_suggestions']` array as far as I couldn't see.

Any comment is hardcore appreciated, thanks.

# Answer
> 6 votes
There's a documentation about template suggestions at Displaying Media under the heading *Further Theming*.

> The theme suggestions provided by the File Entity module are:
>
> ```
> file__{file type}
> file__{file type}__{view mode}
> file__{mime type}
> file__{mime type}__{view mode}
> file__{file id}
> file__{file id}__{view mode}
>
> ```

# Answer
> 0 votes
Here's an actual example for "document" file type:

```
file--document.tpl.php
file--document--default.tpl.php   // default view
file--application-pdf.tpl.php   // pdf mime type
file--application-pdf--default.tpl.php
file--1234.tpl.php   // file id
file--1234--default.tpl.php

```

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


title: Is Drupal ready for GDPR compliance?

text:
# Question
Title: Is Drupal ready for GDPR compliance?
Is Drupal is ready for GDPR compliance?

Is there any patch or extension they need to apply for GDPR ready for all EU countries as this is the law for EU countries the come in effect on may 25, 2018.

# Answer
I'm one of the maintainers of the GDPR module.

First of all I'd like to call your attention to the fact that GDPR is not an IT-related question solely. Personally I'd suggest stop considering *"adding an extension to my CMS will make me legally good"*. That's not that easy. You, or the owner of the Drupal website you maintain/develop on their behalf should transform their organization/company's inner workflow of dealing with personal data.

However, the GDPR module indeed can be a perfect starting point to install, go through on its checklist points and after you read them carefully, hopefully will realize that you're just stepped on the path of becoming GDPR-compliant, but a big portion of tasks ahead probably falls out of the scope of configuring Drupal.
> 9 votes

# Answer
I don't think Drupal is "ready" for the General Data Protection Regulation (GDPR), at least not yet.

However, help seems to be on its way ... go checkout what the General Data Protection Regulation module *will be* (repeat: *will be*) about. From its project page:

> This module gives end-user visibility to the data stored about himself/herself and aims to help site admins follows the guidelines and legislation set by the EU.
>
> ### Current features
>
> * Checklist for site admin (recommend modules like cookie consent, check if there is privacy policy page etc).
> * Drush command (drush gdpr-sql-dump) to obfuscate data. Primary goal is to prevent developers from accessing user data.
>
> ### Future features
>
> * Allow logged in user to see all raw data stored about himself/herself (user entity).
> * Allow user to initiate “forget me” action from site admins.
> * More items and recommendations to checklist.
> * Make sure user can rectify all data about himself/herself.
> * Allow user to remove the account (content is not removed).
> * Make API for other contrib modules to announce user data stored.

There is a release in the pipeline for both D7 and D8, though so far only ***alpha*** versions ... Fingers crossed to see what will happen by the GDPR's Enforcement date, i.e 25 May 2018.

# Other GDPR related modules

Some other modules in the Drupal pipeline (only alfa/beta releases today), which may give you an idea about the areas of a Drupal site that may need attention, including quotes from their project pages (there are more GDPR related "sandboxes" also):

* General Data Protection Regulation Compliance

> Basic GDPR Compliance use cases:
>
> + Form checkboxes
>     + Pop-up alert
>     + Policy Page
* GDPR Consent

> ... collects GDPR Data processing consent from logged-in users using the site.
* Commerce GDPR

> Adds data anonimization features so the data will still be available for statistical and history purposes but will not allow to identify a user and the store will comply with the GDPR directive.
* Mask User Data

> ... mask all the current data in your database related to the users.
>
> ... could be really useful when considering the new GDPR legislation, as all the user data could easily be masked in development/local copies.
* Cookiebot - Cookie consent, Cookie monitoring and Cookie control

Drupal integration for the third party Cookiebot service.

> Cookiebot helps make your use of cookies and online tracking GDPR and ePR compliant. This module exposes this third party functionality to Drupal. It enables their Cookie banner/consent manager and allows you to place the automatically updated cookie declaration on a given node page or via a block. A free subscription is available for small sites and bigger sites can evaluate this functionality using their free trial. More info about Cookiebot.

Many sites now offer more sophisticated cookie controls to the visitor. More sophisticated than perhaps the compared with the eu\_cookie\_compliance module, whereby various cookie types/functions are displayed and can be managed by the visitor. This Drupal Contrib module cookiebot is a general solution used to provide this functionality in Drupal 7 and 8 sites. I would imagine that some Drupal site developers have made their own, but this module offers the advantage of a module whereby it can be reused in several sites, also not re-inventing the wheel.

However the downside is that it is subscription-based. A standalone non-subscription self-contained solution if existing, would be a compelling choice.

# Make no mistake

* Don't assume that if you've enabled the GDPR module, you're done ...
* GDPR will apply to any Drupal site that deals with users, site visitors, etc, who are from the EU (which public site does not do so?) ...

# Infrastructure and data maps

* Covering GDPR issues is not just about the application itself (the Drupal site) but also the platform that it runs on. As part of reaching the GDPR compliance process, a "Datamap" is drawn up to identify all the systems where the sensitive user data will flow. Also bear in mind what happens if the application is moved to another platform, would there be the possibility of residual data left on the former platform? For example, here is an answer on stackoverflow.com regarding configuring the file system path of Docker-based setups to support the approach to run a Docker-based web application inside an encrypted filesystem so that such residual data is never left behind.

# Read more
> 7 votes

# Answer
Drupal is not ready and even if the Drupal project on GDPR is finished it is not enough to comply with GDPR. Every Organization has to do their due dilligence on that. Time is running out.
> 3 votes

---
Tags: 8
---


# Question
Title: How do I programmatically remove a ckeditor button based on a user permission
Without creating a whole new text format and ckeditor profile, I want the "view source" button removed for certain users dynamically, so this needs to happen in a hook or something.

# Answer
First I want a new permission so I can say that only admins can view source when using ckeditor:

```
/**
 * Implements hook_permission().
 */
function MYMODULE_permission() {
  return array(
    'edit ckeditor source' => array(
      'title' => t('Edit ckeditor source'),
      'description' => t('Use the view source button on ckeditor.'),
    ),
  );
}

```

Then the tricky bit where we want to remove "Source" from the buttons:

```
/**
 * Implements hook_settings_alter().
 */
function MYMODULE_ckeditor_settings_alter(&$settings, $conf) {
  // Only allow the View source button if the user has the permission
  if (!user_access('edit ckeditor source')) {
    // Replace 'Source' including quotes and an optional comma
    $settings['toolbar'] = preg_replace("/'Source',?/", '', $settings['toolbar']);
  }
}

```

Note that if you `print_r($settings['toolbar'])` you may think you are looking at an array, but it is a string, hence the simple string handling preg\_replace above.
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to get current route in the midst of a Views AJAX request
I need to conditionally pass contextual filter values to a view based on the current route and am attempting to do so in hook\_views\_pre\_view. This is the result of using AJAX via views\_infinite\_scroll and losing the contextual filters that I initially pass in programmatically.

On the initial request, the following works great for getting the current route in hook\_views\_pre\_view:

```
$current_route_match = \Drupal::getContainer()->get('current_route_match');
$current_route_match->getRouteName();

```

However, when I hit the 'Load more' button supplied by views\_infinite\_scroll, the route name of the current route match is 'views.ajax'. While I understand that this is technically the request's route, I need to know the original route, or from where the request was made.

After digging around, I noticed that $\_SERVER\['HTTP\_REFERER'\] had the right path, but the documentation says:

> Not all user agents will set this, and some provide the ability to modify HTTP\_REFERER as a feature. In short, it cannot really be trusted.

# Answer
> 6 votes
```
use Symfony\Component\HttpFoundation\Request;

if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $fake_request = Request::create($previousUrl);
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      $route_name = $url_object->getRouteName();
      // Do something with $route_name;
    }
  }

```

---
Tags: 8, routes, ajax, views
---


# Question
Title: How to convert query string http://example.com/myview?page=1 to http://example.com/myview/page/1 in views?
I have to make url of views seo friendly. I need to convert query string http://example.com/myview?page=1 to http://example.com/myview/page/1.

Can you please suggest, how can i do this.

# Answer
Try using the module: Query parameter to url(https://www.drupal.org/project/query\_parameters\_to\_url), It will work for you.

Just specify the pattern {^myview} inside **/admin/config/search/query-parameters-to-url** after installing and activating the module.

Let me know if any helps needed.
> 1 votes

---
Tags: views, paging
---


title: Disable the cache for a specific view

text:
# Question
Title: Disable the cache for a specific view
I'm showing my users a random number (`{{ random() }}`) in a twig which is being rendered in a view. But when I refresh a page it just shows me the same number.

I tried several things but they all failed:

1. Disabled caching in `admin/config/development/performance`
2. Disabled cache in views advanced settings
3. tried to use cacheexclude module
4. I even disabled twig cache!

How can I completely disable cache for specefic twig or specefic view?

**Update:**

By the way in response header there is a header called `x-drupal-cache:HIT`. (It's `MISS` for the first time and then `HIT` after first load) Why?

**Update 2:** I uninstalled `Internal Page Cache` too. the `x-drupal-cache` is gone now but the page is still being cached! I literally disabled everything but still no luck to show a random number in twig in a view..

This is my response header if it helps:

```
cache-control:must-revalidate, no-cache, private
content-encoding:gzip
content-type:text/html; charset=UTF-8
date:Wed, 28 Feb 2018 14:26:47 GMT
expires:Sun, 19 Nov 1978 05:00:00 GMT
server:nginx
status:200
strict-transport-security:max-age=15768000
vary:Accept-Encoding
x-content-type-options:nosniff
x-drupal-dynamic-cache:UNCACHEABLE
x-frame-options:SAMEORIGIN
x-generator:Drupal 8 (https://www.drupal.org)
x-ua-compatible:IE=edge

```

**Solution:**

I uninstalled Internal Cache module and ALSI big pipe module too.

# Answer
> 4 votes
Unfortunately point 1 doesn't work for anonymous traffic.

You have to uninstall the Internal Page Cache module.

Or trigger

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

in a view hook.

When the View is placed on most or all pages then uninstall the Internal Page Cache, because the page cache kill switch also disables the dynamic page cache and you don't want to disable both caches, unless this is only for a few pages which don't have too much traffic.

Additionally you need point 2 (disabled cache in views advanced settings) in any case.

**Update:**

> By the way in response header there is a header called x-drupal-cache:HIT. (It's MISS for the first time and then HIT after first load) Why?

This header is generated by the Internal Page Cache, a HIT means it is served from this cache.

# Answer
> 1 votes
In Drupal 8 in order to disable cache for a specific view

```
your view > ADVANCED > Caching > None

```

For your case twig caching is probably at play but it better be left untouched.

```
services.yml > twig.config:  cache: false

```

You might want to consider creating a random number in view using https://www.drupal.org/project/views\_random\_seed

**NOTE:** If you Drupal cache is enabled in `admin/config/development/performance` than the `no cache` setting of any view will not be respected by default and all views will be cached instead. Installing cache\_control\_override will help resolve this and allow views configured with `no cache` to work as such. Read more on this problem in the module's page.

Above problem is resolved assuming there is no other caching mechanisms between the drupal site and the browser.

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