# Question
Title: How to fix my Rule to notify authors of products by email at order completion?
I'm trying to send email notifications to authors of each products (line-items) in the order at completion.

I have tried many things surrounding the rule below... that is now at a strange point in its life.

I can use the `[commerce-order:commerce-line-items:0:commerce-product:creator:mail]` trick, but that sends the mail only to the first product owner.

```
{ "rules_commerce_order_message_admin_order_notification" : {
    "LABEL" : "Commerce order message: admin order notification e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "3",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "message_notify", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_line_items" } },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commerce_order_admin_order_confirmation",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:message-commerce-order" ],
          "value" : [ "commerce-order" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : 1 } },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "\u00c9l\u00e9ment de la liste courante" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "commerce_product", "id" : [ "list-item:line-item-id" ] },
                "PROVIDE" : { "entity_fetched" : { "entity_product_fetched" : "Entit\u00e9 r\u00e9cup\u00e9r\u00e9e" } }
              }
            },
            { "variable_add" : {
                "USING" : { "type" : "user", "value" : [ "entity-product-fetched:creator" ] },
                "PROVIDE" : { "variable_added" : { "event_creator" : "Variable ajout\u00e9e" } }
              }
            },
            { "message_notify_process" : {
                "message" : [ "entity-created" ],
                "save_on_fail" : "0",
                "save_on_success" : "0",
                "mail" : [ "event-creator:mail" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

What's wrong with my rule?

**Note**:

I would prefer using the Rule, but out of desperation, I have also tried to give directly the email whit something like :

```
$order = commerce_order_load($order_id);
foreach ($order->commerce_line_items['und'] as $line) {
$line_item = commerce_line_item_load($line['line_item_id']);
$product_item = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
$product_author = user_load($product_item->uid);
$courriels = $courriels . '<' . $product_author->mail . '>,';
}
print substr($courriels, 0, strlen($courriels)-1);

```

# Answer
> 0 votes
### Preface

I have the impression that there is indeed "*something wrong*" in your rule, but please allow me to start with some (constructive intended) critique about the rule you created ...

Your issue may be partially caused because of the naming conventions you used for the variables in your Rules Actions. Your rule processes *thingies* such as `entity_created`, `list_item` and `entity_product_created`, etc. And you didn't post many details about what this rule is supposed to actually do/achieve. So probably only somebody who knows how to "read" Rules in its export language, may possibly be able to understand your current rule.

Imagine how much easier it would be to READ your rule if you'd have used variables such as `admin_order_confirmation_msg`, `line_item` and `ordered_product`.

### What your current rule seems to be doing

By using the kind of variable names I suggested, it seems to me that your last Rules Action is an attempt to send the entire content of the message that you created in your first Rules Action (to be delivered to `commerce-order:owner` as per that same 1st Rules Action). But in this last Rules Action you ask the Message Notify module to eMail that very same message to what appears to the eMail Id contained in a user object whereas that user object corresponds to the `ordered_product` in the `line_item` being processed.

To move on, let's assume you really want the entire order (of X line items) to be eMailed to each (cfr your Rules loop) user that matches a specific `ordered_product` in any `line_item`. If that assumption is wrong, then make sure to add another Rules Actionn to create another message (entity) specific to a single line item (which is what I'd do, so that these messages would only contain data about "a" line item, not all of them ...).

### Maybe the message module is confused

I've never tried, in a rule, to send the same message "entity" via Message Notify module and also have that same entity delivered (saved) with the Message module. So could it be that you're just confusing the Message module?

And another cause of possible confusion is within the rules module, where sometimes it gets tricky to "save entities". So possibly adding an appropriate intermediat "save entity" action may also help (if nothing else helps).

### Time for some basic Rules debugging

Just (temporary) add a Rules Action to "display a message" (located within group "System"). And show the actual value of your token `event-creator:mail` as part of that message (btw: this is a Drupal status message, not anything related to the message module).

Based on the actual eMail Ids that will be shown in those debugging messages, you'll know in which direction to move forward to fix your rule.

### Maybe add 'Replacement tokens' to your Message entity

If anything above does not help to solve your issue, then it may well be that you can get it to work with the technique of ***Replacement tokens***. For (way) more details on that, head over to the answer to What's the purpose of "Replacement tokens" of a Message type?. I'm pretty sure that using this technique you can create a perfect solution to your issue. If you have more questions about that, use this link.

---
Tags: commerce, rules, emails
---


# Question
Title: Unable to import due to "Field 'sourceid2' doesn't have a default value"
I am using the awesome module Migrate, but I have problem, which I am unable to solve. I try to migrate articles from custom PHP site with MySQL DB to D7 with MySQL. The generated SQL query from my migration is ok when I run it in my MySQL DB using MySQL CLI. But when I try to migrate it using the Migrate UI, I get an error:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=113&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE\[HY000\]: General error: 1364 Field 'sourceid2' doesn't have a default value: INSERT INTO {migrate\_map\_geografbgarticlenode} (sourceid1, needs\_update, rollback\_action, hash) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3); Array ( \[:db\_insert\_placeholder\_0\] =\> 2 \[:db\_insert\_placeholder\_1\] =\> 3 \[:db\_insert\_placeholder\_2\] =\> 0 \[:db\_insert\_placeholder\_3\] =\> ) in MigrateSQLMap-\>saveIDMapping() (line 434 of ~/drupal/dev/sites/all/modules/migrate/plugins/sources/sqlmap.inc).

It seems the problem is with my MigrateSQLMap function, looks like N.id is NULL when the query is run by Drupal. But I triple checked it before posting, it's not nullable field in DB and in the generate query result. Any idea how can I fix it?

```
$query = Database::getConnection('default', 'legacy')
      ->select('news', 'N')
      ->fields('N', array('id', 'category_id', 'createdon', 'updatedon', 'createdby', 'updatedby'))
      ->fields('L', array('code'))
      ->fields('NT', array('name', 'short_description', 'description'))
      ->fields('G', array('id', 'description'));
    $query->leftJoin('news_translations', 'NT', 'NT.target_id = N.id');
    $query->leftJoin('languages', 'L', 'NT.language_id = L.id');
    $query->leftJoin('tags', 'T', 'T.news_id = N.id');
    $query->leftJoin('gallery', 'G', 'G.target_id = N.id');
    $query->addExpression('GROUP_CONCAT(LOWER(T.tag))', 'tags');
    $query->groupBy('N.id');
    $query->orderBy('N.id', 'ASC');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('article');

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'id' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
        ),
        MigrateDestinationNode::getKeySchema()
      );

    //... not relevant

```

# Answer
Ok, I resolved this issue. I am new to Migrate module and I think the message was not clear enough.

First I have mapped to complex foreign key with two columns:

```
<?php
    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'id' => array(
            'type' => 'int',
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
          'id2' => array( // no longer exists in my code
            'type' => 'int',
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
        ),
        MigrateDestinationNode::getKeySchema()
      );
?>

