# Question
Title: Delay in code changes on custom pages in drupal 8 in a docker environment
There is a delay between saving code changes in a controller and being able to view them in the browser.

This is frustrating (to say the least) and makes it very hard to develop and debug module code.

I have tried setting up a development environment in docker and it's working quite well except for this nasty and unpredictable delay.

For a minimal example I tried installing the Hello World example module from the Prepare a Module skeleton guide.

My (minimal, but complete) setup is available here: https://github.com/glaux/drupal8docker.

### To replicate the delay

* Get the site up and running.
* Log in as `admin` with pass `123` on http://localhost:8090
* Navigate to /hello
* Change the markup in the file `/docker/project/modules/D8HWexample/src/Controller/HelloController.php`
* Refresh /hello - the changes will show up after between 5 and 300 seconds.

### What I've tried

I've tried disabling all the caches by following the official guides. When making css changes to a custom theme (not included in the minimal repo above) the code changes are visible immediately, so this is not a cache problem I believe.

This is also emphasized by the fact that rebuilding the cache via the interface, drush and/or drupal console seems to have no effect on this delay.

In a similar manner I've tried disabling the browser cache (by opening the dev console on chrome). This have no effect either, nor have clearing the browser cache manually.

How can I get rid of this delay, what am I doing wrong here?

### Edit

I think Clive could be right that this is possibly on the file system level. Here is an excerpt from the docker-compose file:

```
volumes:
  - ./docker/project/modules:/var/www/html/modules
  - ./docker/project/themes:/var/www/html/themes
  - ./docker/project/libraries:/var/www/html/libraries
  - ./docker/project/profiles:/var/www/html/profiles
  - ./docker/project/sites:/var/www/html/sites
  # Add anonymous volumes to exclude cache files explicitly
  - /var/www/html/sites/default/files/js
  - /var/www/html/sites/default/files/css
  - /var/www/html/sites/default/files/php

```

The files are added as explicit volumes, and the changes I make to `HelloController.php` are reflected in the image. I'm running this on Windows 10. Could this be the culprit, and how can I test this?

# Answer
> 5 votes
Your image is based on drupal:8.4.3-apache, which sets an opcache revalidate frequency of 60 seconds:

```
# set recommended PHP.ini settings
# see https://secure.php.net/manual/en/opcache.installation.php
RUN { \
        echo 'opcache.memory_consumption=128'; \
        echo 'opcache.interned_strings_buffer=8'; \
        echo 'opcache.max_accelerated_files=4000'; \
        echo 'opcache.revalidate_freq=60'; \
        echo 'opcache.fast_shutdown=1'; \
        echo 'opcache.enable_cli=1'; \
    } > /usr/local/etc/php/conf.d/opcache-recommended.ini

```

This means that if you access the same file within 60 seconds, it will be served from RAM instead.

---
Tags: 8
---


# Question
Title: Body class padding top, where is it coming from
I'm using Drupal 8.4.2 lightning-8.x-2.23 and Boostrap subtheme, Admin Toolbar. The body class has an injected class of padding-top: 40.4px; for publisher user and padding-top: 79.4px; for admins. I want to make it the same padding. Does anybody know where this style is coming from? I dont see it in any style sheet. In Drupal 7 the admin toolbar had a settings page that allowed for padding top so that it pushes the body below the toolbar.

Logged in as admin body class

```
<body class="toolbar-tray-open toolbar-horizontal toolbar-fixed user-logged-
in path-workbench has-glyphicons" style="padding-top: 79.4px;">

```

Logged in as publisher body class

```
<body class="toolbar-tray-open toolbar-horizontal toolbar-fixed user-logged-
in path-workbench has-glyphicons" style="padding-top: 40.4px;">

```

# Answer
It is being done by the core toolbar module. See `updateToolbarHeight` in `core/modules/toolbar/js/views/ToolbarVisualView.js`.

```
updateToolbarHeight: function updateToolbarHeight() {
  var toolbarTabOuterHeight = $('#toolbar-bar').find('.toolbar-tab').outerHeight() || 0;
  var toolbarTrayHorizontalOuterHeight = $('.is-active.toolbar-tray-horizontal').outerHeight() || 0;
  this.model.set('height', toolbarTabOuterHeight + toolbarTrayHorizontalOuterHeight);

  $('body').css({
    'padding-top': this.model.get('height')
  });

  this.triggerDisplace();
},

```
> 2 votes

---
Tags: 8
---


title: jQuery ui options not working

text:
# Question
Title: jQuery ui options not working
hope someone can help, I have a jQuery ui accordion working OK, but I cannot get any options I set to work. I'm not using modules for this, adding jQuery UI in my library, and the accordion itself works so I know all scripts are loading OK. My library file has:

```
ui-accordion:
  version: 1.x
  js:
    js/site/min/jqui-accordion-min.js: {}
  dependencies:
    - core/drupal
    - core/drupalSettings
    - core/jquery
    - core/jquery.ui.accordion

```

The library is then attached in a template file. My `jqui-accordion-min.js` has:

```
(function ($, Drupal) {
  Drupal.behaviors.basic = {
    attach: function (context, settings) {
        $("#accordion" ).accordion({ heightStyle: "content" });
    }
  };
}(jQuery, Drupal));

```

I've tried other options too, including `autoHeight: "false"`.

Is there something wrong with my jQuery, or do I need to load something else?

# Answer
> 0 votes
OK found the answer here \- I only had part of the option set correctly; here's the full jQuery:

```
(function ($, Drupal) {
  Drupal.behaviors.basic = {
    attach: function (context, settings) {
        $("#accordion" ).accordion({
            heightStyle: "content"
        });

        // Getter
        var heightStyle = $( "#accordion" ).accordion( "option", "heightStyle" );

        // Setter
        $( "#accordion" ).accordion( "option", "heightStyle", "content" );
    }
  };
}(jQuery, Drupal));

```

My bad for skim-reading the API, I saw 'Initialize the accordion' then 'Or set...' (and so ignored the next bit) instead of 'Get or Set'. Wasn't clear if the 'or' means you could use the 'getter' or the 'setter' instead. But I used both as written and it works now. :)

---
Tags: javascript
---


# Question
Title: How to show a user's age at the time of creating a node in a View?
My users have a *Date of birth* field (I am using the Date module). Every node page contains a View with some information about the node. I would like to add the author's age at the time of publication to it. How can I do that, assuming that *Date of birth* is available as a Views field?

I first tried to use Time Ago, but unfortunately it is not possible to select a time range. Next, I computed the difference between the time of publication and the date of birth in Unix seconds with a mathematical expression, but I am not sure how to convert this value to a year.

# Answer
Okay, this was actually really simple: divide the difference in Unix seconds between the day of publication and the day of birth by the number of seconds in a year (31536000 is used in the Time Ago API), and floor the result. The mathematical expression in the Views field thus becomes

```
([created] - [field_date_of_birth]) / 31536000

```

where rounding is enabled. Mind that both date fields use the custom format `U`.

One more caveat: the HTML should be removed from the Date field *Date of birth*. Otherwise, its value will be considered as 0 and the result will be wrong.
> 0 votes

# Answer
it can be done by rules, here is a rule that calculate in DAYS the difference between two dates. my rules does the following, make necesary changes to fit your needs: First convert both dates to an integer value, then substract them (date1-date2= diff-value in seconds), for days value divide diff-value by 86400 (24\*60\*60), this new variable convert it to an integer, this last value is the diference in days between those 2 dates. react on after saving(updating) your node, store this value by rules in a node hidden field, last add this field to your view.

rule's code:

```
{ "rules_parcialidad_calculate_dias_de_retraso" : {
"LABEL" : "parcialidad calculate dias de retraso",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "calculate retraso pago" ],
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--parcialidad" : { "bundle" : "parcialidad" } },
"DO" : [
  { "data_convert" : {
      "USING" : {
        "type" : "integer",
        "value" : [ "node-unchanged:field-fecha-de-parcialidad" ]
      },
      "PROVIDE" : { "conversion_result" : { "fecha_parcialidad_converted" : "fecha_parcialidad_converted" } }
    }
  },
  { "data_convert" : {
      "USING" : { "type" : "integer", "value" : [ "node:field-fecha-de-pago" ] },
      "PROVIDE" : { "conversion_result" : { "fecha_pago_converted" : "fecha_pago_converted" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "fecha-pago-converted" ],
        "op" : "-",
        "input_2" : [ "fecha-parcialidad-converted" ]
      },
      "PROVIDE" : { "result" : { "diferencia_en_segundos" : "direfencia_en_segundos" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "diferencia-en-segundos" ],
        "op" : "\/",
        "input_2" : "86400"
      },
      "PROVIDE" : { "result" : { "diferencia_en_dias" : "diferencia_en_dias" } }
    }
  },
  { "data_convert" : {
      "USING" : { "type" : "integer", "value" : [ "diferencia-en-dias" ] },
      "PROVIDE" : { "conversion_result" : { "retraso_dias_round" : "retraso_dias_round" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-parcialidades-dias-retraso" ],
      "value" : [ "retraso-dias-round" ]
    }
  }
]

```

} }
> 2 votes

---
Tags: views, datetime
---


title: How to change pictures position?

text:
# Question
Title: How to change pictures position?
I'm doing a website about tips and tricks to save money. Everything is working fine, except the visual identity, which sucks a bit.

I've tried to change the views to give my articles a good looking, but it's still very ugly, as you can see in the homepage for example : http://etu15.hes.planethoster.org/d8/

I'd like to find a wysiwyg editor which allow me to change the position and the size of my picture in my articles (or any modules which can do that). I'm currently using CKeditor, but I can't make a lot of modifications.

Thanks !

P.S. : printscreen of the "manage fields", "manage display" and the view

# Answer
> 0 votes
You could build a view that displays "Content" instead of "Fields" form the "Show" setting.

