title: Webform mail sender

text:
# Question
Title: Webform mail sender
I'm new to Drupal and i'm working on a website that wasn't made by myself.

How can I change the mail sender from a form made with the webform module?

# Answer
> 1 votes
Go back to the WEBFORM tab and look for the E-mails sub-tab. Fill in an address and click Add.

# Answer
> 0 votes
You can edit by it's edit page, it will be /node/XX/webform/emails where XX is your node number

---
Tags: webforms
---


# Question
Title: How can I add content in between views in bootstrap grid format?
How can I add content in between views in grid format?

Header and footer is fine, but how about interrupting the flow of grids, is there a module for that?

Or do I need to hard code a template file?

Or maybe use css to make the element full width at X item number in the grid?

Image to explain here:

# Answer
I am stepping in with the response of Neograph734. Google is your friend and you can easily find the answers there.

But I am going to help you. It is easy to be done: Create a view (page or block) and setup the filter and order criteria to what you want to display. In the pager section, set items to display to 3.

Make an attachment display with the same filter and order criteria. attach the attachment to the first view. Take "attach after" . Then in the pager section, determine how many items you want to show and set the offset to 3.

This way you can either put in the footer section of the first view or the header section of the attachment the text you want to place there.
> 1 votes

---
Tags: views, theming, bootstrap-theme
---


# Question
Title: how to optimize inline images in ck-editor
Is it possible to optimize inline images uploaded via ck-editor.

There is an image with size 11 MB and in default behavior its rendered original without any optimization applied to it.

# Answer
As you can see in the image below, you only have these settings to optimize your image via upload in CKeditor. Using it you can for sure set the image dimensions, file size and path for images.

The below screenshot is from Drupal 8. You can get the same settings at www.example.com/admin/config/content/formats/manage/full\_html
> -1 votes

---
Tags: 8, media, performance
---


# Question
Title: HTTP/2 does not allows to write in folders in Drupal 7, how can I fix?
I've recently changed from HTTP 1.1 to HTTP/2, as soon as i did it I was not able to create or edit files from backoffice (both image upload or css/js cache), but if I did it from FTP there is no problem

All the folders are 755 and all the files are 644 and I could not get other informations

Varnich cache is not installed on the server, what can cause the problem?

# Answer
> 0 votes
Solution found, just needed to install suPHP module and configure it so apache could execute php with owner permissions instead of default user

---
Tags: 7, files
---


# Question
Title: How to fix migration problem with missing entity plugin?
I recently updated my local Drupal website from 8.3.5 to 8.3.7 on my computer. Everything runs perfect; I have no pending updated, the cache has been cleared, and to prepare the site for live deployment, it's in maintenance mode.

Om my computer, the MySQL version is 5.7.9, and PHP version is 5.6.30. I have exported all the files via FTP to the live server, exported the database, and imported it on the live server. I've altered the setting.php files to make it match with the live database credentials.

Then I went to check if there were any log messages I encountered the following PHP error:

`Drupal\Component\Plugin\Exception\PluginNotFoundException: The "entity" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of /home/kim/domains/kimjanssens.be/public_html/carperfection/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).`

As a result of this error, after I clear my cache the whole site crashes and gives the following error messages:

```
The website encountered an unexpected error. Please try again later.

Drupal\Component\Plugin\Exception\InvalidDeriverException: Plugin (entity_view) deriver "Drupal\ctools\plugin\Deriver\EntityViewDeriver" does not exist. in Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDeriverClass() (line 218 of core/lib/Drupal/Component/Plugin/Discovery/DerivativeDiscoveryDecorator.php).

Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator->getDeriver('entity_view', Array) (Line: 99)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDerivatives(Array) (Line: 87)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 22)
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('system_breadcrumb_block') (Line: 16)
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('system_breadcrumb_block', Array) (Line: 76)
Drupal\Component\Plugin\PluginManagerBase->createInstance('system_breadcrumb_block', Array) (Line: 65)
Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->initializePlugin('system_breadcrumb_block') (Line: 57)
Drupal\block\BlockPluginCollection->initializePlugin('system_breadcrumb_block') (Line: 80)
Drupal\Component\Plugin\LazyPluginCollection->get('system_breadcrumb_block') (Line: 45)
Drupal\block\BlockPluginCollection->get('system_breadcrumb_block') (Line: 138)
Drupal\block\Entity\Block->getPlugin() (Line: 113)
Drupal\block\BlockAccessControlHandler->checkAccess(Object, 'view', Object) (Line: 105)
Drupal\Core\Entity\EntityAccessControlHandler->access(Object, 'view', NULL, 1) (Line: 340)
Drupal\Core\Entity\Entity->access('view', NULL, 1) (Line: 56)
Drupal\block\BlockRepository->getVisibleBlocksPerRegion(Array) (Line: 137)
Drupal\block\Plugin\DisplayVariant\BlockPageVariant->build() (Line: 259)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 149)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 656)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

# Answer
> 0 votes
Your error is related to ctools module. Is it still enabled/available ?

---
Tags: 8, migrations
---


# Question
Title: How to create a rule to notify administrators of new comments by non-administrators?
I would like to use Rules to notify all administrator users of new comments that have been posted to the site.

I can get as far as getting the notifications working for all comments, but I would like to set it for notifications to just comments by non-administrators. Administrators will then not be notified for their own responses to comments.

Any hints?

**Note**: I want to do this so that I just have to specify the admin role only, as many new roles will be added that are non-admin roles. This way I do not have to update the rule every time a new role is added by site admins.

# Answer
What you are trying to do is pretty straightforward. I suspect that you have a Rule that is active and has the following:

On event *After publishing a comment*

(no condition)

DO

Send an email to user (or whatever you want to be your notification method; it doesn't really matter)

What you need to do is add a condition by clicking on the respective option. In the "Condition to add" option, you need to select: **"User has role(s)"** and press Next.

In the next page, select **"Published Comment Author"** in the User option and select all the roles of your site except for the Admin role. Leave the rest unchanged.

Now your admins should be receiving notifications for comments from non-admins only.
> 3 votes

# Answer
The previous (and accepted) answer is a pretty good solution to answer this question. But it does have some challenges:

* the question states that "all administrator users" should be notified, which is not exactly the same as sending a notification to a user (as suggested in the accepted answer).
* if new roles get added afterwards, you'd have to also update (not forget ...) the custom rule.

Therefor, I think an improved version of the answer is to use a rule, which looks like so (in Rules export format):

```
{ "rules_notify_admins_about_new_comments" : {
    "LABEL" : "Notify admins about new comments",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "comment:author" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "A new comment was posted for node with id [comment:node:nid] ...",
          "message" : "This is to inform you that a new comment was added to the node with id [comment:node:nid] ... The comment can be found at [comment:url]"
        }
      }
    ]
  }
}

```

Some details about this rule:

* Rules Event: After saving a new comment.
* Rules Condition: the author of the comment does NOT (!!!) have the role "administrator".
* Rules Action: send mail to all users of a role, with role = administrator.

Use the Rules UI to import this rule in your own site, no tuning of any kind needed to make it work as requested in this question, except that you may want to refine the eMail title and eMail body to fit your own needs.

Think about it: it doesn't matter what happens after you enable this rule, i.e. new users are granted the admin role also, or new roles are added (as in the "*Note*" in your question). In all such future updates to a site, the business logic as requested in the question will continue to function with zero maintenance required to this custom rule.
> 0 votes

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


title: How can I add fields to a block?

text:
# Question
Title: How can I add fields to a block?
I'm learning Drupal 8 after working with 7 for a number of years and I'm a bit unsure how to approach this. I need to be able to add a block and have it appear on a few specific pages.

I also need to be able to add some text and a link to this block. Is there a way to add these as fields to the block that can be filled in when the block is added to the page?

It looks like I could accomplish something similar by creating a new content type with those fields and adding it as an "Entity view" but this seems like overly complicated.

Is there another way I'm not aware of?

# Answer
> 4 votes
You can create a Custom block type (admin/structure/block/block-content/types/add) and then add fields to it (admin/structure/block/block-content/manage/YOUR\_BLOCK\_MACHINE\_NAME/fields).

You will see that you have the *Manage form display* and *Manage display* tabs too like the content types, you don't need to create a content type. In Drupal 8 you can use blocks in more than one region.

Check The Block System is Finally Useful in Drupal 8 and see the video.

---
Tags: 8, blocks
---


title: How to build a link to a field_ui form?

text:
# Question
Title: How to build a link to a field_ui form?
Given an entity type id of a fieldable entity type, a bundle name, and a view mode name, how do I construct a url to the respective field\_ui form where this view mode can be edited?

The patterns for the route name seem to be:

* `entity.entity_view_display.ENTITY_TYPE_ID.view_mode`
* `entity.entity_view_display.ENTITY_TYPE_ID.default`

But it seems the parameters have custom names, e.g. `/admin/structure/types/manage/{node_type}/display/{view_mode_name}`, here the bundle parameter is called `node_type`.

Is there a generic way to build such urls to field\_ui pages for any entity type?

# Answer
> 2 votes
After searching in the core files I found the pattern, see the example below:

```
use Drupal\Core\Url;
// The entity type can be 'node'.
$entity_type = 'taxonomy_term';

// Find the bundle entity type, e.g. 'node_type' or .
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $etm */
$etm = \Drupal::service('entity_type.manager');
$bundle_entity_type = $etm->getDefinition($entity_type)->getBundleEntityType();