```

But then I used only the first foreign key. The database table storing the mapping between source and destination had two columns sourceId, because of first attempt to run migration, but hasn't updated with the new migration in the code.

I dropped the migration\_map table and everything was freshly rebuild and works like a charm.
> 0 votes

---
Tags: 7, migrations
---


title: Drupal service session handling

text:
# Question
Title: Drupal service session handling
In my angular app, I am trying to use headless Drupal using service module. I can't able to find a proper documentation to handle session authentication for each subsequent calls. My each request ends in "csrf validation failed" message.

Can anyone suggest a good tutorial or steps to handle session authentication?

# Answer
For any POST, PATCH or DELETE request, you always need to pass along the `X-CSRF-Token`.

After logging in via REST, the new `X-CSRF-Token` should be provided in that data result, then you can just set that aside (in a global variable, in local storage, etc) and then pass it along with each request.

I personally use (and created) this module to make things easier: https://www.drupal.org/project/angular\_drupal
> 0 votes

---
Tags: 7, services
---


# Question
Title: "Accept answer" button for Advanced Forum comment
I have a forum using the Advanced Forum module in which users ask questions. I want to add a button next to responses, so that the poster of the question can accept one of the answers (in fact, just like this forum works). I then want that post to appear highlighted as being the correct answer.

I realise that Flag is the module to use for this functionality, but I'm not sure how to make the "Accepted answer" appear to all users when the node owner flags the comment, when they are not owners of the original comment. Any ideas about how I can implement this functionality?

# Answer
> 1 votes
## Answers module as a possible alternative

To implement something like "*the poster of the question can accept one of the answers*" (as in your question), you'll need something to allow one or more ***answers*** to be posted, and also have a way to create a (visual) relationship between the answer(s) and the question.

To do so, you might want to have a look at the Answers module (disclosure: I'm a (co-)maintainer of it). Either to actually use this module, or to get inspiration from it to see some of its features at work.

Here are some details about it (from its project page):

> Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Since a picture is worth more then 1000 words, here is a sample screenprint of it (head over to its project page for more details):

## About the Answers module

At its core, this module exists of 2 typical content types: **`Question`** and **`Answer`** (what other names would you expect ...).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module (and supports voting, which in this use case may not be needed, unless you want users that evaluate offers to use it).

To be complete:

* You can use the "Best Answer" submodule for implementing something like "Node author can accept". And you could make the Rules module trigger all sorts of subsequent things to happen "when an answer gets marked as best answer".
* It also comes with a "subscribe" feature (based on the "Message stack", with the amazing the Message module at its core).
* Since the module is using (2) standard content types, all sorts of the typical standard Drupal facilities are also available, or can be enabled. E.g. if you want, you can also use a text format like "***Markdown text***", provided you first enable/configure the Markdown filter module.
* ... (there is really a lot, not just a bit, more).

## Demo site

Have a look at the demo site of the Answers module. This link shows various menu options within the block with title ***Answers Menu***, i.e.:

* **Questions** (= a view):
    + **All**: of all existing questions (= default tab).
    + **Answered**: all questions which have a "best" (= accepted) answer (= sub-tab).
    + **Unanswered**: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).
* **Answers** (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
* **Rankings** (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
* **Ask Question**: to post a new question (the equivalent of `node/add/question`), which is only shown for authenticated users though.

These views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visible in the demo site).

## Try it out

To experience it yourself, try out a demo of it. Here are the steps to do so:

* Head over to the demo site.
* Just accept the defaults to create a sandbox demo site (make sure you're using the most recent 7.x-4.x version). Then hit the create sandbox button, and wait for the process to complete. Make sure you also enable the ***Answers Theme*** (sub-module of Answers, new as of 7.x-4.x).
* Create at least 1 question using either the "*Add content*" menu link and then selecting "Question", or just enter relative path `/node/add/question`. And complete the title and body of the question.
* After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
* If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
* Use the ***Questions*** tab (or enter relative path `/questions`, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

## Release recommendation

To decide between the **7.x-3.2** and the **7.x-4.0-rc2** release, I would recommend the 7.x-4.0-rc2 (which also has the shiny new theming stuff ...). Even though it is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. Pretty soon an rc-3 (the last 'rc' release?) should become available also, which will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).

---
Tags: 7, flags, nodes
---


# Question
Title: How do I programmatically place a block?
From UI you can add a block in a region in that way:

1. Go to Admin -\> Structure -\> Block layout (/admin/structure/block).
2. Click on "Place block" button besides the region name.

I want to do the same thing but programmatically. How do I add an existing block to a region and save it? This block should then be displayed in that region and be available in the *Block layout* page.

# Answer
> 9 votes
To provide a *plugin block* you can build an array of settings and pass it off to `\Drupal\block\Entity\Block::create()` to create the Block object and save the instance.

For example if you wanted to add a Devel *Execute PHP* block to the Seven theme:

```
$values = array(
  // A unique ID for the block instance.
  'id' => 'devel_execute_php_1',
  // The plugin block id as defined in the class.
  'plugin' => 'devel_execute_php',
  // The machine name of the theme region.
  'region' => 'content',
  'settings' => array(
    'label' => 'Execute PHP',
  ),
  // The machine name of the theme.
  'theme' => 'seven',
  'visibility' => array(),
  'weight' => 100,
);
$block = \Drupal\block\Entity\Block::create($values);
$block->save();

```

# Answer
> 8 votes
You ca use Twig tweak module:

> Twig Tweak module provides a Twig extension with some useful functions and filters that can improve developer experience.

And then on your twig template region:

```
{{ drupal_block('block_id') }}

```

# Answer
> 6 votes
Each instance of a block (which "block type", configuration and the placement) is a config entity: `\Drupal\block\Entity\Block`. So all you have to do is to create a new instance of this entity with the correct details and you're done.

This can be done but is crazy complex, you would need to understand the plugin system, block plugin system and a lot more.

You can take a look at `\Drupal\block\BlockForm::submitForm` to get a feel for this or `\Drupal\simpletest\BlockCreationTrait::placeBlock`. You might want to think about if this is something you really need, the visibility of the block is pretty complex.

# Answer
> 6 votes
I found the answer thanks to How to manipulate an Entity:Block programmatically in Drupal 8.

```
use Drupal\block\Entity\Block;

$block = Block::load('sitebranding');
$block->setRegion('content');
$block->save();

```

# Answer
> 5 votes
I'm just learning D8 but I seem to have found a much easier way to place a block programmatically (It seemed pretty intimidating after reading googletorp's answer!)

When I enabled my custom module that defined the block I wanted the block to automatically be placed in the correct region. Steps I used to achieve this are:

1. Enable the module and place the block using the UI at `/admin/structure/block`
2. Go to the Single Item config export page at `admin/config/development/configuration/single/export`
3. Select **Configuration type** block and for the **Configuration name** select the block that you just placed using the UI and then copy the generated code.
4. In your module create the folder `/config/install/`
5. Under the generated code textarea it tells you the filename you need to use. Create this file in the `/config/install` directory and copy the code in there.
6. Now when you uninstall your module and then re-enable it the block will automatically be placed.

# Answer
> 2 votes
The example above is close enough but still not correct. The idea is that you have to come up with your own id of the block instance (in my case devel\_execute\_php\_1112 (maybe because I tried to make it work 1112 times, it will remain mystery)) and then the actual block id (the one that is declared for the custom blocks in the annotation) and the theme. Then just set the region and you are good to go. Created an instance of a block under the desired region.

```
$blockEntityManager = \Drupal::service('entity.manager')->getStorage('block');
$block = $blockEntityManager->create(
  array(
      'id'=> 'devel_execute_php_1112',
      'plugin' => 'devel_execute_php',
      'theme' => 'seven'
  )
);
$block->setRegion('content');
$block->save();

```

edit1: I actually checked later the comment above - and it is right. It is just not clear that the id is something that you have to come up with. As a redemption for my lame comment I will post a solution on how to create a block instance of a custom block entity:

```
$blockEntityManager = \Drupal::service('entity.manager')->getStorage('block');
$block = $blockEntityManager->create(
  array(
      'id'=> 'ggggggggsssssss',
      'plugin' => 'block_content:79d53b4e-9e60-4f97-befc-101da919bb7a',
      'theme' => 'visitb_he_theme'
  )
);
$block->setRegion('content');