Through that, you can set the view to utilize either the default display mode for the node, the teaser mode or another custom display mode.. Using the display mode approach, your view will render each node, respecting your WYSIWYG content and (left/center/right) aligned inline images (assuming you haven't added custom css to automatically center the images at all times).

Alternatively, you can add css to alternate the images (left and right) aligned with the content by using the `.views-row:nth-child() .views-field-field-image` identifier, specifying any custom alternating sequence in the nth-child. If you simply want to alternate every other row, you can enable the **"Add striping"** option in the **"Unformatted List \> Settings"** of the view.

---
Tags: views, theming, media
---


# Question
Title: How to index Drupal Commerce 2 products for the search?
The products in Drupal Commerce 2 could not be found through Drupal's default search form.

Modules like Commerce Search are available only for Drupal 7.

How can I index product titles or SKUs and add them to the search in Drupal 8?

Thanks!

# Answer
> 1 votes
The core search will only ever search node's and users. If you want to search other entity types, like products, use Search API.

Just install the module, create a server (you can use the search api db submodule if you just want to use your sql database) and create your index. You will have the option of selecting which entity types get added to the index, you probably want nodes and products. Then add which ever fields that you want to be searchable.

See the official documentation for screenshots and more info on how to take it further (like adding facets).

---
Tags: 8, commerce, search
---


# Question
Title: Entity field value inherited from another entity programmatically?
I'd like to setup two content types in a parent -\> child relationship.

Node A of content type "parent" has custom field:

1. (text) Description

Node B of content type "child" has custom fields:

1. (text) Description dynamically inherited (referenced) from parent node.
2. (reference) to parent node

When the description of Node A changes, Node B automatically reflects this change.

I'd like to achieve this entirely on the backend, no UI or forms needed.

I will be creating the child nodes programmatically.

Topics I've found have danced around what I'm trying to do but lack the details I need to execute it. inheriting fields from a base content type

I have experience with Drupal 6 & 7 but am new to Drupal 8's entity apis.

A detailed explanation or example of how to achieve this would be greatly appreciated.

Thanks

**One possible solution:**

Store the parent node's updated date in the child node. Upon loading the child node, lookup the parent node's updated date, if it differs, copy the parent's field value to the child.

The parent node will not be updated frequently.

# Answer
The way I would tackle this is to create a new field type called “parent\_value”.Design it in such a way that it doesn’t actually store any data in the database but instead uses the existing object’s entity reference value to look up the value from the parent. This way you don’t have to rely on any sort of Dripal trigger to alter the value in the child, which will ensure that if values are updated programically, they will still match.

There is also the added advantage that creating a custom field will teach you everything you need to know about Drupal 8 plug-ins.
> 0 votes

---
Tags: 8, nodes
---


title: Create series of Events

text:
# Question
Title: Create series of Events
I've got the following task: i have a site which should be used as a kind of team calendar. there are lots of people in different roles (moderator, member) and moderators can create events (in my case ordinary nodes with time field) and members can now leave comments. there is not much more functionallity behind it, so no subscription, ... for events.

the problem i'm facing right now is the creation of events. normal events which occur once in a time are no problem, but there are much events that happen in a periodic time interval, e.g. every week.

so i need a possibility to create such a series but have them all as seperate nodes, to be able to edit individual dates. think about this scenario: the regular meeting x is scheduled every sunday from 10:00 to 12:00, but somehow it need to be changed in week 23 from 11:00 to 13:00.

is there a module for that?

# Answer
> 1 votes
Basically you need recurring meetings like in outlook.

I think you will have to create a rule based on flags. The flag could be something like daily, weekly, bi-weekly, monthly or yearly. Once an organiser selects the flag, rule should create nodes with meeting start time in future according to which flag was set.

Also give user an option to select # of events or end duration and you can put this check in your Rule as well to limit the events it creates.

# Answer
> 0 votes
The Date Repeat Instance module will allow you to break out repeating events into separate nodes when you need it. Basically, you would just enable the Date Repeat Module and on your content type containing the date field, indicate on the date field configuration page, click to 'allow repeating dates'.

A Repeat Tab will appear on your node edit page where you can edit the individual repeating date instances on the node.

---
Tags: 7, nodes
---


# Question
Title: Programmatically loading Custom block in page/node preprocessor
I've followed some previous solutions on DA to programmatically load a Custom block in my page preprocessor hook but nothing I try seems to be working.

Currently, my custom block is within *Structure \> Block Layout \> Custom block* Library under the name 'SGT Pricing Header' (Machine name: `sgt_pricing_header`, ID 12).

I have attempted loading it in the page preprocessor as well as the node preprocessor hooks.

Currently I have:

```
function THEME_preprocess_node(&$variables) {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(12);// BLOCK_ID
    $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'sgt_pricing_header');
    $variables['block_pricing_header'] = $block_view;
}

```

I have also used 'sgt\_pricing\_header' in place of the ID 2 with no success.

In the TWIG template, which is a paragraph template by the way, if that is relevant, I am simply trying to display the block with

```
{{ block_pricing_header }}

```

I referenced Programatically render a block in a twig template when trying to get this to work.

I also tried using Twig Tweak to display the block, without success.

```
{{ drupal_block('sgt_pricing_header') }}

```

Simply does nothing.

PHP Version: 5.6.32-1+ubuntu17.10.1+deb.sury.org+1 Drupal version: Lightning (lightning-8.x-2.17)

Not entirely certain what to try next other than simply hard code the block content into the template which I would prefer to avoid.

# Answer
I think the problem here is that Drupal 8 has both block definitions (a.k.a. plugins) and block instances. Both of which tend to be called blocks. What is listed in the custom block library is a block definition. This is like what is done when a block is created with code. It define the block but not the configuration.

An instance is the configuration data for a block. It has the settings for a specific block. E.g., title override, display title, region, and the like.

So, you are trying to render the block definition with code that requires an instance block.

How do you get an instance of a block to render? The simplest way is to create a hidden region in your theme by adding a region line in the info file. Something like "Hidden Blocks".

Add your custom (or code based) blocks to this region in the block placement screen. I also tend to set the rules for where this can be displayed just to help keep these from being generated when not needed.

Once you do this, you should be able to render using the block id from the placement screen. Note this can be different from the plug-in id on the custom block page if you have placed it more than one.
> 1 votes

# Answer
Rendering custom blocks with Twig tweak module can be done as follows (assuming the ID of your block is 12):

```
{{ drupal_entity('block_content', 12) }}

```
> 2 votes

# Answer
Try this code by including `EntityInterface`:

```
// Block
use Drupal\Core\Entity\EntityInterface;
// the last part of the parameter is the block id
$block = \Drupal\block\Entity\Block::load('yourblockid');
$block_content = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
\Drupal::service('renderer')->renderRoot($block_content);

```
> 0 votes

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


# Question
Title: Passing multivaluearray from php to javascript after ajax call
The passing of the array works only one time. After an ajax call the new array is not passed to drupalSetting only the 1st array will displayed multiple times in the console. I tried it with a static test array, with a dynamic array, with json\_encode() and such other things.

My PHP script:

```
$form['#attached']['drupalSettings']['variable'] = $vars;

```

devel:

```
Array (
    [0] => Array (
            [0] => val1
            [1] => val2
            [2] => val3
        )
    [1] => Array (
            [0] => val1
            [1] => val2
            [2] => val3
        )
....
)

```

My jQuery script:

```
(function($, Drupal, drupalSettings) {
    Drupal.behaviors.vShop = {
        attach: function (context, settings) {

            var loadVar = function(event, request, settings) {
                var varArr = drupalSettings.variable;
                console.log(varArr);
            };

            $( document ).ready(loadVar);
            $( document ).ajaxComplete(loadVar);
        }
    };
})(jQuery, Drupal, drupalSettings);

```

console:

```
Object { 0: {…}, 1: […] }

```

I think the main issue is that the drupalSettings.variable don't get the new array from the form after the ajax call.The attached values in the form are changed correctly.

# Answer
I searched on the wrong position, after i found: http://www.thecarneyeffect.co.uk/drupal-8-ajax I got the solution here https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21SettingsCommand.php/class/SettingsCommand/8.2.x

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\SettingsCommand;

function ajaxCallback(array &$form, FormStateInterface $form_state) {

    $form_state->setRebuild();

    $myValue = $form_state->getValue('myValue');

    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new SettingsCommand([
       'variable' => $myValue,
    ], TRUE));

  return $ajax_response;
}

```
> 1 votes

---
Tags: 8, forms, javascript
---


title: Loose frontpage content

text:
# Question
Title: Loose frontpage content
I've just tried to change my frontpage view settings (display : fields -\> content). After that, my frontpage is empty, despite my settings :

The checkbox "promoted to frontpage" is marked for all my articles. I don't understand. Could you help me ? Thanks !

# Answer
> 1 votes
Drupal Views can be used to setup a dynamic page, a block to insert on another drupal generated page, custom backend administration pages, and much more. One "view" can have multiple display modes/formats.

* Clicking the ADD button (denoted by #1 in the attached screenshot) will list possible types of views you can add to an existing view (it typically keeps settings across display modes consistent, unless you choose "this display only" in top left of popup dialogs while editing various settings).
* The top of the middle section (denoted by #2 in the attached screenshot) will indicate specific settings for that particular view display mode.

Based on the screenshot you've provided, it looks as if you've setup this view (as a page); you need to assign a custom route/path for the page such as /custom-homepage. Then, in Configuration \> System \> Site Information, set the path to the front page to be /custom-homepage.

However, if you are simply trying to add a section to the existing homepage, you want to create a block with views, not a page. Refer to https://www.drupal.org/docs/8/core/modules/views/create-a-simple-block-view

It guides you through setting up a block in views and placing it on a page.

---
Tags: views
---


title: Implement hook_theme in custom module

text:
# Question
Title: Implement hook_theme in custom module
I am developing a custom module and I need to implement a theme. The result of my code below is that the code inside the block does not print because Drupal can't find the theme. I'm using hook\_theme() and I'm not sure what I am missing.

**Directory structure**

**jsblock.module code**

```
/**
 * Implements hook_theme().
 */

function jsblock_theme($existing, $type, $theme, $path){
  return array(
      'jsblock_custom_theme' => array(
          'variables' => array('content' => NULL),
          'template' => 'panels_pane__block__jsblock_jsblock',
          'path' => drupal_get_path('module', 'jsblock') .'panels_pane__block__jsblock_jsblock',
      )
  );
}