if (NULL === $bundle_entity_type) {
  // Not clear what to do in this case.
  return NULL;
}

// The bundle can be 'article'.
$bundle = 'tags';
// The route, see that the $entity_type variable is used.
$route = "entity.entity_view_display.$entity_type.view_mode";
// The view mode can be 'teaser'.
$view_mode = 'full';
$a = Url::fromRoute($route, [$bundle_entity_type => $bundle, 'view_mode_name' => $view_mode])->toString();
// To use dpm() you need the Devel module.
dpm($a);

```

---
Tags: 8, entities, routes
---


# Question
Title: Retrieve the default image from an image field programatically
Currently im using the following code to retrieve the uri of an image field:

```
$field = $paragraph->field_background_image_left;
$uri = $field->entity->getFileUri();

```

This seems to work fine when the field contains a value. But when no value is set, '$field-\>entity' will contain null, even when a default image was set for this field.

How do I retrieve the uri of the default image from my field?

# Answer
The default image is stored in field configuration. You can retrieve it as follows:

```
<?php

use Drupal\field\Entity\FieldConfig;

$field_info = FieldConfig::loadByName('node', 'article', 'field_image');
$image_uuid = $field_info->getSetting('default_image')['uuid'];
$image = Drupal::service('entity.repository')->loadEntityByUuid('file', $image_uuid);
$image_uri = $image->getFileUri();

```
> 4 votes

# Answer
Note that you're probably asking the wrong question, and shouldn't be doing this (more on this below). But if you insist:

Remember that there are two layers of defaults. First the default file as set on the field storage, which can be overridden by the default file as set on the field config.

```
<?php

use Drupal\Core\Image\Image;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;

/* var $file File */
$file = $node->field_hero_image->entity;
if (!$file) {
  /* var $field_config FieldConfig */
  $field_config = FieldConfig::loadByName('node', $node->bundle(), 'field_hero_image');
  $file_uuid = $field_config->getSetting('default_image')['uuid'];
  if (!$file_uuid) {
    /* var $field_storage_config FieldStorageConfig */
    $field_storage_config = FieldStorageConfig::loadByName('node', 'field_hero_image');
    $file_uuid = $field_storage_config->getSetting('default_image')['uuid'];

  }
  $file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $file_uuid);
}
/* var $image Image */
$image = \Drupal::service('image.factory')->get($file->getFileUri());

```

But this is really only useful if you want to build everything manually. Most of the time it's better/easier just to use the field's `->view(` method:

```
<?php
$build['headshot'] = $node->field_person_headshot->view([
  'label' => 'hidden',
  'type' => 'responsive_image',
  'settings' => [
    'responsive_image_style' => 'people_headshot',
  ],
]);

```

Further reading:
> 3 votes

---
Tags: 8, media
---


# Question
Title: Can I use my own template for a view mode?
I'm creating a cusom module that loads a node through a `view_builder`. However, none of the available `view_mode` display the elements like I'd like them to be, so I'm about to create my own view mode. However, I have parsed quite a few tutorials about view\_builders, but none talked about using a custom template (or I missed it)

So, is it possible to use your own template, and how do you do so?

Thank you in advance

# Answer
The standard way to do this is to create a template in your theme, you can use node--nodetype--viewmode.html.twig . (two dashes between each part).

To use it in your custom module, you'd have to use hook\_theme\_registry\_alter to change the path that it looks in for that theme hook.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['node__nodetype__viewmode']['path'] = drupal_get_path('module', 'mymodule') . '/templates/';
}

```

I don't really see the value of moving it into a custom module though. It's a standard to keep custom templates in the theme.
> 3 votes

# Answer
When calling the view method, the second argument is the name of a view mode:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityViewBuilderInterface.php/function/EntityViewBuilderInterface%3A%3Aview/8.2.x

Pass in the machine name of the view mode you want to use.

Example:

```
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$output = $view_builder->view($node, 'my_view_mode');

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Cron tasks don't work: Could the Domain Access module be the cause?
I have an issue with a website running Drupal 8. I cannot seem to get cron working. If I go to the status page and click 'run now' it works. If I try to open the cron settings (/admin/config/system/cron) I get an error. The log reports the following:

> Symfony\Component\Routing\Exception\InvalidParameterException: Parameter "key" for route "system.cron" must match "\[^/\]++" ("" given) to generate a corresponding URL. in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 202 of /var/www/exin.com/files/core/lib/Drupal/Core/Routing/UrlGenerator.php).

I looked up the system.cron path in the core files and found it attached to /cron/{key}, so that is not the settings page. It is the URL I was supposed to use for the cron tasks. Calling that URL (replacing {key} with my token) generates a permission denied error, even if I open it when logged in as administrator.

I found the key on the status page by looking at the URL of the 'run now' button (/admin/reports/status/run-cron?token=mytoken). Is this the correct token?

I'm running Drupal 8.3.7, which was updated from version 8.3.1, where I had the same issue.

I'm also using the *Domain access* module and some creative nginx configuration to open different "domains" through a proxy, which (for example) takes users from www.mysite.com/fr/ to fr.mysite.com. This was necessary since the *Domain access* module could not work with subdirectories. It caused a lot of issues which we managed to resolve, but this one sticks. So I'm not sure it is caused by either this module or the nginx configuration, but I feel it is important information.

# Answer
The error is coming obviously from these lines of code in the cron settings form, when it tries to build the cron link:

```
$cron_url = $this->url('system.cron', ['key' => $this->state->get('system.cron_key')], ['absolute' => TRUE]);
$form['cron_url'] = [
  '#markup' => '<p>' . t('To run cron from outside the site, go to <a href=":cron">@cron</a>', [':cron' => $cron_url, '@cron' => $cron_url]) . '</p>',
];

```

Somehow you've lost the system state variable `system.cron_key`, which is on your site "" and causes the error. You find this in the database in the table `key_value` and collection `state`.

To set a new key you can rerun this code (which normally runs when the system is installed, see system\_install()), for example in a `drush php` shell:

```
  // Populate the cron key state variable.
  $cron_key = \Drupal\Component\Utility\Crypt::randomBytesBase64(55);
  \Drupal::state()->set('system.cron_key', $cron_key);

```
> 5 votes

---
Tags: 8, cron
---


# Question
Title: How to show the distance relative to the user's location?
I'm trying to recreate a site, and one part of the content is supposed to show the distance relative to the user's location, like this:

Does anyone know of a way I can accomplish this?

# Answer
> 2 votes
You need to install the Geolocation Field module and the example submodule that comes with it.

In the examples you will find a view that made exactly what you need, and you only will need to clone and edit the view.

> Geolocation Field provides a field type to store geographical locations as pairs of latitude and longitude (lan,lng). The Drupal 8 version also provides a views proximity search plugin. Geolocation Field can be used with all fieldable entities like nodes, users, comments, taxonomy terms, etc.

---
Tags: 8, location
---


# Question
Title: How to send notification emails in a journal style "Newsletter"?
I am working on replace an existing, custom built website with a Drupal 7 site. In the existing website I've coded a more or less smart email-notification system which I like to re-build for the Drupal version (if possible).

The website allows members to create/edit/cancel events, participate/decline events, comment events etc. If any of these action happened they where logged for email-notification. The user then could set an interval how often the so called "Action-Log" should be emailed to the user. eg. once an hour, every four hours, one a day or once a week. This is extremely handy to a) stay in touch with the event and b) to not fill the members inboxes.

Advanced feature (phase 2): Further more the website had some logic to reduce the notification if or example a member already declined an event he will not get any notifications about that event. Think this will get really tricky to do in a generic way.

Any hints about how to do this with Drupal 7?

I already had a look to the following modules:

* Triggers / Actions (sonding email but not "cached/delayed").
* EntityRegistration (used for event registration).
* Notifications (is alpha on D7 and called "quick port").

PS: I was told this feature is normally called "digest".

# Answer
For sending notifications you can use the Notifications module.
> 1 votes

# Answer
# Part 1 - Building your action logging

IMO the Message module could be a perfect alternative for the activity logging you are trying to implement. Using this module, you can create your own custom "*Events logging*" (to register things that happened in a site).

Specific to this question here, I'd create one or more so called "Message types" that contain data about:

* the usernames (of the latest editors of content).
* the relevant date(s).
* any data about the actual entity (node, user, etc) or event you want to track, such as the node's id, its title, author, relevant field values, etc.

You could even track things like updates to nodes, i.e. how data looked like before and after they got updated, a kind of "light" revisioning (only for those node attributes you want to know about).

About *Message types*: think of them as equivalent to Content types, whereas you create messages (instead of nodes) of a specific Message type (instead of Content type).

### Part of the Message Stack

The Message module is part of the Message Stack, which consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Think of the Message Notify / Message Subscribe modules as successors (replacements?) of the Notifications / Subscriptions modules ... even with Drupal 8 successors available also.

Just looking at the available documentation about the Message Stack, it's not obvious to get going with it. But if you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to ***subscribe*** to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

### Rules integration

A really interesting facility of the Message module is its perfect integration with the Rules module. Have a look at the answer to "How to implement a follow author (or user) function?" for way more details on that.

As an example, here is a (rather basic) custom rule:

* a Rules Event like "Before saving a new node", of "After updating an existing node" (or variations of these events).
* a Rules Action to "Create a message" (of a selected Message type).

That's really it ...

### Example included in Commerce Kickstart

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

### Replicate/replace the Activity module

Should you want to do so, it seems perfectly possible to build a view (report) that contains the data similar to what you can do with the Activity module as shown in this screenprint (from this module's project page).

### More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules.

Though there is ***not a lot of documentation about it*** (which is what makes it a hidden D7 gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

**Tutorials:**

# Part 2 - Building your journal style Newsletter

After you've implemented your action logging, similar to what is described in "Part 1", it really becomes a piece of cake to complete it with the journal style Newsletter. Because your action logging will be fully entity based, and therefor perfectly integrates with modules such as Rules and Views.

If you then also add the Views Rules module to it, you've reduced your Newsletter challenge to building some rules that:

* Run at specified intervals (eg when cron runs).
* Process (= Rules Actions) a views result (using Views Rules) to create an appropriate "*digest*" of relevant messages contained in your action logging.
* Send that *digest* by eMail to only those users for which the Views results are not empty (i.e. if there is anything new that happened in the site, and which the user wanted to be informed about).

PS: for dozens of other questions (+ answers) about the Message Stack, refer to this.
> 0 votes

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


# Question
Title: How to provide email notifications to admins for *all* comments?
My site admins are asking to receive email notifications automatically whenever a comment is posted on any content on the entire site. I already have comment\_notify enabled, but that only allows them to get emails for comments posted on *their* content, or on posts they have subscribed to. They want to get those emails for all content by default.

I have also seen the "Notifications via e-mail comparison" page, but none of the module descriptions say they have this feature.

Am I stuck with having to implement a Rules based solution? Or am I missing something?

# Answer
I see that you've already found the Comment Notifications comparison page over at Drupal.org - but also that you say you have not found the module you're looking for there.

However, from the description of your requirements, it sounds like the Notify module is pretty close.

Since it uses a digest format and depends on cron, it will not give your site admins *instant* notifications of new content, but otherwise, it matches your description. Most important, It will send out notifications about *all* new comments, *all* new nodes, or both.

Disclosure: I am a co-maintainer.
> 3 votes

# Answer
Search no longer, and just go for the Rules. But don't fear, all you need is an extremely *basic* rule (a kind of Rules 101 exercise ...), which looks like so (in Rules export format):

```
{ "rules_notify_admins_about_new_comments" : {
    "LABEL" : "Notify admins about new comments",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "A new comment was posted for node with id [comment:node:nid] ...",
          "message" : "This is to inform you that a new comment was added to the node with id [comment:node:nid] ... The comment can be found at [comment:url]"
        }
      }
    ]
  }
}