```

basically the same but for a plugin you write block\_content:uuid\_of\_custom\_block\_entity\_instance

---
Tags: 8, blocks
---


title: Multilingual site title

text:
# Question
Title: Multilingual site title
I've got a problem translation my site title with the Configuration translation module. I set my set title to let's say XXX which is not displayed by the tamplte at all. Instead, it always attaches "| Drupal" string to the end of the node title.

When I click to add translation, translate the string to let's say YYY and save the form, everything appears to be saved correctly, the English version of my site even displays the correct title. However, the form for adding Site information translation still displays an "Add" button as if nothing had been added before and the default version of the site continues to display the "| Drupal" string even though my site name is set to XXX.

Has anybody else experienced the same behaviour?

# Answer
> 1 votes
Well, I have experienced a similar problem when manipulating with more language versions. In the `config` database table, I had two rows with the name `system.site` \- one of them had a `collection = "language.sk"` and the other (full record) had an empty `collection` and in the `data` column `langcode` SK. So, I think the interface was confused, because there were two rows for one language. However, I do not know how the database got into this state.

So I have deleted the row with `collection = "language.sk"`, cleared the cache and now you can change source site name and also create translations - it started to work. Please try this and let me now, if that works.

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


# Question
Title: How do I contribute a version of the same module for the latest core version?
I have contributed a module for Drupal 7; now I am interested in contributing the Drupal 8 version of the same module.

When I started creating the Drupal 7 version; I had all the instructions (under VERSION CONTROL of the project); now I need instructions in order to start with the Drupal 8 of the module.

So, I am looking for GIT instructions.

# Answer
Drupal.org apparently doesn't give information for Drupal 8, in the *Version control* tab of projects. I checked for a project with a Drupal 8 version (the Token module), but even selecting a Drupal 8 branch, the information given is for Drupal 7.

That said, there isn't much difference, with Drupal 8. What I report here are the adapted instructions for Drupal 8.

> ## Creating Releases
>
> See the naming conventions for a complete description of how to name branches and tags so you can create releases.
>
> ### Branch for a dev release
>
> This creates and checks out a new branch in one command, then pushes it to Drupal.org.
>
> ```
> git checkout -b 8.x-1.x
> git push -u origin 8.x-1.x
>
> ```
>
> ### Tag for a stable release
>
> ```
> git checkout  8.x-1.x
> git tag 8.x-1.0
> git push origin tag 8.x-1.0
>
> ```
> 3 votes

---
Tags: community-official-site
---


# Question
Title: Should all files/folders in an installation be owned by the web server user?
As in the title, should all files/folders in a Drupal 8 installation be owned by the web server user, e.g. the default www-data user for Apache?

As far as I know, the answer is **yes** at least in principle, so that all files/folders should have www-data as both owner and group, and more so because of logistics/minimalism/ease of management.

Is that correct or are there other considerations?

# Answer
> 3 votes
Securing file permissions and ownership is the canonical reference for this topic, and is still relevant for Drupal 8.

If we are going under the assumption where we are talking about who owns these files, then we can also assume you have root on the machine and configure the entire environment the way you need.

Having "www-data" (or equivalent) own the entire DOCROOT of any website is an unnecessary security attack surface. If there is a security breach (either through code or the webserver), then an attacker can change code on the site.

If you have root, then you don't need to explicitly use the UI for uploading or updating modules. This is the only real reason to have www-data own the site.

The linked article has all of the details, but I always recommend

* A normal user owns everything in DOCROOT, except for sites/default/files (or wherever your files are for your sites), the private, and tmp directories (and if possible private and tmp outside of DOCROOT).
* Apache runs with a proper umask so that group write is on for files
* The data directories have 2775 permission on them, so group ownership is retained
* Your normal users is also in the www-data group, so drush / drupal console work as expected

The script in the linked article handles most of this; I usually create custom ones for my sites that do the same thing.

---
Tags: 8, files
---


# Question
Title: How to create a view showing content linked with an entity reference field?
I have 2 content types: Developments and Carousel Images. Carousel Images has an entity reference field to select the Developments page it is linked to.

I simply want to create a view which will display on all Development pages, but only show the images which are linked to it. So the Development page called 'London' will display a view with all Carousel images where 'London' is selected in the entity reference field.

I have tried using contextual filters and relationships but not been able to get this working.

Any ideas?

# Answer
OK, finally worked out how to do it. Thanks to this video which explains it all: https://www.youtube.com/watch?v=4Pdii7aFIvc&t=392s However, in case anyone else is stuck you need to first create a relationship based on your entity reference field, sthen create a contextual filter using node:id based on url. This is all you need to do.
> 0 votes

---
Tags: 7, views, entities
---


title: rendering a custom entity

text:
# Question
Title: rendering a custom entity
I have a custom entity 'sponsor'.

I want to create a custom template for that entity. But I still want to use the formatter settings that have been defined in the UI.

So

* I set the viewbuilder to the default EntityViewBuilder in my annotation
* I defined the theme hook 'sponsor' in my .module file

```
function sponsors_theme(){
$theme_hook= array(
    'sponsor'=>array(
        'variables'=>array(
            'sponsor'=>null,

        ),

        'template'=>'sponsor',
    )
);

return $theme_hook;

```

}
* Then I created my sponsor.html.twig file

Now I can access the raw values through {{sponsor.field.value}}

But I don't want to access all fields through their raw values. I still want to use the formatters.

Is there anyone who can tell me how to do that or point me to the right docs?

Matt.

# Answer
You could craft a variable that holds all entity fields with respect to their order and formatter settings.

```
/**
 * Implements hook_theme().
 */
function sponsor_theme() {
  return [
    'sponsor' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for sponsor templates.
 */
function template_preprocess_sponsor(&$variables) {
  // Helpful $content variable for templates.
  $variables['content'] = [];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

```

This approach is used by core entities (node, user, comment etc).
> 5 votes

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


title: EntityFieldQuery INNER JOIN

text:
# Question
Title: EntityFieldQuery INNER JOIN
I'd like to run a query using the EntityFieldQuery object. I need value from both the node and node\_access table therefore I'd need to use INNER JOIN. From the d.o documentation I can't figure out how this is possible.

Here's what I have --

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'node_access')
->propertyCondition('type', 'external_link')
->propertyCondition('status', 1)
->fieldCondition('gid', '3', '=')
->fieldCondition('realm', 'domain_id', '=')
->fieldCondition('grant_view', '1', '>=')
->range(0,1)
->execute();

```

# Answer
> 30 votes
You can't add extra joins to an `EntityFieldQuery` directly (it's not supported), but you could add a tag to the query, implement `hook_query_TAG_alter()`, and add the join manually when the query is converted down to a standard db query.

This isn't tested but will probably get you most of the way there:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'node_access')
  // etc
  ->addTag('MYTAG');

// get the query results as normal

```

And then the query alter function:

```
function MYDMOULE_query_MYTAG_alter(QueryAlterableInterface $query) {
  $query->join('node_access', 'node_access', 'node_access.nid = node.nid');
}

```

The other way to do it would be to subclass `EntityFieldQuery` itself and add the join, but I think the above method is simpler in this case.

# Answer
> 3 votes
If you're using custom properties with your own tables, the tag method won't work. You need to use subqueries instead:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user');

$roles_subquery = db_select('users_roles', 'ur');
$roles_subquery->fields('ur', array('uid'));
$roles_subquery->condition('rid', $my_role_id);

$query->propertyCondition('uid', $roles_subquery, 'IN');

```

See Need a join in an EntityFieldQuery, how about a subquery? for details.

---
Tags: 7, database
---


# Question
Title: How do I access the loaded comment object?
I'm trying to access the comment field value in controller. With the following code I'm able to access the particular comment object.

```
$comment = \Drupal::entityManager()->getStorage('comment')->load($commentID);

```

When I try print\_r for the $comment variable, I can see the fully loaded comment object.

I understand I cannot access the values by traversing the object since the values are protected. I tried `$comment->get('subject')->value` function, this time its looping and doesn't return any results.

How do I achieve retrieving the value of specific fields associated with comment entity?

# Answer
> 4 votes
It is better to use `kint()` function of the devel module for debugging entities because you will get also a list of available public methods.

You cannot get all comment fields values by looping them as different fields have different array result structure.

Using `$comment = \Drupal::entityTypeManager()->getStorage('comment')->load($commentID)` you get full comment object.

`$comment->get('comment_body)->value` you get comment body value as it uses some text format (eg. full html).

You also can covert comment object to array `$comment = $comment->toArray()`.

---
Tags: 8, comments
---


# Question
Title: How to send an eMail to registered users after they are invited using the Group module?
I use the Group module and the "Ginvite" submodule on Drupal 7.52.

The module allows you to invite people (either registered users or users without an account) to become a member of the group that the invitation is about.

This is what happens after somebody is invited:

* When I write an email in "Invitations by email" and the person is not registered on my site, then the person receives an email invitation.
* when I write an email in "Invitations by email" and the person is already registered on my site, then the person receives an invitation message on the user's account, as shown in this screenprint:

However, I want people who already have a user account, to receive an email notification about that invitation in addition to the invitation (message) on their user account.

How to do this?

# Answer
> 1 votes
You can use the Rules module to achieve that "*people who already have a user account, also receive an email invitation in addition to the invitation on their user account*" (as in your question).

Here is the rule (in Rules export format) to actually do so:

```
{ "rules_send_email_after_inviting_a_registered_user" : {
    "LABEL" : "Send eMail after inviting a registered user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } },
      { "NOT user_has_role" : {
          "account" : [ "group-membership:user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[group-membership:user:mail]",
          "subject" : "You have a pending group invitation",
          "message" : "Hi there!\r\n\r\n[site:current-user:name] has invited you to become a member of the group \u0022[group-membership:group]\u0022 on [site:name].\r\nIf you wish to accept the invitation, you need to login with your existing account first, which is \u0022[group-membership:user:name]\u0022.\r\nPlease visit the following address in order to do so: [site:login-url]\r\n\r\nKind regards,\r\nThe [site:name] team",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "You just invited existing user with name [group-membership:user:name] and eMail Id [group-membership:user:mail] to the group named [group-membership:group].\r\n\r\nAn appropriate message about this invitation just got eMailed to [group-membership:user:name] also." } }
    ]
  }
}

```

Some more details about the magic included in this rule:

* Sending an invitation in the Group module's terminology is equivalent to inserting a new Group Membership with status "`invited`" (how easy can it be?). So that explains the Rules Event I'm using, and the first Rules Condition.
* Since we only want to send such eMail to users who already have an account, the 2nd Rules Condition is to check that the invited user does NOT (!!!) have role anonymous.
* The Rules Action is just to send an appropriate eMail, using specific tokens related to the Group Membership, etc.
* For debugging purposes, the 2nd Rules Action shows a confirmation message about the triggered eMail (feel free to remove that action if you don't like it).

Just import the above rule (using the Rules UI) in your own site, with no customization (changes) needed to see it at work in your own site (don't worry, there is no spyware in the eMail being produced ...).

The eMail content is pretty close to the eMail delivered when inviting anonymous users (the only difference is that it has an instruction to login with their existing account, also included in the eMail body). Here is how a sample eMail body looks like:

```
Hi there!

Pierre.Vriens has invited you to become a member of the group
"Drupal for Sitebuilders" on www.example.com.

If you wish to accept the invitation, you need to login with your existing
account first, which is "Dries.Buytaert".

Please visit the following address in order to do so:
http://www.example.com/user

Kind regards,
The www.example.com team

```

Possibly you may want to finetune the eMail subject, or eMail body. But apart from that no other changes should be needed.

**Voilà** ...

---
Tags: 7, rules, emails, group
---


# Question
Title: How to change the "Add new comment" message for custom comment form?
I have custom content type called *books* that represents a book that can be reviewed by using a custom comment type called *reviews*.

My problem is the comment form title above the comment form shows as "Add New comment", which I need to change as "review the book".

How can I change this to read as "review the book"?

# Answer
The *Add new comment* header is a part of theme layer.

You can copy your theme's existing comment template (e.g. **core/themes/classy/templates/field/field--comment.html.twig** if you're using a theme that utilizes the base classy theme) over to your theme's template dir and rename it to match your specified field (e.g. **field--field-my\_custom\_comment\_machinename.html.twig**). If you're not familiar with this, enable Twig template debugging.

Once you've create a copy of the template, you can then edit template header as you see fit.
> 3 votes

# Answer
You can implement the `template_preprocess_field__comment()` hook in your custom module:

```
/**
 * Implements hook_preprocess_field__comment().
 */
function MY_MODULE_preprocess_field__comment(&$variables) {
  switch ($variables['field_name']) {
    //field_message_custom is your custom comment field name
    case 'field_message_custom':
      $variables['add_new_comment'] = t('Review the book');
      break;
    default:
      $variables['add_new_comment'] = t('Add new comment');
  }
}

```

And now you change use the `add_new_comment` variable in your field--comment.html.twig this line:

```
<h2 class="title comment-form__title">{{ 'Add new comment'|t }}</h2>

```

for this line:

```
<h2 class="title comment-form__title">{{ add_new_comment }}</h2>

```

**After this clean your cache.**

It seems that we will be able to change this message in the interface in Drupal 8.3. Read: You can add a review, opinion, greeting, etc. comment type but not change the "Add new comment" text
> 2 votes

---
Tags: theming, 8, comments
---


# Question
Title: I get notification for TB Sirate Starter update despite that I use new fresh drupal installation
I get notification for TB Sirate Starter update despite that I use new fresh drupal installation, never setup TB Sirate Starter. This repeated many times and on many of my new drupal project.

I only tested it in the past on my local server. But I always setup fresh and clean drupal installation.

Is there any soultion

# Answer
> 1 votes
Despite not using the distribution any more I keep getting the message to update TB Sirate Starter

====================================

I had this issue before and yes, I took notes. In my case it was solved by finding the culprit(s). They were **jquery\_plugin** and **jquery\_update**

```
# grep -r "tb_sirate_starter" .
./sites/all/modules/jquery_plugin/jquery_plugin.info:project = "tb_sirate_starter"
./sites/all/modules/jquery_update/jquery_update.info:project = "tb_sirate_starter"

```

The fix / workaround?

I deleted the directories jquery\_plugin/ and jquery\_update/

Then reinstalled them.

```
# grep -r "tb_sirate_starter" .
#

```

No more messages "Update Available - TB Sirate Starter " And I think this is what the OP asked :)

---
Tags: updating, notifications
---


# Question
Title: How to hide/show view based on field's value?
Problem: I have a user directory that anyone can access, with pages for each user. However, there is a view (that's a block) with personal info that I only want shown to the user who's page it is, or users with an admin role. They are not the authors of the page. I know how to fix the admin role issue, and how to get the username using php, but not how to get the field containing the username of the person who owns the page. I can't use Views PHP, just Views. Thanks!

**EDIT:** I tried doing something where in the view's header I had

```
if ($current_user == "[field_user_name]") { ?>

```

Then in the footer of the view:

```
<?php } ?>

```

But that hasn't worked.

# Answer
Okay, I think I got it now. Already tested.

1. Override the view's template (Tutorial)
2. Include `global $user;` somewhere in the first php tag.
3. Use an if statement: `<?php if (strip_tags($view->render_field("YOUR_FIELD", $id)) == $user->name): ?>` with `YOUR_FIELD` as the field's replacement pattern without brackets. (remember the `<?php endif; ?>`)

Sample view template (for unformated view display):

```
<?php

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

```
> 1 votes

# Answer
The Rules block visibility module may possibly be an alternative. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

Moreover, as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you have the power of Rules available to implement all sorts of custom logic (cfr. the "programmatically / custom module" part of your.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
> 0 votes

---
Tags: views, users
---


# Question
Title: Which permission is associated with variable_set()?
It seems that only site administrators can use `variable_set()`. If this is truly the case, is there a special permission that grants `variable_set()` function to site administrators?

# Answer
There is no permission associated to using `variable_set()`. Permissions are associated to pages, and not having a specific permission doesn't allow to see those pages; associated to part of the page, and not having a specific permission doesn't allow to see that specific part of the page; or associated to an action, and not having a specific permission doesn't allow to do/start that action.

There could be a module that checks the currently logged-in user has a permission before saving some data with `variable_set()`, but that doesn't mean every call to `variable_set()` needs the user to have a specific permission. `variable_set()` doesn't even check for any user permission.

As for what done from Drupal core and its modules, none of the functions calling `variable_set()` that aren't part of tests use code similar to the following PHP pseudo-code.

```
if (user_access($permission)) {
  variable_set($key, $value);
}

```

This means that, for example, in a form submission handler for a setting page used by Drupal core, the settings will be saved independently from the user permissions the logged-in user has. That user has the permission to see that setting page, though.
If you are noticing that setting values for a form are saved just when the user is administrator, and that happens also for setting pages handled by Drupal core modules, then there is something wrong happening.
> 2 votes

---
Tags: users, configuration
---


title: Retrieve newly created Term tid

text:
# Question
Title: Retrieve newly created Term tid
I've created a PHP program outside Drupal that inserts Terms into my Drupal installation.

```
define('DRUPAL_DIR', __DIR__);

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

$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

$term = \Drupal\taxonomy\Entity\Term::create([
      'vid' => 'subject',
      'langcode' => 'en',
      'name' => 'Test af Tag',
      'description' => [
        'value' => '<p>My description.</p>',
        'format' => 'full_html',
      ],
      'weight' => -1,
      'parent' => array(0),
])->save();

var_dump($term);

```

My question is - how do I retrieve the newly created Term tid? The var\_dump only gives a

> string(9) "SAVED\_NEW"

Why on earth doesn't it return the newly created Entity/Term?!?

I need it in case there will be a child Term later. I've looked at www.drupal.org/documentation and api.drupal.org. But those pages just confuses me more :-(

Thank you very much

# Answer
> 12 votes
> Why on earth doesn't it return the newly created Entity/Term?!?

Why would it? You already have the term object, why do you need it to be chained in a return from a save method that can and does provide you with extra context??

Just use this:

```
$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => 'subject',
  'langcode' => 'en',
  'name' => 'Test af Tag',
  'description' => [
    'value' => '<p>My description.</p>',
    'format' => 'full_html',
  ],
  'weight' => -1,
  'parent' => array(0),
]);

$inserted_or_updated = $term->save();

$tid = $term->id();

```

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


# Question
Title: What's the side-effect of changing the file directory setting of a file field which already has contents?
Before, the "file directory" setting of a file field in a bundle is set as "field/file". Now, I want that every user uploads his files into own directory, so I need to add a token in the "file directory" setting. But I'm afraid that the files uploaded in the old nodes can still show normally? If not, how to fix it?

# Answer
> 2 votes
Those files will still be shown normally unless you remove their directory manually, because the file path is stored in the database with each file information. So even when you change the folder for new files, the old ones will still know the path where they were uploaded.

---
Tags: files
---


# Question
Title: Error trying to update database after module update
After I update a module, and click at http://omroepzuidplas.nl/admin/update/ready on the 'run' button to do the database updates. Drupal sends me to this url:

http://omroepzuidplas.nl/http%253A//omroepzuidplas.nl/authorize.php%3Fbatch%3D1?op=start&id=2796

Which result in an 404 page not found error.

I use Drupal 7.50 on CentOS7.

# Answer
> 0 votes
The problem you are having is likely either that the `RewriteBase` is not set in .htaccess, or the `base_url` is not set in settings.php. Likely you can bypass the settings problem if you go directly to http://omroepzuidplas.nl/update.php.

To do database updates you have to be logged in as User 1 (often called admin or super admin, but it could have any user name).

---
Tags: 7, updating
---


title: Adding action to textarea

text:
# Question
Title: Adding action to textarea
I am hoping that this enquiry will be a easy one for someone to help shed some light on... I know that in order to create a textarea in Drupal 8 the following code can be used (e.g. render array)

```
$the_textarea=array(
        '#type' => 'textarea',
        '#required' => FALSE,
        '#ajax' => array (
            // Function to call when event on form element triggered.
            'callback' => array($this->componentCallbackObject,$this->componentCallbackFunction),
            'event' => $this->componentEvent,
        ),
    );

```

In the above code, a callback is defined using ajax ... this has the result of the code requiring the client to communicate with the server, which then sends back instructions to the client side using ajax... Is there away to get a component to execute some javascript (where the javascript would be loaded when the page in question, first loads) and when either the upkey, downkey or onchange event is triggered for the textarea the javascript, which would already be available to the client would be executed.

The main point here is that the client wouldn't need to communicate with the server, just with the javascript which is loaded when the page first loads e.g. without having to callback to the server and then wait for the server to send back the information.

# Answer
> 1 votes
The technique you need is easy, the full details can be complicated (depending on exactly what you want the JS to do). You can attach a custom JavaScript file from without your module in three steps:

1. Create the JS file.
2. Define a library.
3. Attach the library to the form element.

The JavaScript should typically live in a folder named `js` at the root of your module: `js/my-great-jscode.js`.

To create your library add a \[module\_name\].libraries.yml file to the root of your custom module. In there define the library:

```
my-library:
  version: 1.x
  js:
    js/my-great-jscode.js: {}

```

Then to attach the code to your form element you add `#attached => library` to the render array.

```
$the_textarea=array(
  '#type' => 'textarea',
  '#required' => FALSE,
  '#ajax' => array (
  // Function to call when event on form element triggered.
  'callback' => array($this->componentCallbackObject,$this->componentCallbackFunction),
  'event' => $this->componentEvent,
  ),
  '#attached' => [
    'library' => [
      'my-module/my-library',
    ],
  ],
);

```

There is more detail in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module on Drupal.org

# Answer
> 0 votes
> The main point here is that the client wouldn't need to communicate with the server, just with the javascript which is loaded when the page first loads e.g. without having to callback to the server and then wait for the server to send back the information.

That is not AJAx, that's just plain javascript. So you shouldn't use the #ajax system for if that's not what you want. Keep in mind that using ajax is a must if you need to change the form, because Drupal will not accept form elements that it didn't provide.

There's also the #states API, see https://randyfay.com/states. It allows some basic client-side changes, like making form elements visible based on another element/selection, showing them as required (note that you still need to do server-side validation yourself too) and so on.

And if that's not enough, then sure, you can always write your own JS, add that using libraries.yml and #attached and do whatever you want there. You might also need to look into using drupalSettings to dynamically pass configuration (like the name of your form element if it is not hardcoded) to your JS, so it knows what to do.

---
Tags: 8, forms
---


# Question
Title: Taking node map from /map/node and using it on home page
I need a google map block which would show all the nodes' location with markers. I noticed that Location module has this built in if I follow `/map/node` url. My question is, can I somehow take this map block and use it on my home page? Add it through blocks interface or by page components?

# Answer
Just create an appropriate view, give that view some path that you like, and set that path as your homepage. To actually create such view with the kind of data your question is about, have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.
> 1 votes

---
Tags: 7, location, google-maps
---


# Question
Title: How to delete all Persistent variables when a page is loaded?
I have many variables set through variable\_set. Is there any other way to delete them all at once apart from variable\_del?

or How can find all the persistent variables set in the module?

# Answer
It is considered bad practice to delete all the persistent variables whose name starts with the short name of the module. There could be a module whose short name starts with that short name; in that case you would be removing the persistent variables of that module.
For example, given the Views module, there could be a Views Enhancer module. Deleting all the persistent variable matching the SQL pattern `'%views_%'` would mean deleting the persistent variables of both modules.

Instead, you should have a list of all the persistent variables your module uses. (That is not hard, since you are writing the code of your module.) Using that list (for example, contained in `$variables`), a code like the following would delete all the variables.

```
  global $conf;

  db_delete('variable')
    ->condition('name', $variables, 'IN')
    ->execute();
  cache_clear_all('variables', 'cache_bootstrap');

  foreach ($variables as $name) {
    unset($conf[$name]);
  }

```

This is, essentially, the code of `variable_del()` adapted to delete a list of variable names contained in `$variables`.

You could also use that code to implement a function your module uses.

```
function variable_delete_multiple(array $variables) {
  global $conf;

  db_delete('variable')
    ->condition('name', $variables, 'IN')
    ->execute();
  cache_clear_all('variables', 'cache_bootstrap');

  foreach ($variables as $name) {
    unset($conf[$name]);
  }
}

```
> 2 votes

# Answer
You can always use MySQL to delete persistent variables set by variable\_set:

`delete from variable where name like '%module_name_variable_name%';`

but assuming that you want to delete those variables on every page load consider another way to implement your code than using variable\_get which is using the caching system
> 0 votes

---
Tags: 7, configuration
---


# Question
Title: How to sort randomly two or more nodequeues in Views but keeping nodes position?
I've got 3 nodequeues:

Nodequeue A

* Item 1
* Item 2
* Item 3

Nodequeue B

* Item 4
* Item 5
* Item 6

Nodequeue C

* Item 7
* Item 8
* Item 9

Does anyone know how to sort these nodequeues in Views (randomly) but keeping the nodequeue position of every node within its nodequeue?

For example:

Nodequeue A, Nodequeue C, Nodequeue B
Nodequeue B, Nodequeue C, Nodequeue A

But items inside every nodequeue stay, based on its original position.

# Answer
> 0 votes
I finally got the solution. It's just about grouping nodequeues.

At fields, select "Nodequeue ID" field. Then you can group by this field at Format options.

To mix nodequeues without altering the nodes sorting within the queue just sort by:

* Nodequeue: Position (to keep queue order)
* Global random (only nodequeues blocks will be mixed)

I hope this helps.

---
Tags: 7, views, nodes
---


# Question
Title: Alter entity.user.canonical (/user/{uid}) route
When a user (e.g. nid = 37) goes to some other user's profile page at a url like /user/1, /user/2, ..., /user/n, I want automatically redirect them to their own: /user/37 page.

How can I do properly this with Drupal 8?

I think I must create a custom Controller Class and configure the default drupal route (/user/{uid}) adding my custom Controller, but I don't know how can I do this.

# Answer
> 3 votes
There are at least two ways you could pursue to do what you're trying to achieve:

1. You can alter routes using a RouteSubscriber.
2. Listen for a event (likely KernelEvents::REQUEST), and respond appropriately.

The RouteSubscriber is probably a bit hard to do (I haven't written one yet, I just discovered their existence the other day), but is more in keeping with the older `hook_menu_alter` patterns from previous versions of Drupal.

The EventSubscriber is probably easier to write once you understand the event system (which requires some learning but is where lots of the future of Drupal internals is headed).

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


title: Can't install DRUSH

text:
# Question
Title: Can't install DRUSH
I upgraded my system from Ubuntu 14 to Ubuntu 16.10 and suddenly i can't find the drush command.
I wanted to install it via `apt install drush` but this is not working and sent me this error:

```
 Reading package lists... Done
Building dependency tree
Reading state information... Done
Package drush is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package drush has no installation candidate

```

Is there any solution for that? Thank you

# Answer
I found that on the drush documentation:

```
php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush
php drush core-status

chmod +x drush
sudo mv drush /usr/local/bin
drush init

```

And it's working, Thank you very much..
> 0 votes

---
Tags: drush, installation
---


# Question
Title: Field_image empty after database export and import
I exported my previous D7 database (db1), and imported it into a new database (db2). That said, all of my data (pages, articles, content, etc) seems to have exported the way it should... EXCEPT for the images attached to my articles. Now when I navigate to an article, what was uploaded to my field\_image previously is now a broken link (even though the fid in my database seems to be correct). Does anyone know why this might be or how I can fix it?

**If it helps, this is the error message I get on the screen as well:**

> Warning: array\_key\_exists() expects parameter 2 to be array, null given in theme\_image\_formatter() (line 605 of /modules/image/image.field.inc)

When I right click on the broken image and attempt to "show image address", it simply gives me my domain name. E.g. mydomain.com, and no real path to an image. Not sure if that matters.

# Answer
I am assuming that the Images are showing as uploaded in the backend. But when trying to view it on the front it is coming broken. you can check the file system path in the drupal admin it should be sites/default/files

if the file path is not the issue, then look at here(https://www.drupal.org/node/920840) there was a thread going around the warning and seems to be resolved. #22 could be the solution to look.
> 0 votes

---
Tags: 7, entities, media
---


title: Theme search block

text:
# Question
Title: Theme search block
I want to theme the default search block to a bootstrap search bar.

When I create the searchbar in html it looks like:

```
<div class="input-group">
                    <input type="text" class="form-control" placeholder="Search for...">
                    <span class="input-group-btn">
                      <button class="btn btn-default" type="button">Go!</button>
                    </span>
                  </div>

```

I tried already changing the input--search.html.twig file to:

```
{% set classes = ['form-control',] %}

 <input {{ attributes.addClass(classes).setAttribute('placeholder', 'Search for...').setAttribute('type', 'text') }} />{{ children }}

```

and block--search-form-block.html.twig to:

```
<div class="input-group">
{{ content }}

                    <span class="input-group-btn">
                      <button class="btn btn-default" type="button">Go!</button>
                    </span>
                  </div>

```

But nothing does change the layout as expected. Is there some easy way to change the layout of the default search block?

# Answer
Found a dirty way to fix my problem. Because Drupal 8 creates the search form on a special way, I changed my form.html.twig manually.

```
{% if element['#form_id'] == 'search_block_form' %}

  <form action="{{element['#action']}}" method="get" id="search-block-form" accept-charset="UTF-8" data-drupal-form-fields="edit-keys">
    <div class="input-group">
      <input title="Enter the terms you wish to search for." data-drupal-selector="edit-keys" type="text" id="edit-keys" name="keys" value="" size="15" maxlength="128" class="form-search form-control" placeholder="Search for...">
      </input>
      <span class="input-group-btn">
        <input data-drupal-selector="edit-submit" type="submit" id="edit-submit" value="Search" class="btn btn-default js-form-submit submit-button">
        </input>
      </span>
    </div>
  </form>
{% else %}

  <form{{ attributes }}>
    {{ children }}
  </form>

{% endif %}

```
> 4 votes

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


title: Add a "view in JSON" local task

text:
# Question
Title: Add a "view in JSON" local task
How can I add a *Preview in JSON* local task?

My link is exactly the same of entity.node.canonical, but I have to add a query string (?\_format=json). I know how to add the local task, but I don't know how to append the query string to the URL.

# Answer
You need to configure URL options in links.task.yml file. See Url::fromUri for details.

```
your_module.export:
  title: Export
  route_name: entity.node.canonical
  options:
    query: {_format: json}
  base_route: entity.node.canonical

```
> 1 votes

---
Tags: 8
---


# Question
Title: How to changing Bartik's "Show - Main navigaton" mobile menu message?
When you install Bartik and minimize your browser to mobile display you can see the caption "*Show - Main navigaton*":

I want to translate it to Hebrew so I went to `admin/config/regional/translate` and typed the stream to change it but found nothing so I guess it's hardcoded somewhere.

Yet, I searched in page.html.twig and menu-block twig but didn't find this stream. I also didn't find CSS language-construct (as in `content:x;`).

You might know where this stream is located or at least answer with a good way to search it?

# Answer
> 3 votes
You can translate following strings through the core translation system (`admin/config/regional/translate`):

* `Show — @configuration.label`
* `Hide — @configuration.label`

The strings above are defined in `block--system-menu-block.html.twig` at line 17 and 18.

Furthermore you should translate/rename your Main menu name.

---
Tags: theming, navigation
---


# Question
Title: Automated login with LDAP always returns error
I have successfully setup LDAP module to authenticate users (and create new users). This is done through manual login form. Now I'm trying to enable automated single sign-on, but with no luck.

I have enabled LDAP SSO, and selected **Turn on automated single sign-on**.

On IIS, I've enabled Windows Authentication (Anonymous is still enabled).

I do not get automatically logged in, it returns error msg "You were not authenticated by the server. You may log in with your credentials below".

What else needs to be configured in a Windows environment to enable SSO?

Does anyone have any insight on what the reference info is talking about, when the say "This requires that you have operational NTLM or Kerberos authentication turned on for at least the path /user/login/sso, or for the whole domain" ? Other than looking at Windows Authentication on IIS, enabled providers = NTLM, what else needs configuring?

# Answer
Perhaps not a direct answer to you question about the LDAP module but I managed to enable SSO in a Windows domain environment with the Webserver authentication (https://www.drupal.org/project/webserver\_auth) module.

You need to force Windows Authentication in your IIS site and disable Anonymous authentication. The Webserver authentication module is also capable of creating accounts when a Windows Domain user is visiting your site and is not registered in Drupal.
> 0 votes

---
Tags: users, authentication-authorization
---


title: Loading and deleting a cache item

text:
# Question
Title: Loading and deleting a cache item
I have a render array I'm caching as follows:

```
$build['friend_link'] = [
  '#type' => 'item',
  '#markup' => $link,
  '#cache' => [
    'keys' => ['friendship', $user->id()],
  ],
];

```

I need to delete this cache when the friendship is invalidated. However, I'm having a lot of troubles with retrieving the cache in order to invalidate it. I'm attempting to use the following code to retrieve the cache item:

```
$render_cache = \Drupal::cache('render');
$render_cache->get('friendship:' . $friend->id()); // id = 4

```

However, this doesn't work, because the actual cache key in the DB is:

```
friendship:4:[languages:language_interface]=en:[theme]=bartik:[user.permissions]=80e4ddd871aca07e035f618b532bc75cb7c155caaaedd08a4ae17e5e137ca30f

```

I tried setting the cache contexts to an empty array:

```
'#cache' => [
  'keys' => ['friendship', $user->id()],
  'contexts' => [],
],

```

But this didn't change the key. So I set the contexts to a value:

```
'#cache' => [
  'keys' => ['friendship', $user->id()],
  'contexts' => ['user'],
],

```

This changed the key to:

```
friendship:4:[languages:language_interface]=en:[theme]=bartik:[user]=1

```

So while this does make it potentially easier to build the key manually, it seems like I'm missing something.

I did find RenderCache::createCacheID(), however it's protected so I can't call it.

I'm at a bit of a loss here, is there an API function I'm missing somewhere to retrieve the cache?

# Answer
> 4 votes
What exactly is a "friendship"? You most likely want to use cache tags for invalidation.

One way to do that would be to add the cache tag for the user, then you just have to make sure that you are invalidating that user cache tag. So you add `'tags' => $user->getCacheTags()`, and when the friendships of a user change, you use `Cache::invalidateTags($user->getCacheTags())`. The downside is that this will invalidate too much: It will invalidate all content where the user is displayed, e.g. if he's the author of an article.

You could define your own cache tag; they're really just strings and invalidate just that, e.g. `'tags' => ['friendships:' . $user->uid]` and then invalidate that.

Cache contexts are for variations of the same cache entry; it's exactly those things you see in the cache key. Having `$user->id()` in the cache keys and the user context is practically the same thing. You can do either or the other; you don't need both. (Cache context user and keys just 'friendships' would be the same as what you have now.)

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


# Question
Title: How to avoid certain variables from being cached?
I've spent days trying to figure this out and really hope you guys can help me out here.

Let's say, I’ve created a list field on the user entity called `field_render_array` with the options:

* Render array 1
* Render array 2

There is a controller called `RenderArray` which should:

* Return render array 0 if `field_render_array` is not set.
* Return render array 1 if `field_render_array` is equal to `render_array_1`.
* Return render array 2 if `field_render_array` is equal to `render_array_2`.

I’ve been trying to achieve this using a controller like:

```
<?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

class RenderArrayController extends ControllerBase {

  public function content() {
    $user = \Drupal::currentUser();
    $field_render_array = $user->get(‘field_render_array’)->value;

    if (!isset($field_render_array)) {
      return array(
        ‘#markup' => ‘You haven’t set your preferred render array.',
      );
    }
    else if ($field_render_array == ‘render_array_1’ ) {
      return array(
        ‘#markup' => ‘Your preferred render array is 1',
      );
    }
    else {
      return array(
        ‘#markup' => ‘Your preferred render array is 2’,
      );
    }
  }

}

```

The problem is that the value of `$field_render_array` is getting cached. This comes across as a bug for end-users as the render array doesn’t immediately change after changing the value of `field_render_array`.

Is it possible to somehow avoid certain variables from being cached or is there another solution to achieve the same thing?

# Answer
> 3 votes
If the variables come from the current user, then add this cache context to the build array you return:

```
$build['#cache']['contexts'][] = 'user';

```

# Answer
> 0 votes
To solve this problem I decided to reduce the number of render array's from 3 to 1.

```
<?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

class RenderArrayController extends ControllerBase {

  public function content() {
    $user = \Drupal::currentUser();
    $field_render_array = $user->get('field_render_array')->value;

    if (!isset($field_render_array)) {
      $markup = 'You haven’t set your preferred render array.';
    }
    else if ($field_render_array == 'render_array_1' ) {
      $markup = 'Your preferred render array is 1';
    }
    else {
      $markup = 'Your preferred render array is 2';
    }

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

  }

}

```

As the `field_render_array` can always change, I added `'#cache' => ['max-age' => 0]` to the render array left. See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for more information.

---
Tags: 8, caching
---


title: How to get the name of a field?

text:
# Question
Title: How to get the name of a field?
I'm on `hook_form_alter` for the config edit form. The code runs for all fields, but it's critical that the code figures out the name of the field it is on.

When I load the formobject, I can see the `field_name` perfectly when I `print_r` the array. But I can't figure out how to pull it out. Something like `$name=$field['field_name']`

The field name is 'field\_plan\_purpose' I need to get that in a variable in the code.

My code minus all of things I've tried:

```
$field = $form_state->getFormObject()->getEntity();
print '<pre>';
print_r($field);
print '</pre>';

```

Here is the top part of the array that gets printed:

```
Drupal\field\Entity\FieldConfig Object
(
    [deleted:protected] =>
    [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
        (
            [id:protected] => node.field_plan_purpose
            [field_name:protected] => field_plan_purpose <--- HOW DO I GET THIS
            [entity_type:protected] => node
            [type:protected] => text_long
            [module:protected] => text
            [settings:protected] => Array
                (
                )

            [cardinality:protected] => 1
            [translatable:protected] => 1
            [locked:protected] =>
            [persist_with_no_fields:protected] =>
            [custom_storage] =>
            [indexes:protected] => Array
                (
                )

            [deleted:protected] =>
            [schema:protected] =>
            [propertyDefinitions:protected] => Array
                (...

```

As you can see, 'field\_name' is in there. Does anyone know how I can pull that out and reference it directly?

A few things I've tried:

```
    // print_r($field->getEntityKey('#field_name'));
    // getEntityType()->getKey('field_name')
    // $field['field_name']  $field['field_name:protected']
    // $field['id']
    // $field->getKey('field_name')
    // $field->definition['field_name'];
    // print_r($field->definition);

```

EDITED \******* SOLUTION

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   $field = $form_state->getFormObject()->getEntity();
   $field_name = $field->getName();
   print $field_name;

}

```

# Answer
> 7 votes
`FieldConfigBase` has a method named `getName()`. That will retrieve the field name:

```
public function getName() {
  return $this->field_name;
}

```

---
Tags: 8, entities
---


# Question
Title: How to add a catch-all wildcard to hook_menu?
I want a url structure like so:

```
https://example.com/bob

```

which loads a custom page for the user bob. This is what I'm trying:

```
function mymodule_storefront_menu() {

    $items = array();

    // Wildcard catch for user's storefront
    $items['%'] = array(
      'title'           => 'User custom page',
      'type'            => MENU_CALLBACK,
      'page callback'   => 'mymodule_load_user_page',
      'page arguments'  => array(0),
      'access callback' => TRUE,
    );

    return $items;
}

function mymodule_load_user_page($user) {
    echo $user;
}

```

However, I'm getting a server 404 and drupal is logging a 'page not found' message the the dblog. Any ideas?

Edit:

I am able to get this to work:

```
$items['u/%'] = array(...);

```

but would prefer the plain wildcard to work, if possible.

# Answer
The documentation for `hook_menu()` says it in the first wildcard example it provides. (Emphasis is mine.)

> ## Wildcards in Paths
>
> ### Simple Wildcards
>
> Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':
>
> ```
>   $items['my-module/%/edit'] = array(
>     'page callback' => 'mymodule_abc_edit',
>     'page arguments' => array(1),
>   );
>
> ```
>
> When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. **Note that wildcards may not be used as the first component.**

The reason of this is pretty easy to understand: A wildcard as first component would be a catch-up for every Drupal route.
It would also conflict with the routes every Drupal module defines. This is also the reason why Drupal core uses node/%node for nodes, and user/%user for user accounts: Despite the wildcards being qualified, Drupal would not understand if a URI like 1 is referring to a node or a user account.
> 3 votes

# Answer
Wildcards may not be used as the first component of a route path.
> 2 votes

---
Tags: 7, navigation
---


# Question
Title: Title link doesn't change after the content type has been changed
The title link for a view block doesn't change after the content type has been changed.

Title "Video" links to http://example.com/video.

>

After changing the title to "Entertainment" and the content type to "Entertainment", the "video" title has changed to "Entertainment" but the link still link to http://example.com/video.

# Answer
> 1 votes
> For title, try putting `<a href="/entertainment">Entertainment</a>`
>
> Thanks @No Sssweat.

---
Tags: views
---


# Question
Title: How do I show the current node title in page.html.twig OR in node.html.twig?
If I want to show the current node title in page.html.twig (by default it seems to only be available in node.html.twig) I have to create a preprocess function like so:

```
function theme_preprocess_page(&$variables, $hook) {
  // Set our page title so we can access it in page.html.twig
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['my_node_title'] = $node->title->value;
  }
}

```

And then I have to overwrite page-title.html.twig by copying it into my current theme folder and commenting out everything.

This doesn't seem "right". Is there a better way?

# Answer
> 27 votes
The node is already available in the page template thanks to `template_preprocess_page`, so there's no need for the preprocess function. You can output the title with:

```
{{ node.label }}

```

The page title itself is a block, so if you don't need it any more just remove it from the region at /admin/structure/block. No need to copy the template to your theme or alter the original.

# Answer
> 3 votes
You can add below codes to top of `node.html.twig` in templates folder of your theme :

```
{% if not page %}
  <h2{{ title_attributes }}>
    <a href="{{ url }}" rel="bookmark">{{ label }}</a>
  </h2>
{% endif %}

{% if page %}
  <h2{{ title_attributes }}>
    {{ label }}
  </h2>
{% endif %}

```

# Answer
> 2 votes
The Drupal 8 code for doing what the code you shown should do is the following one.

```
function theme_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  if ($route_match->getParameter('node')) {
    $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
    $variables['my_node_title'] = $page_title;
  }
}

```

---
Tags: theming, 8
---


# Question
Title: Why are the commands implemented by a custom module still listed after uninstalling it?
I registered a new command via Drupal Console using `drupal generate:command`. I associated the command with a custom module, but after uninstalling the module and removing the module folder, the command still appears when issuing a `drupal list` command. I couldn't find anything in the Drupal Console documentation relating to this.

How do I let Drupal Console know my module is being uninstalled, so that it doesn't list its commands anymore? Does the module needs to implement a specific method for that, or do I need to run a Drupal Console command for this?

# Answer
Problem solved. Issuing `drupal module:uninstall my_module` removes the command from the Drupal Console command list.
> 0 votes

---
Tags: 8, console
---


# Question
Title: Is it safe to use $_SESSION to store temporarily a user provided value under multi-step form processing
I have a form which contains an AJAX button press callback. Upon pressing this AJAX button, I want to store temporarily a form element's value before fully processing all the data upon pressing main form submimission button. On the meanwhile, how do I store that particular field value? Is it fine to achieve this using `$_SESSION`? Is this secure? Does it work flawlessly under Drupal 7, or is there a better alternative?

# Answer
> 2 votes
Since `$form_state` is passed by reference to the form builder and to the form validation/submission handlers, and to the AJAX callback, in this case you can just use `$form_state`. It is not passed to the browser, but stored in the database, so there are less chances its content could be altered by malicious code. (This doesn't mean the content of `$_SESSION` is less secure.)

Traditionally, `$form_state['storage']` was used to contain all those values a module needed to temporary storage, but see what `drupal_build_form()` says. (Emphasis is mine.)

> **storage**: `$form_state['storage']` is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, **especially in a multi-step-style form**. Form implementations may use any key(s) within `$form_state` (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses `$form_state['node']` in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

# Answer
> 2 votes
Drupal has an Ajax framework for this use case. Use $form\_state to store values. The API page about the Ajax framework contains a use of $form\_state.

---
Tags: 7, forms, ajax, security, sessions
---


title: Why is UUID column VARCHAR(128)?

text:
# Question
Title: Why is UUID column VARCHAR(128)?
Just wondering if anyone knows why `uuid` columns created by Drupal 8 in MySQL are of type `VARCHAR(128)`, not `CHAR(36)`?

# Answer
> 3 votes
Basing on this comment by Damien Tournoud, the idea was to support arbitrary string identifiers.
Since Drupal uses a service to generate UUIDs, using a `VARCHAR(128)` as database field for the UUID would allow a module to override the current service with one using a different implementation, and using more bytes for the UUID.

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


title: Getting error while joining two tables

text:
# Question
Title: Getting error while joining two tables
Here is query which is, I am using

```
$query = db_select('users','u');
$query->join('users_roles', 'u.uid = users_roles.uid'); // JOIN users_roles with users
$query->fields('users', array('name','uid')) // SELECT the field name from users
    ->condition('users_roles.rid', 5);

  $results = $query->execute();

```

Actually i want the user name and id for that those user who are under role id = 5

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1066 Not unique table/alias: 'u': SELECT users.name AS name, users.uid AS uid FROM {users} u INNER JOIN {users\_roles} u.uidusers\_roles.uid WHERE (users\_roles.rid = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 5 ) in user\_assign\_list() (line 80 of C:\xampp\htdocs\nic\sites\all\modules\user\_assign\user\_assign.module).

This error shown on the browser. Actually i am creating the custom module file for this requirement. Is there any need to include sql connection for those custom module? here is .module file

```
<?php
function user_assign_permission() {
  return array(
    'submit user_assign' => array(
      'title' => t('Submit user_assign'),
      'description' => t('Submit the user_assign form'),
    ),
    'access user_assign list' => array(
      'title' => t('Access user_assign list'),
      'description' => t('Access the user_assign submissions'),
    ),

  );
}
function user_assign_menu() {
  $items = array();

   $items['users-list'] = array(
    'title' => t('User Assign'),
    'page callback' => 'user_assign_list',
    'access callback' => TRUE,
    'access arguments' => array('access user_assign list'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function user_assign_theme($existing, $type, $theme, $path) {
  return array(
    'user_assign_function' => array(
      'variables' => array('rows' => NULL),
    ),
    'user_assign_template' => array(
      'variables' => array('rows' => NULL),
      'template' => 'user_assign_template',
    ),

  );
}

function theme_user_assign_function($variables)
{
    $output = '';

//   print_r($variables);
    foreach($variables['items'] as $row) {

     $output .= '<div class="views-row"><div class="do_featured">
   <div class="do_title">
    <span>    <div class="field"><div class="field-items">'.$row[1].'&nbsp'.$row[2].'</div></div>
    </span>
   </div></div>';

    }

    return $output;
}

function user_assign_list() {
 // $query = db_select('users', 'n');

//  $query->condition('n.empname', '%' . db_like($_GET['empname']). '%','LIKE');

 // $query->fields('n', array('fe_id', 'empcode','empname','empphoto','empemail','empdesignation'))
  //    ->limit(4)
  //    ->addTag('node_access')
  //    ->groupBy('n.fe_id');
$query = db_select('users','u');
$query->join('users_roles', 'u.uid = users_roles.uid'); // JOIN users_roles with users
$query->fields('users', array('name','uid')) // SELLECT the field name from users
    ->condition('users_roles.rid', 5);

  $results = $query->execute();
     $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->uid,
        $result->name,
        );

  }
  $output = theme('user_assign_function', array('items' => $rows));
  return $output;
}

?>

```

# Answer
> 1 votes
Hi Sumit check the below query and it not showing any error.

Use Query coder module to create any query in drupal format

Query coder Convert SQL query to Drupal Database abstraction layer code.

$query = db\_select('users','u');

$query-\>join('users\_roles', 'r', 'u.uid = r.uid'); // JOIN users\_roles with users

$query-\>fields('u', array('name','uid')) // SELECT the field name from users -\>condition('r.rid', 5);

$results = $query-\>execute(); $rows = array();

foreach($results as $result) {

```
$rows[] = array(
    $result->uid,
    $result->name,
    );

```

}

---
Tags: users, database
---


title: Filter criteria works on first value

text:
# Question
Title: Filter criteria works on first value
I am working on a view where I need to show publications (a content type) in which authors (another content type) should be active (have a specific value for one of their fields).

I am using a relationship to add the fields for the node authors, and then add a filter criteria for checking if they are active or not. It is working in a way that is not what I want. It shows all the publications which has at least one active user (and maybe some other inactive users), but I want to have the ones in which all of authors are active.

What am I getting wrong here? could you please help me?

# Answer
### Step 1

To have such a list of authors that can be referenced, you should ***first*** (repeat: ***first***) create a view (with the Views module) to create a list of all the authors that are allowed to be selected. And the display type of such view must be an *Entity Reference* display.

### Step 2

Your select box field (to select from a filtered list of authors) should be field that looks like so:

* Field Name = Anything you want, eg `field_authors_list`.
* Field Type = Entity Reference, using these additional settings for it:

+ *Target type* = `node`
    + *Number of values* = `1`, though something like "unlimited may do as well (not clear to me from your question).
    + "Mode" (within "entity selection") = `Views: Filter by an entity reference view`. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an *Entity Reference* display, or add such a display to an existing view. In your case, you should select the view created in "Step 1".
    + Pick any of the other options to define this field as you see fit.

### Step 3

If the list of authors you can select (after completing the previous 2 steps) is not exactly what you want, eg "*you want to have the ones in which all of authors are active, whereas active means 'have a specific value for one of their fields'*" (as in your question), then refine/tune the view in step 1 so that the Views results do match with what you want the list to look like.
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: Classes to differentiate between different status messages?
After enabling my custom theme, I noticed that while Drupal adds special classes for different status messages being put out by the `drupal_set_message()` function, e.g. messages and messages--status. However, when I use `drupal_set_message()` in my module, the messages get displayed but no classes are added to the container that is displaying these messages, thus it makes them hardly stylable.

I've been looking for a solution but no site I've been able to find mentiones this. Is this a bug or am I doing something incorrectly?

Thanks a lot in advance.

# Answer
> 1 votes
I've been looking around in core a bit and found a solution from the classy theme. Copying its status-messages.html.twig file to my theme solves the problem since the type classes for each message are being set there.

```
{{ attach_library('classy/messages') }}
{% block messages %}
{% for type, messages in message_list %}
    {%
    set classes = [
    'messages',
    'messages--' ~ type,
    ]
    %}

```

I think this logic in views is a bit weird.

---
Tags: theming, 8, debugging
---


# Question
Title: How to exclude product variations from product teaser display?
I am developing an online shopping website using Drupal Commerce.

In my **products teaser display** all my products variations are also shown. I want only the main product to be displayed and not its variations on teaser display. Right now I am using **in-build taxonomy term view** to display my product teaser.

Any suggestions?

# Answer
> 3 votes
Fortunately I got the answer, by looking at the solution described in a comment to View of products with multi-value product reference field show multiple rows per product node. Here is a summary of it:

> I created a view of product display nodes. Added the relationship to products. Added two fields "Content: Title" and "Commerce Product: Image". Got a row for every display node and product (so a node that references two products gets two rows). This is what I expect to happen.
>
> **Possible solution A**:
>
> I click on "Query settings" in the third column, and in query settings enable "Distinct" (it's a checkbox). That kills the duplicates.
>
> However, DISTINCT is usually a bit stupid, so it might not work in all cases. In those cases, you can try the next possible solution.
>
> **Possible solution B**:
>
> I enable Aggregation (again, it's in the third column). I make sure to have a "Content: Nid" field added at the top of the fields list, so that it groups by that first. Might need to apply "MIN' to the title (by setting: Aggregation type to "Minimum" in "Aggregation settings" for that field).
>
> Note that once you do that, the image will stop displaying. The solution for that is to go into "Aggregation settings" for the image field, and change the "Group column" from "fid" to "Entity ID". That makes it display again.

# Answer
> 0 votes
You may want to try what's below, based on what I found in a comment to "View of products with multi-value product reference field show multiple rows per product node".

Create a view of product display nodes. Add the relationship to products. Add two fields "Content: Title" and "Commerce Product: Image". So that you get a row for every display node and product (so a node that references two products gets two rows). Here are possible solutions for it:

1. Click on **Query settings** (in the 3rd column), and in query settings enable "Distinct" (it's a checkbox). That removes the duplicates.

However, DISTINCT is usually a bit stupid, so it might not work in all cases. In those cases, you can try another possible solution, as detailed below.
2. **Enable Aggregation** (in the 3rd column). Make sure to have a "Content: Nid" field added at the top of the fields list, so that it groups by that first. You may need to apply 'MIN' to the title (by setting *Aggregation type* to `Minimum` in "Aggregation settings" for that field).

Note that once you do that, the image will stop displaying. The solution for that is to go into "Aggregation settings" for the image field, and change the "Group column" from "fid" to "Entity ID". That makes it display again.

---
Tags: 7, views, commerce, nodes
---


title: Access MailChimp forms

text:
# Question
Title: Access MailChimp forms
I currently have a form that it is fully loaded from my Mailchimp Account. I configured it for display as a page using mailchimp configuration page (admin/config/services/mailchimp/signup). Then when I was trying to access it with no admin permissions I got `Not authorized to access this page` message.

Giving `Access all Mailchimp Signup Pages` permission to anonymous users fix this problem but it specify that have security implications and I think it is a wrong solution.

I searched all the drupal interface and was not able to find it on either side (Content, contact forms, etc...). This element it's only present on signup forms list (admin/config/services/mailchimp/signup) and there isn't any permissions configuration.

# Answer
Recently found a FAQ from Drupal Mailchimp módule here It says:

> Q: How do I create anonymous signup forms on the site as either a page or a block?
>
> A: Head to this path admin/config/services/mailchimp/signup/add, fill out the form and click on “Block”, “Page”, or both Display Modes.
>
> Block - ...
>
> Page - enter a path for which you’d like the signup form to appear, and click “Save”. In order to make SignUp pages available to anonymous users, head over to where permissions are assigned (admin/people/permissions), and check the appropriate boxes next to the permission marked “Access all Mailchimp Signup Pages.”

So this means that I should ignore that warning.
> 0 votes

---
Tags: 8, emails
---


# Question
Title: How to give access custom module to individual users?
I have a custom modules name "Employee Entry" and i want that module show only some of the users under a specific role. Like if i have a role office then i want there is few people who can access the content of that module. There is a by default option to give access to whole role but there is no option to give access for specific users.

# Answer
The correct approach here would be to implement hook\_permission to define permissions/a set of permissions to give your user roles specific access.

The Example module has some good info on how to use and validate permissions with hook\_permission in your code.

If you want to restrict certain users, the easiest approach is to create an additional role with those specific things and assign the desired users to that role.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to escape a string so it does not get replaced by Token::replace()
I have a string that is being sent into the replace method of the token service that looks like a token, but it is not.

Here is an example of the string: "\['key:value'\]"

Is it possible to escape this in a way that the replace function will not think it is a token that it needs to replace?

The "clear" flag in the replace function is set to true, so this string always just gets removed, but I want it to ignore this string entirely. Thanks!

# Answer
> 0 votes
`Token::replace()` allows you to use a callback to replace extra tokens no module define, but that is called after the tokens have been replaced; plus, it gets a array as `array($original_token => $replacement)` which makes things slower since you would need to replace each token one by one.

I would rather set `'clear'` to `FALSE`, and then replace all the tokens that have not been replaced with an empty string. Since the strings you need to keep follow a specific pattern, it would be easier to remove the unreplaced tokens with `preg_replace()`.

---
Tags: 8, tokens
---