```

I've been able to print the block by dropping the the file in the theme templates folder, but not when it is inside the module directory. Can someone please tell me what is wrong with my code?

# Answer
> 1 votes
From the naming of your module and template file, I suppose you want to add a template for a custom block returned by your module.

The reason, that your template is found by adding it to the theme is not that you implemented hook\_theme() in your custom module, but the way you named the template. It is found by the theme registry's template suggestions used for the block within your panels pane.

If you want your own theme hook `jsblock_custom_theme` to be applied to the block, you will have to add the theme hook to your block output by using the theme() function. An abstract example:

```
/**
 * Implements hook_block_view().
 */
function jsblock_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'jsblock_jsblock':
      $variables = array();

      // Prepare your block variables here.

      $block['content'] = theme('jsblock_custom_theme', $variables);
      break;
  }

  return $block;
}

```

Some further suggested checks/improvements:

* Check your template path: Keep in mind that `drupal_get_path` returns a path without trailing slashes. You will have to add a `/` to your path.
* Place your template in a `theme` subfolder to keeping a cleaner module structure.
* Don't name the template like the natively used template suggestions to avoid collisions while the theme tries overriding templates.

---
Tags: 7, theming
---


# Question
Title: How can I find out a list of available $string values for user_access($string) function?
> user\_access($string, $account = NULL)
>
> $string: The permission, such as "administer nodes", being checked for.

How can I find out a list of available $string values for `user_access()` function?

# Answer
As long as every module can define their own permissions, there is not a "strict" list of those string. You will need to "construct" it if you really need to have such a list programmatically.

You can run this script in a /devel/php page. (Of course, you need the Devel module.)

```
// Render role/permission overview:
$options = array();
foreach (module_list(FALSE, FALSE, TRUE) as $module) {
  print_r($module);
  // Drupal 6
  // if ($permissions = module_invoke($module, 'perm')) {
  //  print_r($permissions);
  // }

  // Drupal 7
  if ($permissions = module_invoke($module, 'permission')) {
    print_r($permissions);
  }
}

```
> 12 votes

# Answer
As @Berdir said, the easiest way to see which permissions are available is to go to the permissions admin/people/permissions in Drupal 7.

The problem I kept running into is that I could never figure out what string I needed to supply as an 'access argument' to actually make use of the permission. Well, here is how you find the string name for the permissions you want to use (This example uses Google Chrome.)

Step one. Go to admin/people/permissions find the permission you would like to use and right click on a check box to the right of the permission you would like to use. Select 'Inspect Element' or just go look at the source.

Next look for the value of the check box and note the value. (In this case the string is 'create coupon content')

This is the string you need to supply as an access argument in hook\_menu()

Example Code: (non-relevant items removed, don't forget title, callback, etc. in hook\_menu())

```
function fsrsys_menu() {
    $items = array();
    $items['my-custom-url'] = array(
        'access callback' => 'user_access',
        'access arguments' => array('create coupon content'),
    );
    return $items;
}

```
> 27 votes

# Answer
Here's a D7 version of Haza's answer, modified to use DSM instead of print\_r and to leave out modules that don't implement hook\_permission:

```
// Render permission overview:
$options = array();
foreach (module_list(FALSE, FALSE, TRUE) as $module) {
  if ($permissions = module_invoke($module, 'permission')) {
    // List only the modules that have permissions.
    dsm($module);
    dsm($permissions);
  }
}

```
> 9 votes

# Answer
You can use `user_permission_get_modules()` function, which returns an array of all defined permissions and their modules.

> Determine the modules that permissions belong to.
>
> ### Return value
>
> An associative array in the format $permission =\> $module.
> 6 votes

# Answer
The easiest way is to check the permission page (D7: admin/people/permissions, D6: admin/user/permissions). Note that you directly use the displayed string in Drupal 6, for 7 you need to have a look at the checkbox name/value. This is because permissions now have a translated title and description in Drupal 7.

So if you want the name for the permission "View published content" in Drupal 7, the value is "access content" which is your permission name.

If you know which module the permission is coming from, you can also check the corresponding hook\_perm() (D6) / hook\_pemission() (D7) implementation of that module.

In many cases, you want to define your own pemissions and use these, you can do that with the above hooks.
> 4 votes

# Answer
**Using the Devel Module**

* After installing and enabling the Devel module, navigate to `admin/config/development/devel` . There is a setting titled, "Display machine names of permissions and modules". Be sure that is checked.
* Now on the permissions page at `people/permissions`, hover over the name of the permission you are questioning. It may delay a second or two, but then the string value will show.
> 4 votes

# Answer
Here is a simple form alter that will add the permission key to the name on the permissions page. That should make it easier to look it up. You will need to add it to a custom module and replace "mymodule" with the name of that module.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_admin_permissions_alter(&$form, $form_state) {
  foreach ($form['permission'] as $key => &$item) {
    if (isset($item['#type']) && $item['#type'] == 'item') {
      $item['#markup'] .= ' (' . $key . ')';
    }
  }
}

```
> 1 votes

# Answer
I created this JavaScript snippet that helps me with this. I tested it in Drupal 7 only on the Shiny theme.

It basically outputs the machine name, taken from the first checkbox on that name, on to the first cell, under the label. The script relies on jQuery, which shouldn't be a problem on Drupal 7.

I typically paste it on the Developer Tools console and run it from there. I might create a bookmarklet for it in future.

```
// Go through each of the rows on the permissin table
rows = jQuery('#permissions tr');
rows.each(function() {
    // Get the first checkbox in the row.
    checkbox = jQuery('.checkbox .form-checkbox', this).first();
    // Get the first cell, containing the permission label.
    nameCell = jQuery('td:first-child', this);
    // In case this is not a permission row
    if(checkbox.length == 0) {
        return;
    }

    // Embed the permission maching name on permission label cell.
    nameCell.append("<div><code>" + checkbox.val() + "</code></div>");
});

```
> 1 votes

# Answer
```
db_query("SELECT DISTINCT {permission} FROM role_permission");

```
> 1 votes

# Answer
This is a simple module to make it easy: Access Arguments List

Regards
> 1 votes

# Answer
just drop in some module, you will see machine permissions at **/admin/people/permissions**

```
function YOURMODULE_form_user_admin_permissions_alter(&$form, &$form_state)
{
    $perms = &$form['permission'];

    $group_counter = 0;
    foreach ($perms as $k => &$v) {
        if ($k == $group_counter) { // skip fieldsets
            $group_counter++;
            continue;
        }

        $v['#markup'] .= ' (<span class="description" style="color:brown">'.$k.'</span>)';
    }
}

```

regards
> 0 votes

---
Tags: users
---


# Question
Title: Show parent items in hierarchical facet display
Taxonomy terms are configured as such:

```
Parent category 1
- Child category 1
- Child category 2

Parent category 2
- Child category 3
- Child category 4

```

"Empty facet behaviour" is set to "Do not display facet".

"Flatten hierarchy" is turned off.

"Treat parent items as individual facet items" is turned off.

But the facet display doesn't show the parent items. How do I configure it properly to do so?

# Answer
> 1 votes
Enable the "Index hierarchy" option under your index filters. After enabling you can choose the field(s) for which you want to index the hierarchy. Save. Re-index.

Parent terms will now show in your facet.

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


title: Creating Parent-Child Entities

text:
# Question
Title: Creating Parent-Child Entities
Is there a way to create parent-child entities in Drupal 8? I'm trying to create a structure where the top entity is for County, and the next level entity is for departments, and next level would be staff. There will be different counties so the departments created at the second level entity will only be tied to the county it's created for, and same goes for staff which will only be associated to the the 2nd level entity(departments). So Let's say department 1 on County 1 will have different staff from department 2 of the sane county 1.

Also how will the path for this be programmed? Where in Drupal or what files should be created or modified so that it will structured like myowndrupalxx.xxx\module\county\1\department\2\staff\1 to display staff information for staff #1 of department 2 of county 1?

Lastly, can the database tables have a key for each table, so let's say for the Staff table being at the 3 level, it will have 3 keys, County, Department, and Staff, vs. the County table will have 1 key County. This way it does follow the parent-child or relational database structure.

I am not a very skilled programmer in Drupal so please provide your explanations in lay man terms as much as possible.

# Answer
> 0 votes
What about using entity reference (included in D8) ? In your case, Each "department" has "county" and each "staff" has "department" : you may just add field to your department and staff content type (or taxonomy term depend on what you need to do with these).

Your may use pathauto to generate the URL you need for each content type :

> county/{county\_nid}
>
> county/{county\_nid}/department/{department\_nid}
>
> county/{county\_nid}/department/{department\_nid}/staff/{staff\_nid}

This can be easylly used with views / content type display mode and could imho fit all your needs.

---
Tags: 8, entities
---


# Question
Title: How to prevent CKEditor from removing content and tags written in source?
I'd like to be able to use things such as the  *tag for purposes of using font awesome icons, but CKEditor strips tags like this. If I place*  when in 'source' mode in ckeditor it gets removed as soon as I return to the standard mode. Is there a way to ensure that ckeditor allows these tags?

I saw that someone provided a solution here How to stop CKEditor 3.6.3.7474 from stripping \<script\> tags however in drupal 8 admin/config/content/ckeditor/edit/advanced does not exist.

I also saw the CKEditorPluginConfigurableInterface here https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginConfigurableInterface.php/interface/CKEditorPluginConfigurableInterface/8.2.x But I wasn't sure how to make use of that.

Is there a way to prevent CKEditor from removing content and tags written in 'source'?

# Answer
> 3 votes
As long as you are using Full HTML format it should work fine, e.g. this works no problem:

```
<a href="https://www.drupal.org/"><i class="fa fa-drupal"></i> Drupal.org</a>

```

This uses the zero-width non-joiner character instead of a non-breaking-space (makes little difference).

Note you won't see the icon in the CKEditor unless you load Font Awesome into the editorSettings contentsCss.

# Answer
> 3 votes
I had the same requirement, I followed this tutorial for that, How to Display Icons in Drupal using Icon API.

It needs two modules (1) Fontawesome and its dependencies Library module & Fontawesome Library. (2) Other module you need is Icon API which has sub-module Icon\_filter that will convert the icons in the images.

I am afraid that Icon API module will work for D8 or not, but it has D8 version but unstable as you can see on the module page.

I am using this way on D7 site.

**Update:** Filter setting

# Answer
> -1 votes
CKeditor has Content Filtering.