```

Some details about this rule:

* Rules Event: After saving a new comment.
* Rules Condition: none (though you might want to add anything that fits, e.g "not if the comment author is an admin ...").
* Rules Action: send mail to all users of a role, with role = administrator.

Use the Rules UI to import this rule in your own site, no tuning of any kind needed to make it work as requested in this question, except that you may want to refine the eMail title and eMail body to fit your own needs.

Please admit, this is probably the most basic custom rule one could ever think of, in plain English: "***`Whenever a comment is inserted, send an eMail to all admins`***".
> 0 votes

---
Tags: 7, emails, notifications
---


# Question
Title: How do I create a file object from a local file?
I am trying to attach a file in the custom module's directory to every new node created for a content type. How do I create the file object? The following code gives me an error.

```
$uri1  = file_unmanaged_copy('checklist1.pdf', 'public://checklist1.pdf', FILE_EXISTS_REPLACE);

$file1 = File::Create([
    'uri' => $uri1,
]);
$file1->save();

```

The error I get is the following one:

> The specified file checklist1.pdf could not be moved/copied because no file by that name exists. Please check that you supplied the correct filename.

To add, this code is in the module file inside a hook.

# Answer
> 0 votes
You need to specify the path to your module:

```
$module_path = drupal_get_path('module', 'module_name');

$uri1  = file_unmanaged_copy("$module_path/checklist1.pdf", 'public://checklist1.pdf', FILE_EXISTS_REPLACE);

```

---
Tags: 8, files
---


title: Drupal 7 Node Revisions per Role

text:
# Question
Title: Drupal 7 Node Revisions per Role
I have created a new role '**news contributor**'.
I have created a new content type '**news**'.

The '**news contributor**' role has permissions enabled to view, revert, delete **revisions**.
However, this setting also gives them access to view, revert, delete revisions on ALL nodes.

How can i restrict node revisions on specific content types based on user role and content type?

The '**news contributor**' should only be able to tinker with revisions for the '**news**' content type and nothing else.

At the moment they have access to revision any node which is undesirable.

Has anyone had this issue before and, how did you resolve it?

Thanks.

# Answer
I ran across this issue on a site and with drupal core revisions this is next to impossible. We resorted to using a great module called Revisioning which allows role based revisioning and can tighten who can publish revisions. You are able to grant permission to a specific role to publish while other roles can have the ability to create revisions. This can be for specific content types as well. Also you have the ability to "revert" revisions if you want.

https://www.drupal.org/project/revisioning
> 0 votes

# Answer
I haven't tested it, but there is a relatively new module with a stable 7.x release that looks like it was built only for this purpose: Node revision Permissions Per Role

> Node revision Permissions Per Role allows to give roles administer per content type node revision permissions without giving them full administer nodes permission.
>
> For instance, you may let certain users(eg: roles:External-blogger ) manage node revision of a specific content type(eg: blog) but restrict to manage node revision of all other content type that this module is perfectly works for you.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: What would cause a duplicate session key?
I occationally recieve the following error resulting in failure of several pieces of code later in the pipeline.

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'QUyrgEInS_vO0GbrOhJffh6npb2ejlpllvS8Thn2pYY-Cu6Y9OkPd1qJuonzHQw2' for key 1:
   UPDATE {sessions}
   SET sid=:db_update_placeholder_0, ssid=:db_update_placeholder_1
   WHERE (ssid = :db_condition_placeholder_0) ;
Array (
   [:db_update_placeholder_0] => QUyrgEInS_vO0GbrOhJffh6npb2ejlpllvS8Thn2pYY
   [:db_update_placeholder_1] => Cu6Y9OkPd1qJuonzHQw2JI67BDvO85pqp50SBsXE1ZU
   [:db_condition_placeholder_0] => fMabX3y84Ngm-HcGF8MomLvLp1kmceLRIwniv_dSj_M )
in drupal_session_regenerate() (line 393 of /var/aegir/platforms/demandmetric/includes/session.inc).

```

I am using custom code that rougly looks like this:

```
drupal_session_start();
_$SESSION[''] = bunch of generated info.
Authorize linkedin
create user
$form_state['uid'] = $account->uid;
user_login_submit(array(), $form_state);
Update profile from linkedin info.

```

The error occurs on the user login submit part.

I suspect that drupal\_session\_start is causing the issue but I don't understand sessions well enough to debug this. The issue occurs 1 in about 30 users. I added the session start because the session info on line 2 doesn't get set without it.

Other suspects are memcache (very unlikely) and secure pages.

Anyone know about session that can enlighten me to how to track this issue down?

# Answer
> 1 votes
Check your `sites/default/settings.php` file, if you have `$conf[https] = TRUE;` then removing it will fix the error.

Removing it also won't affect any security issues as long as your server/domain is configured properly. You can also check the Enabling HTTP Secure page from Drupal.

# Answer
> 0 votes
Just leave out `drupal_session_start();`. You simple can assigning stuff to `$_SESSION` (even for anonymous users). The data will be still present after a login. For an example of how this works, I'd suggest examining the shopping cart module of Drupal Commerce.

Note that this does not work when logging out for obvious reasons (session is destroyed on logout).

---
Tags: users, sessions
---


# Question
Title: How to get slick slider working well on multi-directional(RTL/LTR) site?
After install slick slider and Slick Views modules on multi-directional site, Slider does not work well on RTL, There is option in slick slider module for RTL sites, but this broke slider on LTR, So we need this an option enabled only on RTL sites, I found this solution. How can accomplish this?

# Answer
> 3 votes
This is possible by implementing template\_preprocess\_slick

```
use Drupal\Component\Serialization\Json;

/**
* preprocess variables for slick.html.twig templates.
*/
function template_preprocess_slick(&$variables) {
  $language = \Drupal::languageManager()->getCurrentLanguage();
  if($language->getDirection() == 'rtl') {

    $settings = $variables['content_attributes']->offsetGet('data-slick');
    if(!empty($settings)) {
      $settings = Json::decode($settings->value());
      $settings['rtl'] = true;
      $settings = Json::encode($settings);
      $variables['content_attributes']->setAttribute('data-slick', $settings);
    }
  }
}

```

---
Tags: 8
---


# Question
Title: How to locate the Entry Points of a Drupal 8 Core module?
I'm to perform a security audit on the Drupal 8 Core modules, and was curious if there were any telltale signs of Entry Points (ie, how a module communicates with an external module and vice-versa).

OWASP defines an Entry Point as "the interfaces through which potential attackers can interact with the application or supply it with data."

I assume this is not very different from Entry Points of standard web applications (forms, HTTP packets, etc.), but I am interested in knowing whether or not Drupal has its own standard as to where these Entry Points are located. Are there specific snippets of code I should be looking for?

I do intend on reviewing the modules manually and in-depth, but figured someone on here may have some advice to help lessen the steep learning curve.

Any and all help is appreciated!

Cheers! :)

# Answer
Entry points will equate to routes in Drupal.

Modules will normally define their routes in a YML file named MODULE\_NAME.routing.yml, but routes can be defined programmatically as well, check out this article from Acquia about routes: https://dev.acquia.com/blog/coding-drupal-8/defining-and-altering-routes-in-drupal-8/22/03/2016/9891

Also the 'routing' table in the database lists all the paths and their corresponding routes (I believe all). Note the use of '%' and '{some\_value}' to indicate dynamic route values.

Hope that gets you started.
> 2 votes

---
Tags: 8, security
---


# Question
Title: How do I create a View filter by a parent taxonomy term?
I've got a taxonomy that is set up as such, which I am using with Taxonomy Term Templates:

`Manufacturer>>Model>>Colour`

Eg:

`Honda>>Accord>>Red`

I'd like to create a View that displays all siblings of a Taxonomy, eg if I am on the Accord page I'd like the view to return other Honda models (eg: Civic, CR-X, HR-V, Odyssey).

I've tried using the `%term:parent` as a contextual filter, but have had no luck - no results display.

Would anyone know how I might go about this?

# Answer
> 2 votes
Please follow such steps for getting your result (Child Items)

1)Add Taxonomy term: Term ID in CONTEXTUAL FILTERS.
2)Add Taxonomy term: Parent term in RELATIONSHIPS. (leave Require this relationship unchecked.)
3)Add Taxonomy term: Parent term in filter section. select great than 0.
4)Do not forget to filter your taxnonmy term in mycase Taxonomy vocabulary: Machine name (= airports).
5)Add Taxonomy term: Rendered Taxonomy term to your fields , select relationship to parent , check the Exclude from display.
6)In setting, under FORMAT section. In grouping field 1, select (Parent) Taxonomy term: Rendered Taxonomy term.

You should good to go. you can use view tpl to add more class base on the group.
I have enclose my screenshot for references.

---
Tags: 7, views
---


# Question
Title: How to enable the php option in Views contextual filters, provide a default value option?
I have a text field called campaign and I want to set a contextual filter for this field, but I don't see a PHP option here. How can I turn this feature on? I don't see it anywhere.

# Answer
You can php option in the filte using "Views Php" module

For installing this please follow such steps :
1. Download this module using https://www.drupal.org/project/views\_php.
2. Install this module.
3. In views filter now you will get PHP option.
> 1 votes

---
Tags: 7, views
---


title: How remove whitespace on field in twig?

text:
# Question
Title: How remove whitespace on field in twig?
I try to print field value in a node--template.html.twig without whitespace. This field is a select in admin page.

```
Location|Location
Achat|Achat

```

This is how my value is print :

> {{ content.field\_type }}

> field.html.twig :

```
{% for item in items %}
{{- item.content -}}
{%  endfor %}

```

I try some twig argument like

> {{content.field\_type|trim}}

But when i print like this, it's empty.

So where are this whitespace ? same if i try to test the value in if else condition :

This doesn't work because of whitespace :

> {% if content.field\_type == "Achat" %}

This work :

> {% if content.field\_type|render|trim == "Achat" %}

So for test a value it's ok, but for print the value if i use

> {{content.field\_type|render|trim}}

i got same result with whitespace.

So if someone can tell me where is add this whitespace and how remove this in twig. I use the boostrap theme, but i don't see anything who add whitespace.

# Answer
It sounds to me that you have a template, probably `field.html.twig` that is adding this space. You can enable the `twig` debug to see which templates' files are used.

Also, I think it's better to test the value on `node.field.value` instead of `content.field` as it's done for the rendering only.

Note that the twig operators as `{% for ... %}` also add spaces, so you should add `-` as well in there for e.g.:

```
{%- for item in items %}
{{ item.content }}
{%  endfor -%}

```
> 6 votes

# Answer
I tried many times and spaceless tag works pretty well.

Use the following syntax:

```
{% spaceless %}

  {{content.field_type}}

{% endspaceless %}

```
> 4 votes

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


# Question
Title: How to escape single quote from a token to use it in SQL query?
Working on Drupal 7.54

I am using a custom PHP/SQL Rules to synchronize Drupal field values with an external database.

I am trying to export a text field value but sometimes I have single quotes in these values.

Consequently, when I try to use a field token in my SQL query, it fails because of this single quote that is not escaped.

I have read a few things about replacing strings and escaping quotes but I did not manage to get my query working (replace? str\_replace? addslashes? htmlspecialchars? decode\_entities?...).

Here is an example :

Let's say I have a Drupal field called "Text-Drupal" in a content type A.

Each time a content of type A is updated, I need to export the Text-Drupal value in an external database in the column text\_database

The little code :

```
db_set_active('database_local');
db_query("UPDATE table
SET text_database=NULLIF('[node:field-text-drupal]','')
WHERE title=[node:title]");
db_set_active();

```

This code works fine with any text without special characters but each time I have a single quote, it fails (and I guess it would be the same with double quotes).

I am quite sure this is something really simple for experienced users so I hope someone could point me to the right direction. Thanks.

# Answer
> 2 votes
**Disclaimer**: you shouldn't be using the PHP filter module, ever, it's very bad practice and can open your site up to security holes. Adding a custom rules action is very easy and should always be the preferred implementation method for something like this.

As a technical exercise, though, something like this might work:

```
$text = <<<EOF
[node:field-text-drupal]
EOF;

$title = <<<EOF
[node:title]
EOF;

$args = [':text' => $text, ':title' => $title];
$sql = "UPDATE table SET text_database = NULLIF(:text, '') WHERE title = :title";
db_query($sql, $args);

```

# Answer
> 0 votes
Here is my own solution to send long text tokens to an external database without single quote problems :

```
     $token="[node:field-text-drupal]";
     $token_clean=addslashes($token);
     db_set_active('database_local');
     db_query("UPDATE table
       SET text_database=NULLIF('$token_clean','')
       WHERE title=[node:title]");
     db_set_active();

```

With addslashes, the token value could contain any quotes without interfering with the query and the database displays the right value.

---
Tags: 7, database, rules
---


# Question
Title: Why do uploaded files gets saved with an all-caps file extension?
On my product site any uploaded images get saved with the .JPG saved in all-caps. I don't see the same issue on my local development machine so I would think it has to be a server issue? The live site uses NGINX.

# Answer
Definitely not a server (nginx) issue, as the server does not do anything with the files (well, it transfers them bit by bit). Like Charlie already asked, do you use any modules?

**Edit:** To answer your second question, of course you can “force” lowercase extensions. But personally I wouldn’t bug your users with that, they should simply upload whatever they have. Instead simply alter the files extension before saving the file to disk/database.

hook\_file\_presave() seems like the correct way to do this. You would have to create a little module and have a look at the file variable that’s passed to your hook, then simply `strtolower()` the file extension.
> 1 votes