> Configure input data filtering in CKEditor. See this blog post for more information about ACF.

By the way, there are two solutions to avoid CKEditor filters content. An easy solution is to disable *Advanced Filtering Feature* on admin/config/content/ckeditor/edit/Full, but I don't recommend it in all cases. A better solution is settings your tags on admin/config/content/ckeditor/edit/Full (*Extra allowed content*).

>

---
Tags: 8, wysiwyg
---


title: CKEditor doesn't show JavaScript

text:
# Question
Title: CKEditor doesn't show JavaScript
I have Drupal 7 with CKEditor 3.6.2.7275 under Wysiwyg module. In configs of Wysiwyg I unchecked all the checkboxes for "Cleanup and output" category. Plus unchecked "Limit allowed HTML tags" for Full HTML text format.

When I try to edit the page, containing javascript inside, the \<script type="text/javascript"\> is inside the \<textarea\> for content editing. But it's not shown by CKEditor when I click source button. So it's undoubtedly CKEditor filtering.

What should I do to make CKEditor show javascript?

# Answer
> 4 votes
Drupal, like most Content Management Systems, has security systems in place to filter most javascript during submission so site members can’t do ugly things via scripting. In most cases, that’s a good thing. When you’re scratching your head trying to figure out a way around it, not so much.

You can hard-code a script into the template, if you need it on all the pages and it works. But just adding a a single, inline javascript into a Drupal node is not as easy as it seems.

***There may well be a prettier way to do this***, but here is a quick way out in case you need it:

First, put the script on your server, someplace it’s easy to find. I usually have a “scripts” folder in my sites/all folder.

Second, when do your post, set your input filter to PHP

Third, do a php include where you’d like to place the script. Something like this:

```
<?php include('sites/all/scripts/my_javascript.js'); ?>

```

And there you go. Inline javascript. I guess in the most common scenarios Drupal is used for, having `<script>` available without filtering would be very foolish security wise. Unfiltered js in a webform makes for a very insecure setup.

# Answer
> 1 votes
You can try appending:

```
config.extraAllowedContent = '*(*)';

```

in the Advanced Content Filter of CKEditor configuration. Be careful of security considerations.

# Answer
> 1 votes
On /admin/config/content/ckeditor/edit/Full open fieldset "Advanced content filter" and in textarea "Extra allowed content" add *script*

# Answer
> 0 votes
I had this problem before,but it's becuase of **CKeditor Content Filtering feature**

> Configure input data filtering in CKEditor. See this blog post for more information about ACF.

You can Handle it by two solutions, the first one is preventing CKEditor filter contents, it's an easy solution just Disabled "Advanced Filtering Feature" at `admin/config/content/ckeditor/edit/Full` but I don't recommend it in all cases.

Better solution is specified your tags at `admin/config/content/ckeditor/edit/Full`(if you use Full filter, you can change it based your format in used) \> **Extra allowed content** \> **Extra allowed content** enter you desire tags, in your case just enter **script** in the textarea. save the form and clear the cache.

---
Tags: 7, wysiwyg
---


# Question
Title: Get the user id for triggers when deleting a user
I have a script that sets up a specific url for a user when they register on a site,

There are no real issues at the moment, but I need to cater for those 'unlikely things to happen that happen 20 times when not prepared for'

Part of this is deleting certain user data when a user deleted (or requests to delete) their account.

I have set up a trigger which at the moment compares the list of uid's with those in the table I wish to delete but this is laborious because every time a user is deleted it has to loop through them all,

What I need is the uid of the user being deleted passed to the trigger so that the trigger than then go directly to the table and delete all user data belonging to uid x.

Is there a method or a way pf programmatically discovering at run time, which uid has been deleted (or being deleted).

The main problem is that the trigger is supposed to be fired after the user is deleted, but it seems to fire beforehand because when I run tests the user data is not removed until the next time, so this is what is happening:

```
User A is created
User A stores data
User A is deleted
- trigger fired, nothing happens
User B created
User B stores data
User B deleted
- trigger fired User A's data removed, User B's data remains until User C is deleted.

```

so comparing the user table id's with the id's of the table is useless because until after the user has been deleted their uid is still present in the users table.

Any help or pointers on how to get this uid would help me a GREAT deal :)

# Answer
> 2 votes
Sounds like a job for `hook_user_delete()`:

> Respond to user deletion.
>
> This hook is invoked from user\_delete\_multiple() before field\_attach\_delete() is called and before users are actually removed from the database.
>
> Modules should additionally implement hook\_user\_cancel() to process stored user data for other account cancellation methods.

e.g.

```
function hook_user_delete($account) {
  db_delete('mytable')->condition('uid', $account->uid)->execute();
}

```

# Answer
> 1 votes
Drupal 8 uses a different hook, but same syntax: `hook_ENTITY_TYPE_delete`.

> Respond to entity deletion of a particular type.
>
> This hook runs once the entity has been deleted from the storage.

Example:

```
function hook_ENTITY_TYPE_delete(Drupal\Core\Entity\EntityInterface $entity) {
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())
    ->execute();
}

```

---
Tags: actions
---


# Question
Title: Unsupported Operand Types theme_image_style
I'm using the following code to generate a thumbnail and it's URI. The URI works on its own (though it 404's) but whenever I add `theme_image_style` function it gives a fatal error: "Unsupported operand types in /theme.inc on line 1088"

```
$image_fields_src = array_column($image_fields, 'uri' );

// thumbnail uri
$thumburi = image_style_path('thumbnail', $image_fields_src[0]);
// generate thumbnail
$thumbnail = theme_image_style('thumbnail', $thumburi );

```

# Answer
According to theme\_image\_style page you tried wrong parameters,

as an example, your code should be something like the following snippet

```
$variables = array(
        'style_name' => 'thumbnail',
        'path' => $image_fields[LANGUAGE_NONE][0]['uri'],
        'width' => $image_fields[LANGUAGE_NONE][0]['width'],
        'height' => $image_fields[LANGUAGE_NONE][0]['height']
);
$thumbnail_image = theme_image_style($variables);

```

and in short

```
$thumbnail_image = theme('image_style', array(
        'style_name' => 'thumbnail',
        'path' => $image_fields[LANGUAGE_NONE][0]['uri'],
));

```
> 2 votes

---
Tags: 7, theming, media
---


# Question
Title: .htaccess https rewrite for single domain on multisite installation
I have a multisite installation with 2 sites running off separate domains. One of these sites needs to go through https:// while the the other can stick to http://. I also want all traffic to be rewritten to include the www. prefix.

So:

**example.com** rewritten to **https://www.example.com**

**example.co.uk** rewritten to **http://www.example.co.uk**

I'm trying to set my `.htaccess` file to handle this, and have tried with the syntax discussed here.

```
RewriteEngine on
<If "%{HTTP_HOST} == 'example.com'">
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>
<If "%{HTTP_HOST} == 'example.co.uk'">
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !http
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>

```

Needless to say, it's not working. Any input would be much appreciated!

# Answer
First I would try using the \[drupal\]/sites/sites.php file to do something like this:

```
$sites['example.co.uk'] = 'example.com';
$sites['example.com'] = 'example.com'; // for demonstration only

```

Then check out the htaccess module to force HTTPS. These are the options:
> 1 votes

# Answer
This is untested, but would the following work:

```
# Force HTTPS for example.com
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [NC,R=301,L]

# Force HTTP for example.co.uk
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} !^(www\.)?example\.co\.uk$ [NC]
RewriteRule ^(.*)$ http://www.example.co.uk/$1 [NC,R=301,L]

```
> 0 votes

# Answer
My suggestion is don't change anything except redirect `http://example.com` to `https://example.com` with following (

```
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

```

And if you like to redirect `https://example.co.uk` to http://example.co.uk`add the following line to your`.htaccess\` file ( but I don't think you need them)

```
RewriteCond %{HTTP_HOST} ^(www.)?example.co.uk$
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

```

Also, you can try to set them with Htaccess module

> Htaccess is a module which autogenerates a Drupal root htaccess file based on your settings.
>
> Drupal tries to provide a one size fits all htaccess for Apache webservers, but this goal is increasingly difficult. This module allows the webmaster to set specific options.
>
> Also, this module is dedicated to webmasters who don't want to manually modify htaccess every time during a version upgrade to use Drupal.

**Features:**
\- Set redirection to www or non www.
\- Use Followsymlinks or SymlinksIfOwnersMatch.
\- HTTPS support (redirect all request to HTTPS or support both protocols).
\- Protect core text files (like CHANGELOG.txt) from being viewed.
\- Ability to insert Boost htaccess settings
\- Add custom rules before Drupal rules.
\- Each htaccess is attached to a profile. This way, you can manage several
\- htaccess files and deploy the right one to your website.
\- Check if htaccess is altered and report in site status .
\- List item \- Drush integration.
> 0 votes

---
Tags: 7, multi-sites, .htaccess, ssl
---


# Question
Title: Language switch with query parameters using hook_language_switch_links_alter
I implemented `hook_language_switch_links_alter()` to preserve the query parameters while switching language.

```
function custom_job_search_query_language_switch_links_alter(&$links, $type, $path) {
  $params = drupal_get_query_parameters();
  $query = drupal_http_build_query($params);

  foreach ($links as &$link) {
    $link['query'] = $params;
    $link['href'] = $link['href'] . '?' . $query;
  }
}

```

The content of `$link` is the following.

```
Array(
  [ja] => Array(
    [href] => the-team/office-location?field_office_location_tid=All&field_job_category_tid=8168
    [title] => 日本語
    [language] => stdClass Object(
      [language] => ja
      [name] => Japanese
      [native] => 日本語
      [direction] => 0
      [enabled] => 1
      [plurals] => 0
      [prefix] => ja
      [weight] => 0
      [javascript] => ctbrOuYmjvFqegLO0dITk5UoiOqA6B0ydAybbphrNX0
    )
    [attributes] => Array(
      [class] => Array(
        [0] => language-link
      )
      [xml:lang] => ja
    )
    [query] => Array(
      [field_office_location_tid] => All
      [field_job_category_tid] => 8168
    )
  )
  [en-JPM] => Array(
    [href] => the-team/office-location?field_office_location_tid=All&field_job_category_tid=8168
    [title] => English
    [language] => stdClass Object(
      [language] => en-JPM
      [name] => JP-Specific
      [native] => English
      [direction] => 0
      [enabled] => 1
      [plurals] => 0
      [prefix] => en
      [weight] => 0
    )
    [attributes] => Array(
      [class] => Array(
        [0] => language-link
      )
      [xml:lang] => en-JPM
    )
    [query] => Array(
      [field_office_location_tid] => All
      [field_job_category_tid] => 8168
    )
  )
)

```

The query parameters are appended as `the-team/office-location%3Ffield_office_location_tid%3DAll%26field_job_category_tid%3D8168` and the URL is not correct.

How can I fix this issue?

# Answer
> 0 votes
I was able to fix the issue using the following code.

```
/**
* Implements hook_url_outbound_alter().
*/
function custom_url_outbound_alter(&$path, &$options, $original_path) {
  // Always make login/logout links go to the current page.
  switch ($path) {
    case 'user/logout':
    case 'user/login':
      $options['query']['destination'] = $_GET['q'];
      break;
  }
}

```

# Answer
> 0 votes
The code shown in the question is wrong because, in `hook_language_switch_links_alter()`, you should not append the query string to `$link['href']`, but set `$link['query']`.

```
function custom_job_search_query_language_switch_links_alter(&$links, $type, $path) {
  $query = drupal_get_query_parameters();

  foreach ($links as &$link) {
    $link['query'] = $query;
  }
}

```

---
Tags: i18n-l10n
---


# Question
Title: Configuring Solr/Sarnia Fulltext Search in views
I am pulling in content from a Solr server using the Sarnia module, and displaying it using views. If no keyword is entered into the views fulltext filter all results are displayed, but for some reason (which I need help figuring out) the views fulltext search is not producing any results when a keyword is entered into the search box. I've spent days searching the issue queues and google but haven't found a solution. Any help appreciated.

Example query:

```
Index: sarnia_sarnia_solr_search
Keys: 'scientific explorer'
Parsed keys: array (
    0 => 'scientific',
    1 => 'explorer',
    '#conjunction' => 'OR',
  )
Searched fields: content, spell, tm_title
Filters:
    ss_type = 'product'
Sorting: fs_field_percent_savings DESC
Options: array (
    'parse mode' => 'terms',
    'conjunction' => 'OR',
    'filter class' => 'SearchApiQueryFilter',
    'search id' => 'search_api_views:shop:page',
  )

```

Update: I now get some results by going to Views\>\>Query settings and changing the parse-mode from multiple terms to single term. The problem is that while a search for the full title "scientific explorer" yields results, a search for just "scientific" or "explorer" comes up empty.

# Answer
> 0 votes
After much digging around (and prayer) I was able to get the search working:

1. Make sure the content you wish to search by is indexed into Solr as type fulltext
2. Under /admin/config/search/search\_api/server//sarnia/schema/fulltext, make sure the content you wish to search by is of type tm\_\* (text).

Additionally, under Views\>\>Query settings you can set the parse-mode to single term to get more targeted search (Exact matches) or multiple terms to get results for each word of the search phrase (or even word stem if so configured in Solr)

---
Tags: search
---


title: get menulink id from enitity id?

text:
# Question
Title: get menulink id from enitity id?
Id like to be able to get a link content ID from an entity id. Not sure how to best do this? I'm trying to render a menu tree and use a specific taxonomy term as the menu tree root. I have access to the taxonomy entity but I don't know how to get the menu link content id i.e. 'menu\_link\_content:e4f3fc49-98d8-4f20-952f-8ed08f9cbfcb' =\> string(54) "menu\_link\_content:e4f3fc49-98d8-4f20-952f-8ed08f9cbfcb"

# Answer
I ended up rendering the entire menu tree, flattening it, then searching for the specific term ID. I'm sure there is a better way to do this.

```
if (empty($entity) || $entity->getEntityTypeId() == 'node' && $entity->getType() == 'product') {
  return;
}

$menu_name = 'main';
$menu_tree = \Drupal::menuTree();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Get menu link ID from field placement term.
if (sizeof($parameters->activeTrail) === 1 && $entity->getEntityTypeId() == 'node'  && !empty($entity->get('field_placement')->getValue())) {
  $term_id = $entity->get('field_placement')->getValue()[0]['target_id'];
  $parameters->onlyEnabledLinks();
  $flat_tree = $menu_tree->load($menu_name, $parameters);
  $flat_tree_manipulators = array(
    array('callable' => 'menu.default_tree_manipulators:flatten'),
  );
  $flat_tree = $menu_tree->transform($flat_tree, $flat_tree_manipulators);
  foreach ($flat_tree as $link) {
    $params = $link->link->getRouteParameters();
    if (!empty($params['taxonomy_term']) && $params['taxonomy_term'] == $term_id) {
      // Set matched route as id or parent.
      $currentLinkId = $link->hasChildren ? $link->link->getPluginId() : $link->link->getParent();
    }
  }
}

// Render menu tree from route.
$currentLinkId = isset($currentLinkId) ? $currentLinkId : reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);
$parameters->setMinDepth(1);
$parameters->onlyEnabledLinks();

$tree = $menu_tree->load($menu_name, $parameters);

```
> 0 votes

---
Tags: taxonomy-terms, navigation
---


title: Is there a way to manage stock levels?

text:
# Question
Title: Is there a way to manage stock levels?
Is there a way to manage stock levels with Drupal 8 Commerce?

I am not sure, but I believe Configure product attributes refers to product attributes, but it doesn't outline how to create stock management.

# Answer
> 1 votes
Yes, you are correct: The quantity available for a product is not considered a product attribute. A product attribute is, for example, color, size, weight. The quantity available in store is a value associated with the store, not an intrinsic property of the product.

Using only Drupal Commerce, you cannot manage stocks. There is a Commerce Stock module, but it just has only a development snapshot, for Drupal 8, which has been updated on November, 2017.

> ### The stock module does two main things
>
> * Maintain stock levels
> * Implement validation of stock to prevent users from ordering out of stock items
>
> ### The module does the following stock validation checks
>
> * Disable the add to cart button for out of stock products
> * Validates the add to cart quantity widget
> * Checks current Cart quantity when adding to your cart (so if stock is 10 and you got 6 in your cart you can only add 4)
> * Checks that all products and quantities in the shopping cart (/cart) are in stock
> * On Checkout if you attempt to enter, continue or complete with out of stock items you get redirected to the shopping cart

---
Tags: 8, commerce
---


# Question
Title: Dependency injection or \Drupal class methods?
Suppose I have an `ExampleService` class and I need a service (current\_user) to process my logic. So I have implemented my service like this.

### The way 1: DI standard Drupal

```
namespace Drupal\example_service;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxy;

class ExampleService implements ContainerInjectionInterface {
    /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
    protected $currentUser;

    public function __construct(AccountProxy $current_user) {
        $this->currentUser = $current_user;
    }

    public static function create(ContainerInterface $container) {
        return new static(
          $container->get('current_user')
        );
    }
}

```

### The way 2: Use global service

```
namespace Drupal\example_service;

class ExampleService {
    /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
    protected $currentUser;

    public function __construct(AccountProxy $current_user) {
        $this->currentUser = \Drupal::service('current_user');
    }
}

```

What is the difference between these methods?
What is better for performance?

# Answer
In Drupal 8, you should always use dependency injection within the context of classes.

However, if you create a custom service, you don't have to manually implement the ContainerInjectionInterface.

Instead, you define your service and the arguments for the constructor within your module's `example_service.services.yml` file (read more about `.services.yml` files here and about service injection here):

```
services:
  example_service.my_service:
    class: Drupal\example_service\ExampleService
    arguments: ['@current_user']

```

And your service class like this:

```
<?php

namespace Drupal\example_service;

use Drupal\Core\Session\AccountProxyInterface;

/**
 * My Example service.
 */
class ExampleService {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Construct an example service instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   Account proxy for the currently logged-in user.
   */
  public function __construct(AccountProxyInterface $current_user) {
    $this->currentUser = $current_user;
  }

}

```

Then you can create an instance of your custom service either via dependency injection as well (within the scope of another class), or within your module/theme files by using:

```
/* @var $my_service \Drupal\example_service\ExampleService */
$my_service = \Drupal::service('example_service.my_service');

```
> 8 votes

# Answer
Both the examples are wrong.

A service doesn't normally implement the `ContainerInjectionInterface` interface. It can be implemented by other classes, for example the `AggregatorController` class, which is not a service, since it is not listed in the aggregator.services.yml file of the Aggregator module.
As described in Services and Dependency Injection Container, what a module maintainer needs to do to define a new service is:

> * Choose a unique machine name for your service. Typically, this should start with your module name. Example: mymodule.myservice.
> * Create a PHP interface to define what your service does.
> * Create a default class implementing your interface that provides your service. If your class needs to use existing services (such as database access), be sure to make these services arguments to your class constructor, and save them in member variables. Also, if the needed services are provided by other modules and not Drupal Core, you'll want these modules to be dependencies of your module.
> * Add an entry to a modulename.services.yml file for the service. See Discovering existing services above, or existing \*.services.yml files in Core, for the syntax; it will start with your machine name, refer to your default class, and list the services that need to be passed into your constructor.

The second example is wrong because, instead of accessing `\Drupal::service('current_user')`, the constructor should just use the argument it gets.

Generally speaking, a service should never use the `\Drupal` class, but use the service container passed as argument to its `create()` (or `createInstance()`) method, or define a service as its arguments. In the latter case, the service will be passed as argument of its constructor.
The only case where a Drupal core service uses the `\Drupal` class in its constructor is when the arguments of a service has been changed. In that case, the service constructor uses code similar to the following one. (The code is the one used for `JsCollectionOptimizer::__construct()`.)

```
public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state, FileSystemInterface $file_system = NULL) {
  $this->grouper = $grouper;
  $this->optimizer = $optimizer;
  $this->dumper = $dumper;
  $this->state = $state;
  if (!$file_system) {
    @trigger_error('The file_system service must be passed to JsCollectionOptimizer::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/3006851.', E_USER_DEPRECATED);
    $file_system = \Drupal::service('file_system');
  }
  $this->fileSystem = $file_system;
}

```

As for the preferable/correct way to implement a service, which should not be confused with overriding the default class used for a service, there is just a way, which is the one I quoted.
> 5 votes

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: Drupal (or perhaps Apache) delivers wrong page
Made a website in drupal 8, and using webforms to save some webform submissions.

Made a custom url to show the submission data the way I want, for the sake of the example let's say: /submissiondata/\[submission\_id\]/\[submission\_token\]

anonymous users can see that page, and made sure that the page is not cached- by adding `options: no_cache: 'true'` in the routing.yml file and also when returning data, returning it like this:

```
return array('#markup' => $html, '#cache' => ['max-age' => 0,]);

```

Some extra info: When showing this info, the user has only 5 min. to see this page, because I compare CREATED to CURRENT\_TIME - and deliver some other HTML if more than 5 min. passed.

the apache server is setup with some reverse proxy...

**Here is the issue:** Sometimes, a person sees another persons submission data, just by surfing around the website. Like clicking the logo and going to the front page, they don't see the front page, but see submission data of another person!

How the heck is that possible?? It's happens very rarely, but it happens! It should not be possible! Is this a Drupal issue?

# Answer
> 1 votes
"The apache server is setup with some reverse proxy..." then you have to provide the correct response headers in an event subscribers, see How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)? how to set response headers.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