# Answer
Files on the camera are stored using a very simple file system using 8.3 file names, which by default are upper-case (originally these file systems didn't distinguish between upper and lower case in filenames)
> 0 votes

---
Tags: 7
---


# Question
Title: Which Rules Event can I use for automatic login from main site to sub site with same database after clicking on a link?
In the home page of main site, I am listing all the products. Buyer has logged into the main site and clicks on any product title or image, then I take the buyer to the corresponding sub domain individual product page. In the redirected page or site I want the buyer to logged in since I am using the same database.

This is what I have done for that to happen:

* I am using the Rules module to **redirect** from one site to another site.
* The **Rules Event** I am using is **Content is viewed**, but **actually it doesn't get called at all**.
* In Rules I am using page redirect action with value `http://[node:author].[site:url-brief]/ajax_callback.php?context=buyer-redirect&username=[account:name]&nid=[node:nid]`

In my `ajax_callback.php` file I have used this code:

```
case 'buyer-redirect':
        global $user;
        $username = $_REQUEST['username'];
        $user = user_load_by_name($username);
        $login_array = array ('name' => $username);
        user_login_finalize($login_array);
        $nid = $_REQUEST['nid'];
        drupal_goto('node/' . $nid);

```

But in the sub domain still I am not logged in as buyer.

Above mentioned is a PHP file where I am manipulating the requests, but Rules Event "Content is viewed" is not all getting invoked.

How can I make buyer login info to be send and make the buyer to be automatically logged in which clicking on a link in main site?

Any suggestions?

# Answer
> 0 votes
I'm pretty sure that the "***`... Content is viewed, but actually it doesn't get called at all ...`***" part of your question is not correct. And that this Rules Event does get called (if not you've found a major Rules bug ...), but that it is NOT the right Rules Event to use for your scenario. Read on for details (and a possible solution) ...

You should be able to get this to work, using the Rules module, using the "**Drupal is initializing**" event. That will ensure that the rule gets triggered BEFORE the actual content is shown. Using Rules event " *Content is viewed* " is typically 'too late'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for more details on that. Adapt your rule to use this event, and (just for temporary unit testing) add a Rules Action (as the very first Rules Action) to "Show a message on a site", e.g to say '*Bingo, let the Rules party begin (we did find a Rules Event to continue building on)*'.

Moreover, as per the `http://[node:author].[site:url-brief]/ajax_callback.php?context=buyer-redirect&username=[account:name]&nid=[node:nid]` URL that you mentioned, you can make the value of the URL arguments (= such as the value of the `context` argument in this example) available as new variable to Rules, simply by using the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

---
Tags: 7, rules, redirection, subsites
---


title: Is Drupal 8 with PostgreSQL supported?

text:
# Question
Title: Is Drupal 8 with PostgreSQL supported?
Is the new Drupal 8 supported/certified by the Drupal community to run on PostgreSQL?

This is the top hit,

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

I don't really know what that means here in the Open Source part as the majority of support is MySQL (or so it appears).

# Answer
it works and its even blazing fast.

tested on

```
drupal core 8.3.7
postgresql 9.6.3
amp stack - XAMPP

```

drupal case to follow on postgres drupal integration https://www.drupal.org/node/2564307
> 3 votes

# Answer
Did you not read the issue thread? or the last comment? Which links to https://www.drupal.org/node/2564307 and says:

> As of September 2015 we have all tests passing the PostgreSQL CI bot (yay!). However, there are still some open issues around that should be fixed in terms of performance, security and for contrib land.

Drupal 8 Core will likely support PG. But, contrib modules typically use vendor specific SQL for complicated queries -- so per-module support will likely continue to be spotty.
> 1 votes

---
Tags: 8, database
---


# Question
Title: Display list of users with a specific role to guest users
Some users on my Drupal 8 site have the role of 'Champion'. I have created a views block that lists out all the users with this role. It shows the list correctly when I am logged in as an admin, but does not display any results to guest users. It appears that the 'View user information' permission, which I have assigned to guest users does not allow viewing of user's roles ( I can see why from a security point of view).

Can anyone suggest how I can get this list of users to display for guest (unauthenticated) users? Either how I could override the permissions, or another approach?

# Answer
> 0 votes
Please check this setting, Also check the user permission.

---
Tags: 8, views, users
---


# Question
Title: Is there any way to use view display format to show the data in drupal 7?
I have created a custom content type "listusers" and add fields to that content type. After that i created a view page where i select display format as "Table" now my output is like below:

can any one suggest me is there any way to achieve the view as attached in below image

# Answer
You could filter the view by the designation column to group the results. To separate the tables I would create different view blocks for each result and put them one after each other. You could use the block title for the Haryana/Ambala text and style it accordingly.

In the example bellow I have a view with 3 blocks and each of the blocks displays rooms tagged by a room category.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Creating Views rows with specific classes?
I have created a view and it gives me lots of default css classes for the rows of my unformatted list. I have added the token \[type\] in the style options for the page under 'Row class'. So now my list items are wrapped in the following div:

```
<div class="views-row views-row-1 views-row-odd views-row-first article"></div>

```

You can see the class 'article' is added according to the node's content type. But, I need to give specific rows, like the third occurence of class 'article' row, their own 'static' unique css classes, like:

```
<div class="views-row views-row-1 views-row-odd views-row-first article my-class"></div>

```

views-row-\[number\] will not do because it changes depending on how many rows there are in the view (not always the same in this view) i.e. the third from last row will sometimes be views-row-10, sometimes it will be views-row-13. How do I find out what other tokens are available to me (I'm looking for ones that will create unique classes), or is there another way that I can create a unique, unchanging, class?

I have tried using pseudo css classes to target the desired rows, like :nth-of-type(N).

**Solution**

To make classes unique, append an incrementing number to the required classes with jQuery. CSS pseudo class selectors are helpful too, as are tokens. There does not seem to be one solution that will fit every situation: a mix of approaches is required.

Add to template.php in your theme's root folder (or how ever you want to implement your jQuery):

```
/**
 * Implements template_preprocess_views_view().
 */
function YOURTHEME_preprocess_views_view(&$vars) {
    $view = $vars['view'];
    if ($view->name == 'VIEWNAME') {
        drupal_add_js('
            (function($) {
                $(function() {
                    $("div.article").removeClass("article").addClass(function(index) {
                        return "article-" + index;
                    });
                });
            })(jQuery);
        ', 'inline');
    }
}

```

# Answer
You could bring a dull ax to the party and use jQuery:

```
$('div.article').filter(function(index){
  $(this).addClass('article-' + index);
  return (index%3 == 2);
}).addClass('article-third');

```

which will create `article-0` thru `article-N` classes on every div with class `article` it finds as well as putting a special `article-third` on every third one it finds.
> 1 votes

# Answer
You need to modify views-view-unformatted.tpl.php.

In your views, in the third column click on theme and choose the how specific should be you file, for the full view or for that display. Copy into your theme folder and rename it.

You can find more info here http://api.drupal.org/api/views/theme%21theme.inc/group/views\_templates/7

```
    <?php if (!empty($title)): ?>
     <h3><?php print $title; ?></h3>
    <?php endif; ?>
     <?php
     $i = 1;
     $num_rows = count($rows);
     $num_rows = $num_rows -2;
     ?>
    <?php foreach ($rows as $id => $row): ?>
    <?php
     if ($i == $num_rows){
       $classes_array['YourCLass'];
     }
     ?>
     <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
      <?php print $row; ?>
      <?php $i++;?>
     </div>
    <?php endforeach; ?>

```

Flush cache
> 2 votes

# Answer
I know you said you tried `nth-of-type`, but have you tried `nth-child`?

Say for example you've added a class called `myrows` to your Views output (you can do this through the UI under style settings for anyone who doesn't know), then targetting every third row should be as simple as the following:

```
.myrows {
  //Make all rows red
  color: #FF0000;
}

.myrows:nth-child(3n) {
  //Make every third row green (not including the first)
  //So 3, 6, 9, 12 etc will be green
  color: #00FF00;
}

```

Here's a jsFiddle just to show it working :)

*Some useful resources:*
> 1 votes

# Answer
This is an old thread, but for reference i think the module Semantic Views can do this. There is both a Drupal 7 and a Drupal 8 version of this module.
> 0 votes

---
Tags: views
---


title: Custom module template not detected

text:
# Question
Title: Custom module template not detected
The page--404 suggestion is visible in the twig debug comments:

```
function amu_http_status_code_display_theme_suggestions_page(array $variables)
{
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  $http_error_suggestions = [
    'system.401' => 'page__401',
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {

    $suggestions[] = $http_error_suggestions[$route_name];
  }

  return $suggestions;
}

```

But it fails to consider the

> templates/page--404.html.twig

from my module.

I have tried this

```
function amu_http_status_code_display_theme($existing, $type, $theme, $path) {

  $arguments= array(
      'template' => 'page--404',
      'base hook' => 'node',
  );

  // this is the name of the templates
  return array(
    'page--404' =>  $arguments,
  );
}

```

# Answer
> 1 votes
thanks to 4k4 comment, i have made it working

```
/**
 * Setting 40x template suggestions
 */
function amu_http_status_code_display_theme_suggestions_page(array $variables)
{
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  //mapping the route with its suggestion hook
  $http_error_suggestions = [
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {

    $suggestions[] = $http_error_suggestions[$route_name];
  }

  return $suggestions;
}

/*
 *
 * make drupal knows the templates are located in the module
 *
 * */
function amu_http_status_code_display_theme($existing, $type, $theme, $path) {

  $arguments403= array(
    'template' => 'page--403',
    'base hook' => 'page',
  );

  $arguments404= array(
    'template' => 'page--404',
    'base hook' => 'page',
  );

  //mapping the hook with its template
  return array(
    'page__403' =>  $arguments403,
    'page__404' =>  $arguments404,

  );
}

```

---
Tags: 8, theming
---


# Question
Title: What does Rules token "node:unchanged" mean?
I am on Drupal 7 and I am using the Rules module to do some stuff.

I must say that I am not very used to using this module; there are few questions that need answers, such as the use of the *node:unchanged* token.

For example, when I set a rule with a data comparison as a condition, I have to give the name of the referred field; then, there is either *node:changed* or *node:unchanged*.

I am quite accustomed to using *node:changed*. What does *node:unchanged* mean?

# Answer
### Terminology

"***`unchanged`*** refers to the value before something (eg, a field of entity user or node) gets updated (the old value that it used to be).

"***`changed`*** refers to the value after something (eg, a field of entity user or node) gets updated (the new value that it will become).

### Examples

Have a look at my answers to these question for some typical usecases of it:
> 5 votes

# Answer
"Unchanged" is literally the opposite of "changed" in this context. If you know what node:changed means, just reverse it for node:unchanged.

For reference, though:

* node:changed refers to a node after field or property data has been changed, following a node save
* node:unchanged refers to the same node, before field or property data has been changed.

The two are useful together for determining whether a particular field or property value has been changed on a node, and what the value went from/to, in a particular save operation.
> 5 votes

---
Tags: nodes, rules
---


# Question
Title: How to get views field data in defineOptions() method of custom filter?
I am creating a custom filter for views. In \*.views.inc file I am using `hook_views_data_alter()` to create the filter in views. Then creating a class for filter that extends `NumericFilter` filter class. Now, in `defineOptions()` method I want to feed the min and max numbers. These min and max data comes from a field in the view. Therefore, I want to know how can I get field data in that `defineOptions()` method.

```
class ItemQuantity extends NumericFilter {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->definition['options callback'] = array($this, 'generateOptions');
  }

  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['value'] = [
      'contains' => [
        'min' => ['default' => ''],
        'max' => ['default' => ''],
        'value' => ['default' => ''],
      ],
    ];

    return $options;
  }

  public function operators() {
    $operators = parent::operators();
    $operators['overlaps'] = [
      'title' => $this->t('Overlaps by'),
      'method' => 'opOverlap',
      'short' => $this->t('<>'),
      'values' => 1,
    ];
    return $operators;
  }

  protected function opOverlap($field) {
    $this->query->addWhere($this->options['group'], $field, [$this->value['min'], $this->value['max']], 'IN');
  }

  /**
   * Override the query so that no filtering takes place if the user doesn't
   * select any options.
   */
  public function query() {
    if (!empty($this->value)) {
      parent::query();
    }
  }

  /**
   * Skip validation if no options have been chosen so we can use it as a
   * non-filter.
   */
  public function validate() {
    if (!empty($this->value)) {
      parent::validate();
    }
  }

}

```

I want to get the value of min\_quantity field in the view.

# Answer
You can access with:

```
$this->options['value']

```

Read more about this in Building Views Query Plugins for Drupal 8, Part 3
> 0 votes

---
Tags: 8, views
---


# Question
Title: How can I use a view on site2 that consumes data from site1?
We have a Drupal site that exposes a JSON API for users (http://site1/api/users).

We need to create on site2 a view of users based on the data provided by site1. (We cannot store the users on site2).

How can I use a view on site2 that consumes data from site1? Which hook should I use? What approach should I follow?

# Answer
> 1 votes
The External Entities module can help you in this task.

> This module allow you to connect to datasets from external databases and use it in your Drupal 8 website. While content lives external, Drupal sees those remote entities as internal. This makes it possible to alter the field displays, add references, comments, pathaliases, share buttons, webshop products and more.

You can read to Drupalize remote data with external entities.

---
Tags: views, 8
---


# Question
Title: How to display a new taxonomy term on a select box using Webform?
I am using Drupal 7. I have Webform and Webform Term Options installed. I have a taxonomy list of terms called "Training Events". Under "Load a Pre-Built Options List" I select the Training Events list, and save. I view the webform and the list of taxonomy terms is there on the select list. However, if I go to Structure -\> Taxonomy -\> List terms -\> Add term and add a new term, that new term does not appear on the webform. Why won't it appear and do I make it appear?

# Answer
The error was I was adding a new vocabulary, not a new taxonomy term to the existing vocabulary.
> 0 votes

---
Tags: webforms
---


# Question
Title: Displaying data by views from external API
I have made 2 db's one is of Drupal 8 and another is external, that is non-SQL(CouchDB) and to manage this DB I made an API with different endpoint(URLs) witch I can axes them by GET/POST methods. After correct request I get response in JSON from my API.

When I create for example a user, content(node) or something else I save some info in my Drupal database and some info in my API db (I made alteration of the forms that create content by hook\_form\_BASE\_FORM\_ID\_alter and this way I create content in my external DB).

My question is how to Display a data from a views, combining information form two Data-Bases?

# Answer
> 1 votes
Maybe you can post some more details, but from what I understand you are storing additional information per node on an external database. You already have developed an API system for communicating with that database, so you don't really need to issue queries from Drupal directly to that database. In that case, one way to proceed this would be the following.

Configure Views to use a display mode to render your entity. On your node preprocess function, issue the API request and fetch the additional data from the 2nd database. Prepare the data and make them available to the template.

```
/**
 * Implements hook_preprocess_node(&$variables).
 */
function MY_THEME_preprocess_node(&$variables) {
  // Issue API request.
  // Process JSON response.
  $variables['additional_field'] = $request_result;
}

```

You can then override the template for that entity (node) and display mode to render your additional fields.

If you need Views to use field display instead of rendering a display mode, you will need to develop a custom field handler that fetches the data from the external API. Let us know if you need help with that.

An alternative would be to use Views hooks to prepare the data in a similar way earlier in the process, but there's not really much of an advantage with that approach. That is, unless you have the capability to fetch all data for all results in a single API request. That would be the most efficient so that you don't issue multiple requests, one per node result. Let us know if this the case and if you need help with that.

# Answer
> 3 votes
There are modules like Views Database Connector, External Entities in combination with Search API for views integration or Web Service Data \- dunno about it's views integration. Remote Entity API is not yet ported to drupal 8. See: Drupal entity from different database

Ideas for custom coding are: Views Query Backend or Search API (or write your own search api backend - Maybe via solr)

> In either way think of caching. As making request to your API in every request to your site is very expensive.

# Answer
> 3 votes
If all you need to do is display data from the API, then you don't need to do anything special within views. Just select that you'd like to view rendered entities of your users with a specific view mode.

In the preprocess function for that view mode, you can hit the API and load the additional data that you need. Data loaded within a preprocess function should cache, so it shouldn't hit the API on subsequent page loads.

```
function mymodule_preprocess_user(&$variables) {
  /** @var $account \Drupal\user\UserInterface */
  $account = $variables['elements']['#user'];

  // custom code to hit the 3rd party API

```

# Answer
> 1 votes
First caveat. It is difficult to query across databases. Views by default does sql queries. Any kind of query that requires coalescing the data from both is 2 custom queries and a merge in PHP. This is not something that views is going to help you with.

There are a lot of approaches that will help you with this. I'd tackle it by building JSON data sources and using AngularJS to present the data.

2x sql sources. 2 sql data sources can be mapped as per drupal 7. Use the query interfaces and massage the data. Return as JSON.

The question leads to answers that map database tables to views, and there are tools to do this. I don't think you will get a views 'experience' form separate databases.

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


# Question
Title: Forced rendered node view results in empty node links
In order to send html email using drupal/swiftmailer I load and view a node.

Then I pass it to the rendere. In the email sent, generated node\__links are empty. As node\_links uses #LazyBuilder, Im then not sure to use the correct way.

`hook_mail`

```
function mymodule_mail($key, &$message, $params) {
   switch ($key) {
       case 'mail_node':
           $message['from'] = \Drupal::config('system.site')->get('mail');
           $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
           $message['subject'] = t('Mail subject');

           $node = Node::load($params['nid']);
           $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

           $body_data = [
               '#theme' => 'mymodule_mail_node',
               '#content' => $view_builder->view( $node ),
           ];

           $message['body'][] = \Drupal::service('renderer')->render($body_data);
       break;
       }
 }

```

`mymodule--mail-node.html.twig`

```
 {# simply render the whole body #}
 {{ body }}

```

`output results in mail`

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'links__node' -->
<!-- FILE NAME SUGGESTIONS:
    x links--node.html.twig
    * links.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/content/links--node.html.twig' -->

<!-- END OUTPUT from 'core/themes/classy/templates/content/links--node.html.twig' -->

```

When I render the same content into an html page, node\__links are correctly filled.

Any recommandation would be appreciate. Thanks

# Answer
> 1 votes
Use renderPlain():

```
$message['body'][] = \Drupal::service('renderer')->renderPlain($body_data);

```

From the documentation:

> Renders final HTML in situations where no assets are needed.
>
> Calls ::render() in such a way that placeholders are replaced.
>
> Useful for instance when rendering the values of tokens or emails, which need a render array being turned into a string, but do not need any of the bubbleable metadata (the attached assets and cache tags).

Source: Renderer::renderPlain

---

"When I render the same content into an html page, node\__links are correctly filled."

render() in a page works, because the page has a render context for the metadata to bubble up, so that the placeholders can be replaced later.

---
Tags: theming, 8, emails, navigation
---


title: How to get managed_file value url?

text:
# Question
Title: How to get managed_file value url?
I'm trying to add a front page image as part of the theme setting. And so far I'm able to upload the image; however, I need to be able to get this in preprocess function so I can use the in my templates.

Here is what I got so far

**casper.theme**

```
/**
 * Implements hook_preprocess_page().
 */
function casper_preprocess_page(&$variables){
    $variables['frontpage_background_image'] = theme_get_setting('frontpage_background_image', 'casper');
    kint($variables['frontpage_background_image']);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function casper_form_system_theme_settings_alter(&$form, &$form_state, &$theme) {
    _casper_theme_settings($form, $form_state, $theme);
}

 function _casper_theme_settings(&$form, &$form_state){
       $form['theme_extra']['frontpage_background_image'] = array(
        '#type' => 'managed_file',
        '#title' => 'Front Page Background Image',
        '#description' => 'Add background image for the front page',
        '#required' => FALSE,
        '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
        '#default_value' => theme_get_setting('frontpage_background_image' , 'casper'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
    );
}

```

And here is the kint results

So my question is what I'm doing wrong ? What should I do to get the URL instead of a number ?

# Answer
Your field only stores the file ID, so it makes sense that theme\_get\_settings only returns a number. If I'm not mistaken, this should work:

```
use Drupal\file\Entity\File;
function casper_preprocess_page(&$variables){
  // Get the value of the first element in the array.
  $fid = reset(theme_get_setting('frontpage_background_image', 'casper'));
  // Load the file.
  $file = File::load($fid);
  // Generate the URL.
  $variables['frontpage_background_image'] = $file->url();
}

```
> 6 votes

# Answer
I've merged the answer provided by marcvangend & suggestion provided by Berdir.

```
use Drupal\file\Entity\File;
/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {
  $facebook_icon = theme_get_setting('facebook_icon', 'mytheme');
  if (!empty($facebook_icon)) {
    $fid = reset($facebook_icon);
    $file = File::load($fid);
    $variables['facebook_icon'] = file_create_url($file->getFileUri());
  }
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Is there a date / time format that only shows minutes if they are non-zero?
I want a time/date format in a View that renders like this when a time ends in :00
**Sep. 16, 2017 - 2pm**

BUT, renders like this only if minutes are present:
**Sep. 16, 2017 - 2:30pm**

Currently, I use this format: `M. d, Y - g:ia` but I need a way to make those zeros disappear when an event starts at the top of the hour.

# Answer
> 1 votes
you can use views conditional module, from module page:

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include: Equal To Not Equal To Greater Than Less Than Empty Not Empty Views conditional allows you to output text based on the result of the condition.

and here is a tutorial how to use it, https://www.youtube.com/watch?v=LIyZV\_Hhccw

# Answer
> 3 votes
A bit of a cludge but if your output allows simple html, you can write a format that includes a span around the colon and minutes and use the minutes as a class. Then hide the span if it's 00. E.g.

```
M. d, Y - g<\s\p\a\n\ \c\l\a\s\s='\m\i\n-i'>:i<\s\p\a\n\>a

```

Then css of

```
.min-00 { display: none; }

```

I've done this with dates to produce over/under large date/small month displays. If it's coming from a view, you may need to check the allow html option on the field.

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


title: composer.json for just core

text:
# Question
Title: composer.json for just core
How do I get just Drupal 8 core using drupal-composer?

This would be very useful for core development and starting a new project without any assumption.

# Answer
> 0 votes
Sounds like you want drupal-console. This tool can quickly create working Drupal 8 sites interactively or via command line. More info here.

Another quick alternative is to use DrupalVM and Varnish to spin up a fully working D8 site. The DrupalVM defaults are to create a D8 sandbox site.

I believe that DrupalVM now has Docker support so you might be able to have a single VM and just spin up a new D8 box.

---
Tags: 8
---


title: Grouping content types in group nodes

text:
# Question
Title: Grouping content types in group nodes
I have created 2 different groups and updated content(basic pages & article) using group module in my drupal 8 project.

Currently it is listed in nodes tab of group.

I have used an view module to group based on the content type. But i couldn't make it.

Can anyone help me out?

# Answer
> 0 votes
The Group module provides Views 'relationships' to any node's parent group.

Try these steps to create your view:

* Add a relationship to the parent group.
* Add a contextual filter on the group's id (`gid`).
* Create a page, a block, a content pane, etc (whatever fits your needs).

---
Tags: views, group
---


title: Create language modal(dialog)

text:
# Question
Title: Create language modal(dialog)
I'm trying to create a language modal for Drupal 8.

I only want to show the modal if:

* Language paramater is not present in URL
* Language cookie is set by previous selection.

I don't really know what the best method is to create this. I started by creating a hidden ajax button which gets clicked by custom js if the language parameter is not present in the URL and the language cookie is not set:

```
namespace Drupal\dms_theme\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\lang_dropdown\Form\LanguageDropdownForm;
use Drupal\Core\Url;
use Drupal\Core\Language\Language;

/**
 * Class LangswitchModal.
 *
 * @package Drupal\dms_theme\Form
 */
class LangswitchModal extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'dms_theme_langswitch';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    $form['actions']['#type']  = 'actions';
    $form['actions']['submit'] = [
      '#type'  => 'submit',
      '#value' => $this->t('Switch language'),
      '#ajax'  => [
        'callback' => '::open_modal',
      ],
    ];

    return $form;
  }

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

  }

  public function open_modal(&$form, FormStateInterface $form_state) {
    // Get active domain
    $domain_negotiator = \Drupal::service('domain.negotiator');

    $form = \Drupal::formBuilder()->getForm('Drupal\dms_theme\Form\LangswitchForm');

    // Build array
    $build = [];

    $build[] = [
      '#theme' => 'langswitch_modal',
      '#title' => 'Welcome',
      '#form' => render($form),
    ];

    $render  = \Drupal::service('renderer')->renderPlain($build);

    // Dialog
    $options = [
      'dialogClass' => 'popup-languageswitcher-modal',
      'width'       => '100%',
    ];

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand(NULL, $render, $options));

    return $response;
  }
}

```

The modal is opened correctly and the content and form is printed.

Logic of the form:

```
namespace Drupal\dms_theme\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\lang_dropdown\Form\LanguageDropdownForm;
use Drupal\Core\Url;
use Drupal\Core\Language\Language;

/**
 * Class LangswitchForm.
 *
 * @package Drupal\dms_theme\Form
 */
class LangswitchForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'dms_theme_langswitchform';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Service
    $domain_negotiator = \Drupal::service('domain.negotiator');

    // Language options
    $language_options = [];
    foreach(domain_locale_custom_get_domains_languages()[$domain_negotiator->getActiveId()] as $domain_language) {
      $language_options[$domain_language->getId()] = $domain_language->getName();
    }

    $form['languages'] = [
      '#type' => 'select',
      '#title' => t('Please indicate from which location you are connecting:'),
      '#options' => $language_options,
      '#required' => TRUE,
    ];

    $form['actions'] = [];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit button'),
    ];

    return $form;
  }

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

  }
}

```

Now i can't submit the form correctly. It redirects to urls like /form\_action\_p\_pvdeGsVG5zNF\_XLGPTvYSKCf43t8qZYSwcfZl2uzM.

I geuss this is caused by the ajax callback url, which is used by some form parameters. But don't really know how to solve this.

Thnx.

Other question: What are in general the best practice to show a language modal. If language is not is in URL? If language is not set in Cookie? Or the combination described above?

# Answer
> 1 votes
You render early twice, which prevents that any attached metadata has a chance to get into the response. You can try without rendering or if you need to render, then attach the metadata to the response like in this example:

ModalRenderer::renderResponse

```
  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    // First render the main content, because it might provide a title.
    $content = drupal_render_root($main_content);

    // Attach the library necessary for using the OpenModalDialogCommand and set
    // the attachments for this Ajax response.
    $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $response->setAttachments($main_content['#attached']);

    // If the main content doesn't provide a title, use the title resolver.
    $title = isset($main_content['#title']) ? $main_content['#title'] : $this->titleResolver->getTitle($request, $route_match->getRouteObject());

    // Determine the title: use the title provided by the main content if any,
    // otherwise get it from the routing information.
    $options = $request->request->get('dialogOptions', []);

    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));
    return $response;
  }

```

Additional to the example you might need to add the attachments of the form too:

```
$response->addAttachments($form['#attached']);

```

---

"Other question: What are in general the best practice to show a language modal. If language is not is in URL? If language is not set in Cookie? Or the combination described above?"

There is also a server side approach. You can add some kind of overlay with the form before you deliver the page.

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


# Question
Title: How to have a content type that displays a title, a description and a list of feeds imported from an external URL such as blogspot?
I know this is already discussed, I read many answers, but I am unable to make this simple operation.

I want a content type that displays a title a description and a list of feed items from an external URL that user can set when creates this content type node.

Ok, I installed feeds module, created an importer. Before this I created a content type named "blogger" (for test only). So I created an importer also named "blogger" and I attached to "blogger" content type.

Then I set fetcher as http download and parser to rss. Now, in processor settings I can see bundle that are my content type installed, so I selected blogger, but I tried to select feed item, the result is the same. In mapping I am confused: I tried to set all possible combinations; I set item guid as unique field. I then create a node type of blogger content type, and I added URL of my blogspot page. I named this node "test page". When I view "test page" I can't see feed items that are imported. Drupal creates 25 node of "blogger" type, that are my feed items, but I don't want this.

Now, I wrong something in settings of feeds module? Or feeds module is not my way?

I only want see my blogspot items all in my test page; that's it...

Can anyone help me?

# Answer
> 0 votes
> Drupal creates 25 node of "blogger" type, that are my feed items, but I don't want this.

There is a difference between attaching an importer to a content type and selecting a content type on the node processor. The first one is meant as a sort of "container" - you'll need to create nodes of this type in order to import content. The content type select on the node processor is the type of nodes that Feeds will create when you import content. Make sure that these two settings are always different.

So you need to make sure that you have two content types:

* One content type - called "blogger" for example - is the content type that you attach the importer to. This setting can be found under "Basic settings". This means you need to create a node of this type in order to import content.
* The second content type - called "blog item" for example - is the type of content that you want Feeds to create. Select this content type on the node processor.

When you now create a "blogger" node and provide a source - in your case an URL since you selected the HTTP fetcher for your importer - Feeds will create nodes of type "blog item".

In order to show the blog items on your blogger node, you'll need to create a View and find a way to display that View on your blogger node. One way of doing that would be using a block that is only shown on your blogger content type.

If you want to have a head start with this, I recommend to install the Feeds News module (this module is included with Feeds). This demonstrates how to use the attach to content type feature. It also includes a View for displaying the imported items (though on a separate page).

---
Tags: 7, feeds
---


# Question
Title: JavaScript from custom module not detected
I have created a custom module, which is working. Except the JavaScript, which is not being detected. I have been following the description at https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview and I have checked other modules.

What have I done to implement JavaScript? I have created a file with the following JavaScript content (location: MODULE-ROOT/js/info.js):

```
/**
 * @file
 * Info behaviors on node edit form.
 */

(function ($, window) {

  'use strict';

  Drupal.behaviors.nodeEditForm = {
    attach: function () {
      console.log('Hi there!');
    }
  };

})(jQuery, window);

```

Then I have added the following content into my MODULE-NAME.libraries.yml file:

```
nodeEditForm:
  version: 'VERSION'
  js:
    js/info.js: {}

```

I expect to see "Hi there!" in my webdeveloper tools inside Google Chrome browser, after I flush the entire Drupal 8 and browser cache. I do not get any output there.

Is it a "must" to attach the JavaScript to any existing behavior? If so: how can I learn which behavior is tied to an node edit form?

Thanks for your attention.

# Answer
> 3 votes
> Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load all assets (CSS/JS) on all pages, because this is bad for front-end performance.

You need to inform Drupal to attach your library to the page.

In your case, you can use `hook_form_alter` and check the `$form_id` or `hook_form_FORM_ID_alter` for a single case and add this:

`$form['#attached']['library'][] = 'mymodule/nodeEditForm';`

Then clear the cache. Search the `core` folder for `$form['#attached']` for more examples. You should then see your js file listed in the source of the page as well as console log output.

---
Tags: 8, javascript
---


# Question
Title: Intermittent Access Denied errors for anonymous users
I'm running into seemingly random Access Denied errors that occasionally come up on most (but not always all) node pages for anonymous and low-level users (anyone without the "Bypass content access control" permission).

* I've rebuilt permissions a few times, which fixes it for awhile too, but the behavior returns.
* I've scoured user permissions and don't think there's anything incorrect in there.
* We are not using any contrib node access modules.

Clearing the site caches fixes this, but it comes back after awhile, so I suspect this is cache-related. We use Redis.

This is a pretty new Drupal 8 site that used the Lightning install profile. We use Panels/Panelizer for layouts. We have a bit of custom code in place (a few form alters, a few blocks, a few redirects, nothing particularly complex - but it's certainly possible there's something off in there).

Anyone seen this before or have troubleshooting suggestions?

# Answer
> 1 votes
Figured this one out, not particularly efficiently (never really found a good way to backtrace this), but got there nonetheless.

The issue was coming from the Custom Permissions module, which I'd incorrectly written off as innocent early on in troubleshooting since I use it on other sites without issue. Whoops.

That module lets you create permissions via a UI for any path you'd like. We had one in place that created a permission that was already defined by core (managing blocks -- accessing admin/structure/block). Removing this redundant permission fixed our problem here. (Uninstalling the module also fixed the issue.)

I'll post an issue in that module's queue if it's reproducible with a clean install.

---
Tags: 8, users, caching
---


# Question
Title: join->left_table with an SQL Select statement
Im adding a join via the query\_alter hook.

```
  $join->left_table = '(SELECT * from blah)';

```

On the left table, instead of a table, I would like to put a select statement.
How do I do this?

# Answer
> 2 votes
Quoting the documentation for db\_select and addJoin it says the table:

> May be a string or another SelectQuery object. If a query object is passed, it will be used as a subselect.

This should be roughly right:

```
$subquery = db_select('blah');
$existing_query->addJoin('LEFT', $subquery...

```

I'm not sure if being in a query\_alter hook or being a left join affect how this works, but it's a suggestion that should help you find the answer.

---
Tags: database
---


# Question
Title: form_set_error highlights only select fields and not other required field types
I have a content type with few required fields. When I try to save a node without filling any data, all the required fields throw an error message saying the field is required, but the required fields aren't highlighted in red. Only the select fields are highlighted; date fields or text fields aren't.

>

This is happening when I use the Zero Point theme (version 7.x-4.10).

How should I proceed with troubleshooting?

# Answer
This was because of CSS overwritten by Zero Point theme, added more classes in my custom CSS file:

```
    /* .form-item input.error, */
    .form-wrapper .fieldset-wrapper .form-item input.error,
    .form-item textarea.error,
    .form-item select.error {
            border: 2px solid red;
    }

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Pros and Cons of Combining CSS/JS files or loading contextually?
I am building an application in Drupal 7. There is one common CSS file `A.css` with 1000 lines of code. There are other 5 CSS files(`B.css`,`C.css` .... `F.css`) with 100 lines each. I want to load the other 5 files contextually(only on the pages they are needed).

Regarding pagespeed, what are the pros and cons of combining all those CSS files into one or loading them separately(contextually) ?

AFAIK, If I load them contextually, then the weight of those 5 files will be avoided in the pages they are not required. But I am not sure how Drupal's aggregation works. There are two possibilities I can think of.

1. When `B.css` is loaded contextually, the aggregated file will contain `A.css + B.css` into one file. Lets call it `X.css`. By this logic, when `C.css` is loaded, the aggregated file will contain `A.css + C.css`. Let's call it `Y.css`. But since `X.css` and `Y.css` are two different files, this will not utilize browser's caching and will make http requests each time.
2. When `B.css` is loaded contextually, `A.css` and `B.css` will load separately. And similarly `C.css` will be loaded separately when needed. By this logic, `A.css` will be cached. Also `B.css` and `C.css` will be cached after being loaded once.

Which way it works(1 or 2)? How do I control it ?

# Answer
> 2 votes
As Drupal documentation says here: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme,

**Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load every assets on every page, because it slows down front-end performance.**

You don't need to worry about loading libraries (CSS/JS) contextually. Drupal can load individual libraries for a certain block, or when a certain node type is being displayed. That's the purpose of the `[theme-name].libraries.yml` file, you can mention the specific blocks and page in there and tell it load the required library for that part.

You can attach the library to all pages, to specific Twig templates, or to a render element in a preprocess function.

For instance for a maintenance page:

```
maintenance-page:
 js:
  js/mobile.install.js: {}
 css:
  theme:
   css/maintenance-page.css: {}
 dependencies:
  - system/maintenance
  - thunder_admin/global-styling

```

Or for certain blocks or part of your page:

```
vertical-tabs:
 css:
  component:
   css/components/vertical-tabs.css: {}
dropzonejs.widget:
 css:
  component:
   css/components/dropzonejs.widget.css: {}

```

You can also use hooks like `THEME_preprocess_HOOK()` function in the `.theme` file. 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';
}

```

# Answer
> 2 votes
AdvAgg's bundler sub module does a good job of balancing the browser cacheabilty (no aggregation) vs faster payload (all aggregated). For CSS when using HTTP/1.1 a value of 2 will give the fastest page rendering times; HTTP/2 doesn't have a real penalty so using a value of 15 is better.

http://www.webpagetest.org/ with the Connection set to mobile edge as well as https://developers.google.com/speed/pagespeed/insights/ is how to measure frontend performance. See https://www.drupal.org/node/2493801 for how AdvAgg is currently used for drupal.org.

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


# Question
Title: Most performant way to check if a user is referenced in any node of a specified type?
I need to get a list of all users that have a specific role. Those users can be referenced in a multivalue field of a specific content type; some users are referenced in multiple nodes of that content type, some in none. I want to filter out all users that are not referenced in any node of that content type. Here's my current (functional) code:

```
 $ids = \Drupal::entityQuery('user')
 ->condition('status', 1)
 ->condition('roles', 'dozent')
 ->sort('field_name', 'ASC')
 ->execute();

 foreach($ids as $k => $id){
   $references = \Drupal::entityQuery('node')
   ->condition('type', 'angebot')
   ->condition('field_dozenten', $id)
   ->count()
   ->execute();
   if(intval($references) === 0) unset($ids[$id]);
 }

```

This works as intended as far as I can tell, but performant-wise it seems quite inelegant due to the large amount of database queries. Is there a better way? Can I somehow include the condition that a user must be referenced in at least one node in the first entityQuery? If not, is there a more performant way to perform the second query (e.g. a way to only search for the first reference from a node to the user, since I don't need the exact count anyway)? I'm open to other suggestions as well.

# Answer
> 2 votes
I suggest you NOT to worry about performance until it's not a real issue. That doesn't mean of course you can write any silly things you want to. The code snippet you posted is just fine. You are using the Drupal API, which is a good thing to do.

If you really want to speed up things, to make it for example with ONE query (instead of two) you can use:

```
\Drupal::database()->select("..."); // With a proper dependency injection

```

About how to write queries in Drupal connection class there is a lot of good tutorials. If you wouldn't find one, please let me know.

However, I only would use this, if it's a REALY performance issue. It's never a good thing "having a knowledge" in your production code about your table schemes. Always start with `EntityTypeManager` or `entityQuery` (as you did).

---
Tags: 8, database, performance
---


# Question
Title: Modifying [current-page:page-number] token
I am using \[current-page:page-number\] token in title and metatag description. Pager in views, gives second page of view as "Page 1" and token gives first page of view as "Page 1".

This creates difference in URL\`s and title tag, such as : Title: Daily News - Page 2 | example.com URL: http://example.com/news?page=1

How to decrease value of \[current-page:page-number\] token by 1?

# Answer
> -1 votes
I was able to achieve this by modifying token.tokens.inc. At line 755, I added this code :

```
 if ((int)$page>0)
      { $page_num = $page;
      $replacements[$original] = " - Page ".$page_num;
      }
      else
      $replacements[$original] = "";
      break;

```

Is there any cleaner way to do it by writing custom module or hook?

---
Tags: tokens, paging
---


# Question
Title: Exclude the www- append to only one multisite
Stock Drupal 7 contains the following in the .htaccess file

```
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  RewriteCond %{HTTP_HOST} .
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

As per client request, this works just dandy! However, on a multisite installation, one site wants to be excluded from this rule. I tried to get them to remove the auto-www-append, but alas, that failed.

So now I'm in a situation which some multisites (most of them) want the www appended and a small group doesn't want it.

**My question**: Can I exempt some sites from this rule? Can I throw these exceptions into an apache conf file in `/etc/httpd/conf.d/www-exceptions.cnf` so that it's not overwritten in a core update?

# Answer
> 0 votes
Unfortunately putting separate htaccess files in each sites folder doesnt work, otherwise it would be quite straight forward.

Perhaps you can use REWRITECOND to do this?

```
RewriteCond %{REQUEST_URI} yourclientsdomain.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

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