And uninstall the module *Internal Page Cache*, because this built in reverse proxy doesn't respect Cache-Control headers and you don't need it, because you already cache outside of Drupal, see PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF

---
Tags: 8, webforms, caching
---


# Question
Title: How do I include my library on the page?
I have an Angular app I want to use as a Drupal 8 theme but when I try to attach it with a YAML file, Drupal doesn't register that any JavaScript is being added to the theme.

ng.libraries.yml

```
base:
  version: 8.x
  css:
    css/styles.09e76a721be8ced0c439.bundle.css: {}
  js:
    js/inline.6375acbd4540ff168f58.bundle.js: {}
    js/polyfills.62cd0a749311c6ac36ca.bundle.js: {}
    js/vendor.d8949c111a4a3560f92d.bundle.js: {}
    js/vendor.d8949c111a4a3560f92d.bundle.js: {}

```

However, when I reference the script locations directly in my template, it works fine:

html.html.twig

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hand of Death</title>
    <link href="themes/ng/dist/styles.09e76a721be8ced0c439.bundle.css" rel="stylesheet" />
  </head>
  <body>
    <app-root></app-root>
    <script type="text/javascript" src="themes/ng/js/inline.cad96cf6be5b6cfb5176.bundle.js"></script>
    <script type="text/javascript" src="themes/ng/js/polyfills.62cd0a749311c6ac36ca.bundle.js"></script>
    <script type="text/javascript" src="themes/ng/js/vendor.d8949c111a4a3560f92d.bundle.js"></script>
    <script type="text/javascript" src="themes/ng/js/main.665799e3572bc9816ad1.bundle.js"></script>
  </body>
</html>

```

From what little I can make sense out of the docs, somewhere I'm going to have to call `Drupal.behaviors.myBehavior`, but that would not actually work in my situation.

Is there a way to get JavaScript to work without hardcoding it in the template?

**EDIT**: I've reverted this to the original so the corrections make sense to future users and went ahead and opened a new question with the most recent code.

# Answer
> 2 votes
So you defined a custom library that includes CSS and JavaScript. This is done by creating the `ng.libraries.yml` file and adding the `base` library definition.

Next, you need to tell Drupal to include this library and attach it to all the pages, if your `ng` theme is used for rendering the output. You can do so by adding a `libraries` section to your theme's `ng.info.yml` file:

```
libraries:
  - 'ng/base'

```

After clearing your caches, the library should be included.

Additionally, you may want to have a check for the syntax of the `.libraries.yml` file. CSS inclusion should follow the syntax:

```
css:
  theme:
    css/styles.09e76a721be8ced0c439.bundle.css: {}

```

Observe the `theme` part.

EDIT:

After you also added your `html.html.twig` template, another issue seems a missing js-bottom-placeholder tag. It will be replaced by any JavaScript that is not attached to the head region:

```
<js-bottom-placeholder token="{{ placeholder_token }}">

```

# Answer
> 0 votes
You did just one part of the job, another part is adding your libraries to some pages or to all pages.

in `YOUR_THEME.info.yml` file add your defined library

```
libraries:
  - 'ng/base'

```

Part of Drupal Documentation about Attaching Libraries to a theme :

> **Attaching libraries to page(s)**: Some libraries you load may not be needed on all pages. For faster performance don't load libraries where they are not being used. Below are examples of how to selectively load libraries.
>
> Attaching a library via a Twig template You can attach an asset library to a Twig template using the attach\_library() function in any \*.html.twig, file like so:
>
> {{ attach\_library('fluffiness/cuddly-slider') }} Some fluffy markup {{ message }} Attaching a library to all pages To attach a library to all the pages that use your theme, declare it in your theme's \*.info.yml file, under the libraries key:

```
 name: Example
 type: theme
 core: 8.x
 libraries:
   - fluffiness/cuddly-slider

```

List as many libraries as you want, all of them will be loaded on every page.

**After editing the \*.info.yml or the \*.libraries.yml file, remember to clear the cache so that the new information is loaded into Drupal.**

> Attaching a library to a subset of pages In some cases, you do not need your library to be active for all pages, but just a subset of pages. For example, you might need your library to be active only when a certain block is being shown, or when a certain node type is being displayed.
>
> A theme can make this happen by implementing a THEME\_preprocess\_HOOK() function in the .theme file, replacing "THEME" with the machine name of your theme and "HOOK" by the machine name of the theme hook.
>
> For instance, if you want to attach JavaScript to the maintenance page, the "HOOK" part is "maintenance\_page", and your function would look like this:
>
> function fluffiness\_preprocess\_maintenance\_page(&$variables) {
> $variables\['#attached'\]\['library'\]\[\] = 'fluffiness/cuddly-slider'; } You can do something similar for other theme hooks, and of course your function can have logic in it — for instance to detect which block is being preprocessed in the "block" hook, which node type for the "node" hook, etc.
>
> Important note! In this case, you need to specify the cacheability metadata that corresponds to your condition! The example above works unconditionally, so no cacheability metadata is necessary. The most common use case is likely where you attach some asset library based on the current route:
>
> ```
> function fluffiness_preprocess_page(&$variables) {
>   $variables['page']['#cache']['contexts'][] = 'route';
>   $route = "entity.node.preview";
>   if (\Drupal::routeMatch()->getRouteName() === $route) {
>     $variables['#attached']['library'][] = 'fluffiness/node-preview';
>   }
> }
>
> ```

# I strongly recommend take a look at Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

# Answer
> 0 votes
You forgot the bottom JS placeholder token in `html.html.twig`:

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    ...
    <js-placeholder token="{{ placeholder_token|raw }}">
    ...
  </head>
  <body>
    ...
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

```

Drupal has 2 different tokens for JS libraries: Usually it places all JS files at the end of the body, except you explicitly move them to the header in your libararies.yml.

---
Tags: theming, javascript
---


# Question
Title: Hook into other module's field formatter?
Am currently trying to implement a node referenced image field on my Drupal 7 site that will change it's 'view mode' depending on programmatical logic just before render. The field is currently being rendered on a number of content types via their display mode settings, each of which are using the field formatter 'Rendered node'.

### **first attempt**

My first idea was to implement the following, considering a hook is a hook is a hook:

```
function HOOK_field_formatter_view( $entity_type, $entity, $field ... ){
  switch ($display['type']) {
    case 'node_reference_node':
      /* Programatical logic here to modfy field render settings */
    break;
  }
}

```

*Obviously exchanging HOOK for my module's name.*

It didn't really matter if the above would fire before or after the original function `node_reference_field_formatter_view` in `node_reference.module` because I would either override it's output entirely or, hopefully, modify its values before rendering. The only problem is, the above hook seems to function only on a per module basis — i.e. it's not site-wide, so basically it doesn't fire for my module.

Now obviously I can write my own field formatter to output a rendered node. But it seems a bit of a waste considering there is already one that exists.

### **other approaches**

My other approaches have been to `HOOK_preprocess_node` and `HOOK_preprocess_field` but the former doesn't contain any `view_mode` information, and the latter contains at least 5 different complicated structures that all have references to a `view_mode` property at different levels — and it feels rather hacky to have to modify each of their values. Even when I've changed certain `view_mode` properties the resulting image doesn't change.

### **question**

Does anyone know of a clean way to step in before a field formatter renders (of a contrib module) and change it's settings on a per page request basis — i.e. by not having to change the actual content type's permanent view mode settings?

# Answer
> 12 votes
The question mentions that `hook_field_formatter_view()` is only called on the originating module, but you can take ownership of the field formatter via `hook_field_formatter_info_alter()`.

You should be able to set the `module` key of the formatter to MYMODULE like:

```
function MYMODULE_field_formatter_info_alter(&$info) {
  $info['some_field_formatter']['module'] = 'MYMODULE';
}

```

**Then** you can implement `MYMODULE_field_formatter_view()`, optionally feeding through the existing module which handled it to get an element to alter.

```
function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  // Your custom logic
  $element = OTHER_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display);
  // Any alterations
}

```

# Answer
> 2 votes
Ok so I realised why my changes to `#view_mode` in either `hook_preprocess_node` and `hook_preprocess_fields` weren't working. *(Thanks to Clive for pointing out that I had totally missed the presence of `#view_mode` in `hook_preprocess_node`)*.

My problem stemmed from the fact that `#view_mode` had already been processed and converted to the correct `#image_style` property — something which I had neglected to search for.

Even so, changing this value seems too heavily dependent on which hook you modified it in. I finally got some code working though, that actually changes the rendered image:

```
function HOOK_preprocess_field( &$vars ){
  $element     = &$vars['element'];
  $entity_type = !empty($element['#entity_type']) ? $element['#entity_type'] : 'unknown';
  $bundle      = !empty($element['#bundle'])      ? $element['#bundle']      : 'unknown';
  $view_mode   = !empty($element['#view_mode'])   ? $element['#view_mode']   : 'unknown';
  $field_name  = !empty($element['#field_name'])  ? $element['#field_name']  : 'unknown';
  switch ( "$entity_type:$view_mode:$bundle/$field_name" ) {
    case 'node:full:mlandingpage/field_lead_image':
      if ( !empty($vars['items']) &&
           ($subelement = &$vars['items'][0]) ) {
        if ( !empty($subelement['field_image']) &&
             ($subfield = &$subelement['field_image'][0]) ) {
          /// this needs to be set to the image_style value, not the view_mode value.
          $subfield['#image_style'] = 'grid-normal-4-cols';
        }
      }
    break;
  }
}

```

The above still doesn't feel very eloquent, but at least it works. I'll take Clive's word on the fact that such an \_alter method doesn't exist for field formatters — it's a shame, formatters are an extremely powerful feature of D7, it would be nice to have more augmenting ability.

Anyway, if any future people have any better ideas, answer away :)

# Answer
> 0 votes
The easiest approach will be using the Panelizer.

If don't use Panelizer but default Drupal view modes or Display Suite, try hook\_field\_display\_alter() or hook\_field\_display\_ENTITY\_TYPE\_alter().

You have entity, display context as well as all the formatter settings there. And you can easily change field render settings. You can even change field formatter to a different one.

The approach works perfect for me. The only disadvantage is that you might be confused with different settings in the the "Manage display" UI.

# Answer
> 0 votes
https://www.drupal.org/node/2130757 It gives a good example. hook\_field\_formatter\_third\_party\_settings\_form() is useful to alter the form of the existing field formatter.

But this doesn't work with field groups.

---
Tags: entities
---


# Question
Title: "The feed from New On Our Blog seems to be broken, due to an error 'Invalid document end' on line 128."
I run a Drupal 7 website and I have a separate WordPress blog. The blog generates a feed I display (RSS2 version) in a block on the Drupal website via the Aggregator module. The last feed shown on the Drupal website is from November 24, 2017. The newer 2 posts have not made it onto my Drupal website. However, when I check the feed itself, the posts are present in the feed.

The error message that Drupal shows is:

> The feed from New On Our Blog seems to be broken, due to an error "Invalid document end" on line 128.

I checked the feed; there is no mention of line 128 on feed validator. Another error shows up for line 187:

> line 187, column 0: url must be a full URL: \[redacted\]/wp-content/uploads/2017/10/adding\_texture.mp4

I don't understand why I am getting these error messages. The lines look okay to me.

* I installed updates
* I deleted my browser's cache (Firefox ESR)
* I deleted the Drupal cache
* I added a new test post to the blog, and confirmed it shows on the feed

# Answer
It turns out that a simple smiley `:)` wrought all the havoc. The smiley was situated in the first paragraph of a post and was therefore transferred via the feed to Aggregator.

Removing the smiley removed the errors and now the feed is showing correctly again.

I don't know what exactly is wrong with ':)', but somehow it messed things up. Explanations are welcome.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: How to display a Rules Link only if access to display the linked content was granted?
I'm using the **Drupal Commerce 7.x**, **Rules Link**, and **Content Access** modules.

In my site Classified ads can be created, and then people can use credits (via User points) to pay for unlocking "contact informations".

For example, when an advertiser creates an ad, 2 things happen:

* content (node) of type **"Classified ad"** is created, and
* it is cloned and converted in another content (node) of type **"Classified complete"**.

So there will be 2 different nodes: the first one is a "Classified ad" and the second one is a "Classified complete".

The **"Classified ad"** is the node which has limited information and the **"Classified complete"** is the node which has all information. They are all linked together with the "Rules link" module.

The "Classified ad" node is displayed for everyone and the "Classified complete" node linked to it can be accessed only if a user paid for it already.

More info about my current setup as described above is included also in my related question "How to access node properties of another node using the Rules Link module?".

Now I want to further refine the display of the link shown via "Rules Link": I want to display a **link rules** in **"Classified ad"** nodes only if all these conditions are satisfied:

* The current user is an authenticated user (done, as per my linked question).
* *The current user already bought the node "Classified complete" so the user has an access granted to that node (with the Content access module).*
* A page redirect to the node "Classified complete"(done, as per my linked question).

How to check if my *current logged in user* already has the **access granted** to a node **id** (the 2nd condition in the previous list)?

# Answer
From the (my) accepted answer to your related question (= How to access node properties of another node using the Rules Link module?), I do remember that apart from the Content Access module, you ALSO use the ACL module.

However, even though via the ACL module you do get some extra Rules Actions (such as `content_access_action_user_grant`), there doesn't seem to be (or at least I have not found it yet) a Rules Condition that you could use to check that "*the current user already bought the node*" (as in your question here).

Too bad, if *IT IS NOT* available, then just *MAKE IT* available. For that, you can use the Flag. If you then configure a (non-global) flag, you could use that flag like so:

* When configuring the flag, only allow it for bundle 'Classified Ad'. And make sure to only grant access to the flag to users with a role like "special role for Classified Ads" (name it what you want), to avoid the link to flag such nodes would be shown to unauthorized users (due to which they could flag the node just using the UI, which you do not want to happen).
* Around the time the user buys access to your 'Classified complete' node, perform an additional Rules Action to "flag the 'Classified Ad' node by the current user as bought", and with the machine name of the flag (say) 'node\_bought' (pick whatever fits).
* Within the Rules Link, use a condition like "Is the node flagged with the 'node\_bought' flag by the current user?".

Below is a (rather basic) Rules Component (= *condition set (AND) "Rules link: authenticated user Link contact infos condition"*) with machine name to match your existing Rules Link also, as in your linked question. And which you could use for this (change the machine name of the flag from 'node\_bought' to your flag's machine name, prior to importing this):

```
{ "rules_link_condition_access_to_contact_info_links" : {
    "LABEL" : "Rules link: authenticated user Link contact infos  condition",
    "PLUGIN" : "and",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "USES VARIABLES" : { "node" : { "type" : "node", "label" : "node" } },
    "AND" : [
      { "flag_flagged_node" : {
          "flag" : "node_bought",
          "node" : [ "node" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ]
  }
}

```

Something I'm unsure about right now (= homework for you to QA-test): as per that "special role for Classified Ads" (see before), the (extra) Rules Action to flag the node may fail (not authorized for current user). If that's the case, then just add these 2 extra Rules Actions as a work around for that:

* Grant access for current user to "special role for Classified Ads", right before the Rules Action to flag the node.
* Remove access for current user to "special role for Classified Ads", right after the Rules Action to flag the node.
> 1 votes

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


title: Dynamic select forms

text:
# Question
Title: Dynamic select forms
I have created a custom form in Drupal 8 where I want to select a vehicle make, populate the models under the vehicle make and avail the list for selection in another field. I am stuck at the Ajax callback I have googled but haven't found a solution. I need guidance on how to use Ajax to get the desired results. My code is the following.

```
$query = \Drupal::database()->select('vehicle_make', 'veh');
$query->fields('veh', ['make_id','make_name']);
$results = $query->execute();
$options_makes = array();

foreach ($results as $result) {
$options_makes[$result->make_id] = $result->make_name;
}

$form['vehicle_make'] = array(
  '#type' => 'select',
  '#title' => $this->t('Vehicle Make'),
  '#options' => $options_makes,
  '#default' => '--Select Make --',
  '#ajax' => array(
    'callback' => 'ajaxfunction',
    'wrapper' => 'vehicle-model',
    'effect' => 'slide',
    ),
);

$form['vehicle_model_container'] = array(
  '#type' => 'container',
  '#prefix' => '<div id="vehicle-model">',
  '#suffix' => '</div>',
);

if ($form_state->hasValue('vehicle_make')) {
  $vehicle_make = $form_state->getValue('vehicle_make');
  $subquery = \Drupal::database()->select('vehicle_model', 'md');
  $subquery->join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery->fields('md', ['model_id','model_name']);
  $subquery->condition('md.make_id', $vehicle_make);
  $results = $subquery->execute();
  $model_options = array();

  foreach ($results as $result) {
    $model_options[$result->model_id] = $result->model_name;
  }

  $form['vehicle_model_container']['model'] = array(
    '#type' => 'select',
    '#title' => t('Vehicle Model'),
    '#options' => $model_options,
  );

  function ajaxfunction(array $form, FormStateInterface $form_state) {
    return $form['vehicle_model_container'];
  }

```

# Answer
> 0 votes
You shouldn't return fetched array as result, in Drupal ajax the return value from the ajax function actually overwrites the wrapper, so you've got to set `$form['vehicle_model']['#options']` with fetched value and the return this piece of form (`$form['vehicle_model']`) as function return value. so the code will be something like this :

```
function _ajaxfunction(array $form, FormStateInterface $form_state) {
  $vehicle_make = $form_state->getValue('vehicle_make');
  $subquery = \Drupal::database()->select('vehicle_model', 'md');
  $subquery->join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery->fields('md', ['model_id','model_name']);
  $subquery->condition('md.make_id', $vehicle_make);
  $results = $subquery->execute(); $options_models = array();
  foreach ($results as $result) {
    $options_models[$result->model_id] = $result->model_name;
  }
  $form['vehicle_model']['#options'] = $options_models;
  return $form['vehicle_model'];
}

```

---
Tags: forms, ajax
---


# Question
Title: Why is Rules Link checking all Rules Links on every page load?
I am using the Rules Link module in a Drupal 7 site. The site contains a view that lists a number of entities, including the Rules link field. The Rules Link rule set is simple: when clicked, data of a field value is set. The rules link works fine, however ...

When I check the recent log messages (dblog) I see that every page load of that views page, Rules link repeats a check on every rules link available on the page. Such as this Rules link where

```
" Executing and Rules link: Bin condition.
0 ms Executing and Rules link: Bin condition.
0.098 ms AND evaluated to TRUE.
0.11 ms Finished executing of and Rules link: Bin condition.

```

I did not include a trigger for when a page is viewed, so I think this is strange. And even stranger, why is a rules condition check for every link listed in a view? I get long lists in my dblog showing repeating Rules Link condition checks.

# Answer
> 1 votes
What you have noticed (= repeat a check on every Rules Link available on the page), is simply how the Rules Link module works, especially if used in combination with the Views module, as in your question here.

As an example, refer to (my) question about "How to show authorized users a link for relevant Views results using the Rules Link module?". The accepted (my own) answer to that question includes an example of a Views result that looks like so:

```
User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

```

Actually the last column (with "Unlock user" for only the first 2 rows) is what got created via the Rules Link module. And to achieve this result, I used the "Configure Rules" tab to specify the relevant "Access Conditions". Don't be confused ... 'Access' here is not about permissions! Instead they are like an extra refinement of the permissions: they can be used to specify when to show the Rules Links, whereas this "when" is expressed using *Rules Conditions* (only).

I specified these Rules Conditions (which must both be satisfied), using the `Add condition` link (right above "Reactions"):

1. Data comparison, with:

* Data to compare: `[user:uid]`
    * Operator: `is greater than`
    * Data value: `0`
2. Data comparison, with:

* Data to compare: `[user:status]`
    * Data value: `Blocked`

The 1st condition will ensure the link is NOT shown for *Anonymous*. And the 2nd condition will ensure the link is only shown for users for which the value of the Active column is `No`.

These *Access Conditions of the Rules Link* are actually saved as a regular Rules Component (using a Component Plugin type of "Condition set (AND)" and with machine name `rules_link_condition_unblock_a_blocked_user`).

So with the above in mind, and after I enabled "Show debug information" (within Rules Settings), I got a Rules Evaluation log which looks like this:

```
" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.532 ms The condition data_is evaluated to TRUE [edit]
1.831 ms The condition data_is evaluated to TRUE [edit]
1.839 ms AND evaluated to TRUE.
1.86 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.251 ms The condition data_is evaluated to TRUE [edit]
0.368 ms The condition data_is evaluated to TRUE [edit]
0.376 ms AND evaluated to TRUE.
0.394 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.277 ms The condition data_is evaluated to TRUE [edit]
0.394 ms The condition data_is evaluated to FALSE [edit]
0.402 ms AND evaluated to FALSE.
0.419 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
...

" Executing and Rules link: Unblock a blocked user condition.
...

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.233 ms The condition data_is evaluated to FALSE [edit]
0.241 ms AND evaluated to FALSE.
0.258 ms Finished executing of and Rules link: Unblock a blocked user condition.

```

Some more details about the above logging data:

* I got exactly 6 groups of logging records (1 for each Views result) of Rules logging data (each of them starting with the line "`Executing and Rules link: Unblock a blocked user condition.`").
* Only for the first 2 groups it says "`AND evaluated to TRUE.`" (i.e. the 2 rows for which the Rules Link-link is to be shown), while for the remaining blocks, they all say "`AND evaluated to FALSE.`" (i.e. the rows for which the Rules Link is to be hidden).

*But*, for the Rules Link module to be able to correctly (yes or no) show such link for each Views result, it has to evaluate both Rules Conditions (those 2 data comparisons in my case, you were lucky ... you seem to only have 1 Rules Condition for each Views result ...). Or, to use your own words (as in your question): "***repeat a check on every Rules Link available on the page***".

Open (followup?) question: what happens if there are multiple pages of views results, i.e. when are those Rules Conditions evaluated for subsequent pages (when the page is to be actually shown, or at the very beginning when the very first page is shown)?

---
Tags: 7, rules
---


# Question
Title: How to fix google page speed insights issue?
I'm facing issues on my every drupal site when i test my website in Google page speed insight . I have configured Advagg module and followed but not succeed.Issues are below:

1. Eliminate render-blocking JavaScript and CSS in above-the-fold content.
2. Leverage browser caching.
3. Enable compression.

Sometimes (1) can be fixed by advagg setting but (2) and (3) need configuration in .htaccess. Can anybody provide me solution?

# Answer
> 1 votes
With AdvAgg enabled go to the status report page `admin/reports/status`. It should offer advice on how to fix gzip and browser caching for css/js aggregates. Also see the readme, under troubleshooting there are some tips for getting apache to do what you need it to.

If advagg doesn't report any issues then check and see what kinds of resources google is complaining about in terms of browser caching (.jpg) and compression (fonts). Also remember that if these are coming from an external domain (google analytics) there isn't a lot you can do as you don't control that server.

Edit: Guide here - https://groups.drupal.org/node/517292. It's the AdvAgg Readme file as well.

# Answer
> 0 votes
As you told you can Handle Aggregation of JS and CSS by AdvAgg but for *Enable compression* and *Leverage browser caching* Read this article about Leverage Browser Caching for Images, CSS and JS.

Add these lines to your `.htacess` file.

```
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

```

Also, you can try

```
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch>

```

---
Tags: caching, css-js-aggregation
---


# Question
Title: Term Reference field as checkboxes, not auto-complete?
I have a brand new Drupal 8 installation (my first D8 site). I've created a new content type with a Term Reference field.

When adding content, it appears that the only way to select a term is via type ahead, auto-complete. Instead, I need a simple list of terms with checkboxes.

I can't recall struggling with this in D7 before. Is there a module I should install... or setting that I should configure?

# Answer
> 4 votes
To change the tag selection to check boxes configure the widget in the tab *Manage form display*:

# Answer
> 0 votes
There is a D8 version of Term Reference Tree that works great for this. Especially if you have a hierarchical term layout.

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


# Question
Title: Pass a variable from a node to a block module that uses a custom template
I have a custom module "jsblock." When the page renders, the module should get the title of the page, pass it to drupal\_add\_js() and ultimately render an output in a block.

I tested the module with the template name suggested by the system. The output rendered in the block as expected. Now, I'm trying to add a custom template to the module but the variable appears to no longer be passed to the block.

**Directory structure**

I have been playing around with hook\_block\_view() and a helper function to handle the drupal\_add\_js() function, but I think I am not attaching it to the block correctly.

**jsblock.module file**

```
// Helper

function get_the_page_title() {
  if ($node = menu_get_object('node')) {
    $title = drupal_get_title();
    drupal_add_js(array('jsblock' => array('test' => $title)), 'setting');
  }
}

// Theme
function jsblock_theme($existing, $type, $theme, $path){
  return array(
      'jsblock_custom_theme' => array(
          'variables' => array('content' => NULL),
          'template' => 'jsblock_custom_theme',
          'path' => drupal_get_path('module', 'jsblock') .'/theme/',
      )
  );
}

// Print
function jsblock_block_view($delta = 'jsblock') {
  if($delta == 'jsblock')
    {
      $block = array();
      $block['content'] = get_the_page_title();
      $block['content']['#attached']['css'][] = drupal_get_path("module", "jsblock")."/css/styles.css";
      $block['content'] = theme('jsblock_custom_theme');
      return $block;
  }
}

```

I checked the console for Drupal.settings.jsblock.test and it is returning the expected value. I can see the block is printing based on an expected outline, but the data is not rendered.

How can I pass the JS variable from the page to the block that uses a custom template?

# Answer
When using a custom theme wrapper for your block output, you actually theme the content parts, before the block will be rendered using the actual block theme wrappers.

If you like to pass in variables to your custom template, you need to provide them via the second parameter of the theme() function:

```
/**
 * Implements hook_theme().
 */
function jsblock_theme($existing, $type, $theme, $path){
  return array(
    'jsblock_custom_theme' => array(
      'variables' => array('my_title' => NULL),
      'template' => 'jsblock_custom_theme',
      'path' => drupal_get_path('module', 'jsblock') .'/theme/',
    )
  );
}

/**
 * Implements hook_block_view().
 */
function jsblock_block_view($delta) {
  $block = array();

  if($delta == 'jsblock') {
    $variables = array();
    $variables['my_title'] = get_the_page_title();
    $block['content']['#markup'] = theme('jsblock_custom_theme', $variables);
    $block['content']['#attached']['css'][] = drupal_get_path('module', 'jsblock') . '/css/styles.css';
  }

  return $block;
}

```

Note the difference between the `$variables` and the `$block` array.

To also cover your second question (which surely should go into a separate question on Drupal Answers):

Keep in mind, that blocks are cached by default for performance reasons, until you clear the caches. So with your current implementation the block view will be generated only once and hence the JavaScript only attached to the first page you render after a cache clear.

Therefore you should attach your JS to the block output as you did with your CSS (attach it to the `content` part of the block output) and make sure to have a distinct cached version of the block for every page by using appropriate cache tags in your hook\_block\_info():

```
/**
 * Implements hook_block_info().
 */
function jsblock_block_info() {
  $blocks = array();

  $blocks['jsblock'] = array(
    'info' => t('My JS block'),
    // Use DRUPAL_NO_CACHE for no caching, or
    // DRUPAL_CACHE_PER_PAGE if you are fine with
    // cached versions per page.
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

```
> 1 votes

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


# Question
Title: Can Drupal site logout user when he change IP Address?
Can Drupal site logout user when he change IP Address or ask user to confirm password again?

I need to implement follow requirements:

* Log source IP address changes during application sessions.
* Notify the user of potentially suspicious activity.
* When IP address changed, ask user to confirm password again.

# Answer
I'm not aware of any contrib module providing all these features out-of-the-box.

If you are on Drupal 7, you might want to give the IP Address Manager module a try, which provides user-based IP address logging and can be extended programmatically with your own module.

For Drupal 8 you may have to create it from the scratch. Which shouldn't be too hard, if you have appropriate knowledge of Drupal 8 programming.

Btw., I also strongly suggest adding another feature to your requirements: Save the previous IP into the active session (cookie) and check, whether the user just switched the IP during the session (e.g. by means of VPNs), but is still using the same device/browser. - I always find it quite annoying and a bad user experience getting captchas/password dialogs when trying to access sites securely with switching IP addresses. (Which I need to when working from within China. ;)
> 2 votes

---
Tags: log-messages
---


# Question
Title: Can I use taxonomy field to display in URL using [current-page:query:?] token?
How to display header field in URL with query token with Drupal 7?

Working on this site, and I disabled title field for taxonomy terms, instead I put a header in there...didn't know could lead to problems later;(

So now I want the header field "field\_header" that substitutes the title to show up in URL for SEO with Pathauto paterns and token.

Tried this \[current-page:query:?\]:

```
[term:parents]/[current-page:query:field_header]

```

But not working, am I missing something here?

# Answer
> 0 votes
According to your image, `field_header` is part of your content type so it's available on **\[node:field\_header\]** token, and all that you need is add it to your content type URL pattern.

---
Tags: path-aliases, tokens
---