# Question
Title: Is there a way to make image and text alternate between rows?
In Drupal theme, the content would have image and title which will have image on left and text on right in Display Suite under view in each row.

The client wants: In first row, the image will be on left and text will be right. Next row, text on left and image on right.

Is there a module that can alternate between rows? Or display suite can do that?

Thanks

# Answer
Create a custom module as follows:

In sites/all/modules create a directory: ds\_odd\_even

Add a file ds\_odd\_even.info under that directory. Add the following text in that file:

```
name = "Display Suite Odd Even Output"
description = "Display Suite Odd Even Output."
core = "7.x"

```

Add a file ds\_odd\_even.module under same directory. Add the following text to that file:

```
<?php

function ds_views_row_adv_past_client($entity, $view_mode, $load_comments) {
  static $i = 0;
  $custom_view_mode = ($i++ % 2) == 1 ? 'left_client' : 'right_client';
  return render(node_view($entity, $custom_view_mode));
}

```

Install the module as usual. Note the function name above. It is based on the pattern: ds\_views\_row\_adv\_YOUR\_VIEW\_MACHINE\_NAME. This is the view name from the admin/structure/views UI page, not the display name from the right hand advanced column on a view. Hence the view that this is based on has a machine name of past\_client. If you add more pages and blocks to this view, the view's machine name still stays the same. Each page or block will get a display name in addition. IT IS NOT THE DISPLAY NAME that you add to the function.

Create two view modes in Display Suite. 1. left\_client 2. right\_client

Add two column layout to both, with alternating image and body placement.

In your view (machine name past\_client) set to show Display Suite as format, and in setting select under Advanced View Mode 'Use the advanced view mode selector'.

Clear your cache for good measure. And that is it.

There is no way I see to differentiate on different displays on the same view, unfortunately. You may explore CSS as an alternative, and use the nth-child() selector to alternatively float the display suite regions left or right (make sure you have greater specificity in the cascade or use !important)
> 1 votes

# Answer
In view - go to Display setting - you will see "Alternating view mode"

Check two checkboxes: 1. Use the changing view mode selector 2. Use this configuration on every page. Otherwise the default view mode is used as soon you browse away from the first page of this view.

Then you need to set view mode for each item.

That's it.
> 0 votes

# Answer
AFAIK there's no such setting in Drupal by default, but there's a module for it called Views Parity Row: https://www.drupal.org/project/views\_parity\_row
> 0 votes

---
Tags: display-suite
---


# Question
Title: How to create a list of paragraphs not linked to a node
Is there a way to create/edit several paragraphs (from within a UI) and use them grammatically by after.

Here is my use case:

I have a paragraph type made of 3 fields:

* Unit Source : taxonomy term reference (Kg, g, piece, box of tomatoes,...)
* Unit target : idem
* Conversion factor: floating number

And I would like to encode some data like

* Unit source = box of tomatoes
* Unit target = kg
* Conversion factor = 3

(A box of tomatoes is equal to 3kg of tomatoes)

I would like to be able

1- to encode through a UI a list of those conversion data

2- to be able to call them in some other function by after.

# Answer
> 0 votes
No, this is not possible. By concept paragraphs are always tied to a parent entity, just like normal fields. If it can exist on it's own, better use a node instead.

---
Tags: 8, paragraphs
---


# Question
Title: Using entries from custom block library in twig template?
I have two custom library blocks for the footer of a website I am developing. The idea is that admins may change the footer quite freely with a wysiwyg editor without any theme changes.

The problem is that I don't find any way to use only the contents of the custom library blocks (without the Drupal generated layout destructing code) in the footer twig.

Am I trying to do something impossible or just missing something obvious?

wbr

hank

# Answer
Use Twig Tweak and

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

```

This renders only the block content, without a block template.
> 2 votes

---
Tags: theming, blocks
---


title: Absolute URLs instead of relative

text:
# Question
Title: Absolute URLs instead of relative
I have a problem with ~~entity~~ URLs in D8. All of them are absolute instead of relative, which causes various problems. For example,link URLs to edit content on `/admin/content` look like this:

`http://example.local/node/693/edit?destination=http%3A//example.local/admin/content`

instead of

`/node/693/edit?destination=/admin/content`

* It's not theme-related issue
* I checked various custom classes implementing `OutboundRouteProcessorInterface` and it seems, that none of them should affect this

What could be the cause, then?

EDIT: It's the same with all Drupal-generated links.

BTW. The issue can be seen by executing

```
use Drupal\Core\Link;
$link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' => 1])->toString();
print_r($link);

```

It should result in relative URL, in my case it's absolute one.

# Answer
> 1 votes
Sorry, it was caused by

```
$host = $_SERVER['HTTP_HOST'];
$config['language.negotiation']['url']['domains']['cs'] = $host;

```

in my `settings.php` file. Thanks all!

---
Tags: 8, entities
---


# Question
Title: Rules: How to check one field against same field on all other nodes of that contenttype?
Using Rules I would like to check the values of some fields.

I have a content type 'A' which has a custom field called 'address'. All nodes of content type 'A' are imported through Feeds.

I would like to create a rule where each node that is imported is checked, to verify if the value of field 'address' is equal to the value of field 'address' on any of my other nodes of type A.

I have read about 'Entity has field' as a Rules Condition. However I understand that this only checks several fields in the same node, while I want to check one field against all other nodes.

How can I accomplish this with Rules or any other method?

# Answer
You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed below.

In what follows, I'm assuming that the machine name of your field is `field_address` (change to whatever fits).

## Step 1 - Create a VBO view

Use the Views Bulk Operations (VBO) module to create a view of all relevant nodes, in which you should:

1. Add a VBO field to it.
2. Add a contextual filter for the `field_address` field for which you want to check that its value is unique. Make sure to correctly configure this contextual filter, similar to what is mentioned in this answer to "How to have a field that counts the nodes submitted by the current user?" (credits to Niall Murphy, merci!).

Include a field like `nid` for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Here is an export of such VBO view:

```
$view = new view();
$view->name = 'relevant_nodes';
$view->description = 'Produce a list of node ids that satisfy a specific filter';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Relevant nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Relevant nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Address */
$handler->display->display_options['fields']['field_address']['id'] = 'field_address';
$handler->display->display_options['fields']['field_address']['table'] = 'field_data_field_address';
$handler->display->display_options['fields']['field_address']['field'] = 'field_address';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Contextual filter: Content: Address (field_address) */
$handler->display->display_options['arguments']['field_address_value']['id'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['table'] = 'field_data_field_address';
$handler->display->display_options['arguments']['field_address_value']['field'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_address_value']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['field_address_value']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_address_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_address_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'relevant-nodes';

```

## Step 2 - Create a Rule

Create a rule like so:

* Rules Event: something like "Before saving content of type Article" seems most appropriate, though you can use any variation that fits.
* Rules Condition: "***Check number of results returned by a VBO view***". And select the VBO view created in the previous step. In doing so, you will be asked to "*specify arguments to pass to the view, one per line. You may use token replacement patterns.*". The token to be entered there is `node:field-address`. If the number of results is 1 or more, then you know the value already exists. So within **Minimum number of results** you should enter the value `1`.
* Rules Action: this is pretty much up to your own imagination (your question doesn't specify what should happen ...). For example if the Rules Condition is TRUE, you could use "Set a data value", to set the value of that field to whatever fits. Maybe also display an appropriate message, such as (when trying to set the value to `HomeIsWhereMyStellaIs`):

> The value "HomeIsWhereMyStellaIs" has already been used in at least 1 other node ...

Here is an export of a Rule that does (without such "Set a value" though) what is described above (if you have the Rules UI enabled, and a field with the machine name `field_address`, you should be able to just import this rule):

```
{ "rules_prevent_multiple_nodes_with_same_field_value" : {
    "LABEL" : "Prevent multiple nodes with same field value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "views_bulk_operations_condition_result_count" : {
          "view" : "relevant_nodes|page",
          "args" : [ "node:field-address" ],
          "minimum" : "1"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "The value \u0022[node:field-address]\u0022 has already been used in at least 1 other node ...",
          "type" : "error"
        }
      }
    ]
  }
}

```

Note that my Rules Event is limited to "Article" (change to whatever fits), and replace (prior to trying to import this rule) the machine name of `field_address` to whatever other machine name your field.

***Done!***

PS: I'm assuming this is about D7.
> 0 votes

---
Tags: nodes, entities, rules
---


# Question
Title: theme content type with image from within paragraph
I'm trying to create a twig layout for a Person content type that is be used within Paragraphs. My twig file is paragraph--person-profile--default.html.twig.

I can get the Person name with `{{ content.field_person[0]['#node'].title.0.value }}`

I cannot get the image. I've tried the following:

`{{ content.field_person[0]['#node'].field_image.0.value }}`

and `{{ content.field_person[0]['#node'].field_image.0 }}`

The following error is reported.

> Exception: Object of type Drupal\image\Plugin\Field\FieldType\ImageItem cannot be printed. in Drupal\Core\Template\TwigExtension-\>escapeFilter()

The end game is to have a taxonomy term and a person content type within a paragraph type. The taxonomy term will be used to to style the person. The same person may be styled differently on different pages.

# Answer
> 1 votes
To get the url from an image field you have to go one level deeper, `.entity` gets the file entity where the URI of the image is stored:

```
{{ file_url(content.field_person[0]['#node'].field_image.0.entity.uri.value) }}

```

But digging through multiple levels of nested entities is not good practice, because this produces code hard to debug and maintain. You should look for a better place to theme the image, for example `node--person.html.twig`, where you can print the image field, formatted how it is configured in UI:

```
{{ content.field_image }}

```

# Answer
> 0 votes
Hi bart please refer the below link, it will be helpfull for getting the full URL of the image.

After that you can use Image Tag for rendering the image

Rendering Image Field

---
Tags: 8, theming, nodes
---


# Question
Title: How can I update all content of a content type with a newly added field?
I have a content type with a set of fields.

Hundred(s) of pieces of content have been created from this content type.

I recently had to go back and add a new field to the content type.

In order for all content of that content type that I previously created to show the newly added field, I have so far been going into each piece of content and adding in the field. This is going to take forever.

Is there another tool or process I can use to update all previously created content with the new field added to the content type?

# Answer
> 1 votes
### Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to **Set a data value**, for each of those fields you want to be updated.

### Step 2

Create a view of the nodes for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

### Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

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

# Answer
> 1 votes
if I understand correctly you need to update node in range of new date? right? so if this is the case why not use EntityFieldQuery() to list of this nodes then node\_save() or field\_attach\_update() to update the new value.

if this is the case I'd be happy to give you some snippets to help you do this.

# Answer
> 1 votes
I would recommend Views Bulk Operations for this. You can make a quick view to select the content with a modify action to set the value. No programming needed.

VBO is a great tool to keep handy for a lot of stuff like this.

# Answer
> 1 votes
Existing Question, Please refer the below link

As they mention use Devel module to Run PHP code.

Bulk Field Update

---
Tags: 7, nodes, entities
---


# Question
Title: Rules: save a node but not "fire" a rule that create a loop
I have a rule that "fire" on a condition of "node save". Now in the action of this rule I get the node that I receive via "arguments" and set/change some values if some other values are foo or bar.

My problem is: how can I save the node without create a loop ?

# Answer
Edit: I misread the question but this might be beneficial anyway. Not sure if you're using saving or updating and what you mean by arguments.

You need a Boolean field in your content type that you set to true in the actions of your rule. Then add a condition that if the Boolean is true, the rule doesn't fire repeatably.

You could also skip the extra field and add a condition that one of the fields you set is empty.

If you can't access the fields, you need to add an "entity has field" condition.
> 0 votes

# Answer
You can achieve this using hook\_node\_presave().

Do your changes before node save.

for example, here is a PHP snippet that should do what you want:

```
<?php

function mymodule_node_presave($node) {
  $val = arg(1); // if your url is like http://example.com/foo
  if ($val == 'foo') {
     do_something();
  }
}

?>

```

Hope this will give you exactly what you want.
> 0 votes

# Answer
Have a look at issue # 430274, which somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...). From the limited details provided in the question, it could well be that this also explains what causes your loop.

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Action (related to *Set a data value*) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save of the node" for sure completed, and your node will have been updated as expected.

PS: I'm assuming this question is about D7.
> 0 votes

---
Tags: rules
---


# Question
Title: Move all files and folders from a directory to another directory
I am unzipping some files and folders from an upload but the zip contains the files and folders one directory too deep. So currently they are located

path-to-folder/anotherdirectory/

When I need them to be located at

path-to-folder/

I have tried using the PHP rename function but get an error stating http 'wrapper does not support renaming in...'

Does anyone know the Drupal way to do this please

# Answer
Sounds like you are trying to rename files by specifying their Url. You can't do that. You have to specify the path to the file. It's a PHP issue rather than a Drupal issue. Try this instead:

```
rename($_SERVER['DOCUMENT_ROOT'].'/path-to-folder/anotherdirectory/filename.ext', $_SERVER['DOCUMENT_ROOT'].'/path-to-folder/filename.ext');

```
> 0 votes

---
Tags: 7
---


# Question
Title: How do I print the {{messages}} variable?
In Drupal 7 I was able to do something like this:

```
<?php echo $messages; ?>

```

It seems this variable is no more in Drupal 8.

```
{{messages}} // This returns NULL on {{dump(messages)}}.

```

I basically have a page--user--login.html.twig where I output the page.content and above that I want the messages to be displayed, in case there are errors on the page and not the entire header.

```
// Not desirable
{% if page.header %}
   {% block header %}
     <div class="col-sm-12" role="heading">
         {{ page.header }}
      </div>
   {% endblock %}
{% endif %}

```

What is the correct variable name for `<?php echo $messages ?>` in Drupal 8?

# Answer
> 8 votes
By default the messages are in the highlighted region, put this in your page twig:

```
{{ page.highlighted }}

```

If you changed the block layout, go to

```
admin/structure/block

```

and check in which region you placed the status message block. When it is disabled, move it back into a region.

# Answer
> 1 votes
I display block with status messages by the next way:

1. in hook\_preprocess\_page() add custom variable and put in messages block

`function my_theme_preprocess_page(array &$variables) {
 // add messages block to front page
 if ($variables['is_front']) {
 $block_msg = \Drupal\block\Entity\Block::load('dtt_theme_messages');
 $variables['custom_system_messages'] = \Drupal::entityTypeManager()
 ->getViewBuilder('block')
 - >view($block_msg);
 }
}`

2. in twig template, for my example page--front.html.twig, I can insert block with messages in any place

`{{ custom_system_messages }}`

# Answer
> 1 votes
you can print the message by:

```
{{ page.highlighted.bartik_messages }}

```

bartik\_messages is the Machine name of this block for current theme

In general, you could use the following pattern:

```
{{ page.MESSAGES_BLOCK_REGION.THEME_NAME_messages }}

```

---
Tags: theming, 8
---


# Question
Title: When directly loading a Commerce 2 Order Item, why is the entity cached for anonymous users?
I'm using the following to load a Commerce 2 Order Item:

```
    $order_item = \Drupal\commerce_order\Entity\OrderItem::load($order_item_id);

```

If I empty the cart for an anonymous user (thereby removing the Order Item), using the above code still loads the item as if it still exists.

The caching issue does not exist when logged in.

Why is the Order Item caches when loaded directly like I'm doing above?

How can I load a refresh version?

# Answer
> 0 votes
The issue was due to the fact that the entity logic was running in a custom form and the form was caching the entity.

Simply setting:

```
   $form['#cache'] = ['max-age' => 0];

```

Resolved the issue.

---
Tags: caching
---


# Question
Title: How do I assign different colors to each serie of a Google bar chart
I'm using Charts module to create some charts using the API. Depending on some variable i can create a pie chart or a column chart.

That variable is chart\_type:

```
$chart_type = 'column';
$chart_type = 'pie';

```

This is the code I have:

```
$chart = array(
    '#type' => 'chart',
    '#title' => 'title',
    '#chart_type' => $chart_type,
    '#chart_library' => 'google',
    '#legend' => FALSE,
    '#tooltips' => TRUE,
    '#height' => 234,
    '#colors' => array('#006400', '#c11d0b'),
);

$chart['Status'] = array(
    '#type' => 'chart_data',
    '#title' => 'title',
    '#data' => array(500, 100),
    '#show_in_legend' => FALSE,
    '#show_labels' => FALSE,
);

$chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#labels' => array('Good', 'Bad'),
);

$my_chart['chart'] = $chart;

return drupal_render($my_chart);

```

When the chart is of type Pie, I can see the two colors (green and red) correctly assigned to the slices of the pie. However, I can't assign the same principle to the column chart - in this case, both bars are green.

What I need is to have the colunn chart with the first bar green and the second one, red.

EDIT: Also, on the pie chart, I get two circles and I want to get rid of them. I thought it was a legend but it's not so... how can I remove them also?

# Answer
It's hard to tell (without access to your site) what's causing your issue. But here is a working sample of a chart using the Charts API (disclosure: I'm a co-maintainer ...):

```
<?php
  echo '<p> </p>';
  $chart = array(
    '#type' => 'chart',
    '#chart_type' => 'column', // pie, bar, line, column, area, scatter
    '#chart_library' => 'google', // Allowed values: 'google' or 'highcharts'
    '#title' => t('Meals by store'),
   '#colors' => array('#006400', '#000064', '#640000', '#c11d0b'),
  );
  $chart['store1'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 1'),
    '#data' => array(16, 11, 13),
    '#suffix' => ' Meals',
  );
  $chart['store2'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 2'),
    '#data' => array(12, 14, 17),
    '#suffix' => ' Meals',
  );
  $chart['store3'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 3'),
    '#data' => array(9, NULL, NULL),
    '#suffix' => ' Meals',
  );
  $chart['store4'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 4'),
    '#data' => array(5, 10, 20),
    '#suffix' => ' Meals',
  );
  $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#labels' => array('Breakfasts', 'Light Meals', 'Sandwiches'),
  );

  // dpm ($chart);

  $example['chart'] = $chart;

 return drupal_render($example);
?>

```

If you have the (dangerous) PHP filter enabled, just paste it all in the body of node, and see what happens (make sure you have a working internet connection if you use the Google library).

It should show 3 column charts (1 for each type of "meal"), with each chart having up to 4 columns (1 for each "store").

BTW, make sure you're using the most DEV version (I'm using Version: 7.x-2.0-rc1+5-dev).
> 0 votes

---
Tags: charts
---


# Question
Title: Allow a user to manage his/her own users and be able to assign roles
I need to give access to a specific user with a specific role to be able to give the user role but not the administrator

My case is that the website I'm building needs different kinds of admins and roles, for the role I need to find a solution is for a sub-admin this person should be able to add users and assign roles and I also want this person to only be able to manage the users he adds not all the users.

I found that by using flags and roles might be the best way I found this answer to the question "Give a specific user role the ability to give a user a role but not the 'administrator' role". My problem is that I'm not proficient in Drupal and I'm not sure what to add in this window https://pasteboard.co/H7E7rX9.png I'm trying to learn more about rules seeing that probably I'll be using more of this on my project

Thank you so much for your help.

# Answer
> 0 votes
Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

The way you described in your question how you imagine using the (great!) Flag module, translates more or less to "Is user X yes or no member of Group G?" combined with "What group roles does this user have". However, after you will understand / realize all the things you can do with the Group module (with zero custom code ...), you'll probably also understand that trying to do something similar with the Flag module, is going to take a lot of flags, and related Rules logic.

# More info

Some more questions you may want to look at for more details:

# Resources

---
Tags: 7, rules, flags
---


# Question
Title: Drupal 8 create a template override for a view block within a custom module
**The Question:**

In Drupal 8: How do I add a template override for a view block and have that twig file reside in a custom module - not my theme?

**Further Information:**

I have already created a custom module that creates a content type, imports data from an RSS feed and generates nodes into the content type it created. The module also contains a view YML file so that the view for my content type is created when the module is installed. The view only has one display which is a block.

I would like to create a template override for the block and house the template override within the module (rather than within my theme). The template override does the following:

* Adds the appropriate classes to the block
* Adds an image beside the block title when the title is displayed
* Wraps the {{ content }} in a div with an appropriate class
* Loads the custom module's library to apply CSS

The goal is to have a module that a non-technical person can install, assign a block to the desired region and have all the templates, CSS, JS, etc pull from the module. I don't want them to have to copy a template into their theme, etc. I want the block to be a view so that the user can use the Views UI to make any desired updates to the view block's fields, number of returns, etc.

I was able to get Drupal to recognize the template by using hook\_theme\_registry\_alter() but the variables from the block are null. Both the {{ label }} and {{ content }} are null when I kint them in the template override.

Here is the hook\_theme\_registry\_alter() code:

```
/**
 * Implements hook theme_registry_alter
 **/
function MYMODULE_theme_registry_alter(&$theme_registry){
  $theme_registry['block__views_block__MYVIEW_block_1']['path'] = drupal_get_path('module','MYMODULE') . '/templates/';
  $theme_registry['block__views_block__MYVIEW_block_1']['template'] = 'block--views-block--MYVIEW-block-1';
}

```

It should be noted that when I used hook\_theme\_registry\_alter() for a view page template override in my module it worked. My guess is that the variables were pulled from the page alias.

Please include detailed information because I am still learning about the various hooks and how variables are passed. Thanks in advance!

# Answer
> 6 votes
To get the same variables as a block template add it as base hook:

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__views_block__MYVIEW_block_1' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}

```

Now you can place the twig template in `mymodule/templates/`, path and filename are discovered automatically.

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


# Question
Title: Update drupal module with existing custom changes
I am new to drupal and am wondering when I update a drupal module, say the menu module for example.

If I have some existing custom changes to the module, is it ok to just update the module and it will retain all my custom changes once the update is completed?

Or is it going to overwrite all my custom changes and I would have to "re-do" them or will it actually create a merge conflict during the update?

I am not entirely sure the practice in updating modules where there are custom changes added to it so any insight would be helpful. This is for drupal 8.

Thanks!

# Answer
You are not supposed to hack modules or core directly, because when you update drupal and modules your changes will get lost. If you have some valuable changes or corrections that others might benefit from its best to submit a patch to the issue queue of the module and if maintainer accepts them you benefit as well.

If maintainer does not decide to use your changes you can also consider making your own module or perhaps with a custom theme you can accomplish what you want to do. Drupal has a great system in place to override parts of code with your own logic without hacking core or contributed modules.

If you actually decide to keep those changes as hacks you will have to do your own merge confict resolution as drupal internal update process or even drush updating will not do it for you.
> 1 votes

---
Tags: 8
---


title: Validate form with preprocess_user_form

text:
# Question
Title: Validate form with preprocess_user_form
I'm newbie on Drupal and I try to set an validation and submit the custom user registry form but I try and validation not call.

```
function mymodule_theme(&$existing, $type, $theme, $path){

  $hooks = array();
   // Make user-register.tpl.php available
  $hooks['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mymodule') . '/templates',
    'template' => 'user-register',
    'preprocess functions' => array('mymodule_preprocess_user_register_form'),
  );
  return $hooks;

}

function mymodule_preprocess_user_register_form(&$vars) {

  $vars['title'] = 'Registro de candidatas';
  $vars['message_welcome'] = '<p>Ingresar tu correo electrónico para iniciar este proceso. Asegúrate de tener abierto dicho correo para recibir las notificaciones y realizar de manera inmediata las indicaciones que recibas.</p>';

  //Shortens the form variable name for easier access
  $form = $vars['form'];

  $form['account']['mail']['#attributes'] = array(
    'placeholder' => 'Escribe tu correo electrónico',
    'class' => array(
      'mymodule-form-email-input'
    )
  );
  $form['account']['mail']['#title_display'] = 'invisible';
  $form['account']['mail']['#description'] = '';

  $form['account']['pass']['pass1']['#title_display'] = 'invisible';
  $form['account']['pass']['pass1']['#attributes'] = array(
    'placeholder' => 'Escribe una contraseña',
    'class' => array(
      'mymodule-form-email-input'
    )
  );

  $form['account']['pass']['pass2']['#title_display'] = 'invisible';
  $form['account']['pass']['pass2']['#attributes'] = array(
    'placeholder' => 'Vuelve a escribir contraseña',
    'class' => array(
      'mymodule-form-email-input'
    )
  );

  $vars['mail'] = render($form['account']['mail']);
  $vars['pass'] = render($form['account']['pass']);
  $vars['captcha'] = render($form['captcha']);

}

function mymodule_user_register_form_alter(&$form, &$form_state, $form_id) {

  $form['account']['mail']['#field_prefix'] = '';
  $form['#validate'][] = 'mymodule_user_register_form_validate';

}

function mymodule_user_register_form_validate(&$form, &$form_state) {

  drupal_set_message(t('AN ERROR OCURED'));

  if ($form_state['values']['mail'] !== '') {
    form_set_error('mail', t('Escribe un correo electrónico'));
  } else {
    if(valid_email_address($form_state['values']['mail'])) {
      form_set_error('mail', t('Email invalido'));
    }
  }

  if ($form_state['values']['pass']['pass1'] !== '') {
    form_set_error('mail', t('Escribe una contraseña'));
  }

  if ($form_state['values']['pass']['pass2'] !== '') {
    form_set_error('mail', t('Confirma tu contraseña'));
  }

  if ($form_state['values']['pass']['pass1'] !== $form_state['values']['pass']['pass2']) {
    form_set_error('mail', t('La contraseñas no coinciden'));
  }

  if (!$form_state['values']['sendgift']) {
    form_set_error(NULL, '', TRUE);
    drupal_get_messages();
  }

}

```

Something I have wrong? I look on documentation and I found few details on registration. I read about hook\_form\_alter() and hook\_preprocess\_form() but it's confusing to me.

Thanks

# Answer
> 0 votes
The most obvious issue with your code is that you are trying to override the entire form structure within a theme preprocess hook. This does not work. Such hooks will be able to alter the output of forms or any other templates by providing additional variables, altering existing (theming) variables, or adding theme wrappers. They will not be able to alter the processing logic of a form.

Instead, you should manipulate your entire form within hook\_form\_FORM\_ID\_alter().

The second issue is, that your implementation of hook\_form\_FORM\_ID\_alter() is missing the `_form_` part between `mymodule` and the form ID.

Also, consider using the t() function with English texts for all labels and add your desired translations to Drupal I stead of using hard-coded strings.

---
Tags: forms, users
---


title: How set node access for guest?

text:
# Question
Title: How set node access for guest?
for example I have a url like:

```
/node/add/feature

```

when I go there as guest, I get `'access denied'`, the access should be changed in the code or in the admin panel? but how can I find the exact place where to make changes by following this url?

# Answer
> 0 votes
The admin panel under `/admin/people/permissions`. The `/node/add/$CONTENT_TYPE` access is controlled under the **Node** section as the *ContentType: Create new content* permission.

---
Tags: users, uri
---


# Question
Title: How to translate a node in a custom block?
I know that the question has been asked several time but I didn't find how to get the translation of a node entity.

Here is the code :

```
    $countries = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadByProperties($properties);

    return [
      '#theme' => 'country_selector_block',
      '#langcode' => $lang->getId(),
      '#countries' => $countries,
    ];

```

And in the twig template I put :

```
{% for country in countries %}
    <option value="{{ country.field_code.value }}">{{ country.title.value|t }}</option>
{% endfor %}

```

=\> but it return the country name in the default language

Can you explain how to handle that ?

# Answer
> 2 votes
You need to pass the loaded nodes/countries through the following so that Drupal marks the best available translation as active, then do *not* use t() in the template. That is a security risk, you must never pass user input to t().

```
$country = \Drupal::service('entity.repository')->getTranslationFromContext($country).

```

Do that in a loop on $countries for example, or use array\_walk()/array\_map().

# Answer
> 0 votes
You can add to the properties array the language that you want like this:

```
$properties = [
 'type' => 'article',
 'langcode' => 'es',
];

$countries = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties($properties);

```

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


# Question
Title: How to check if the user is guest in a form
I have a form in a page, so what I want to do is to check wether the user is a guest or a logged user and depending of that add an additional field to a guest, but hide it for the logged user, should this be done in the code of the form or there are some built-in settings for that behaviour?

# Answer
> 0 votes
Can you please elaborate the question. As per the understanding you have to use this condition to check the user login status. Since you have to use it in a form, you can implements with `hook_form_FORM_ID_alter().`

Use this code to check.

```
if (user_is_logged_in()) {
    echo "Logged In";
}
else {
    echo "Not logged in";
}

```

**Edited:**

Example for user\_profile\_form alter. FORM\_ID = user\_profile\_form

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
}

```

To find form id add this in your custom module.

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  print_r($form_id);
}

```

When you visit the page the form is on, the form\_id will be displayed.

`print_r($form);` , you can see all details of a form, like form ID, field names of a form etc.

Also you can inspect the form and find the form id

```
<form enctype="multipart/form-data" action="/user/288/edit" method="post" id="user-profile-form" accept-charset="UTF-8">

```

Here id="user-profile-form", in order to use it in code replace hiphen (-) with undescore(\_)

```
 user-profile-form => user_profile_form

```

---
Tags: forms, users
---


title: Restore database from backup

text:
# Question
Title: Restore database from backup
I accidentally deleted the Drupal 8 files, but the database is not damaged. Is there anyway I can bring my site back to live?

I have an old backup of only files. I restored the file of that backup in the root folder, and replaced the database credentials in the settings.php file. It didn't work.

Is there any other way to bring back the site to live from the database?

**Note**: this is shared hosting.

# Answer
> 0 votes
Replace the settings.php with the default.settings.php and re-run the installer.

Use the same database credentials and it should detect that there is an existing installation and say the installer cannot continue. However, you should be able to view the site normally once the installer cannot continue.

---
Tags: 8, backups
---


title: Rules with condition on taxonomy

text:
# Question
Title: Rules with condition on taxonomy
Im doing a simple Rules that when a content is created of type X, and has taxonomy term of T1, simple action to display a message in the page.

> **Events**: After saving new content (rules\_entity\_insert:node)
>
> **Conditions**:
>
> * Node is of type
> * ***How to configure this item to select taxonomy term???***
>
> **Action**: Show a message on the site

# Answer
> 0 votes
add one condition that checks if the node has field\_term\_ref (term reference) equal to what term name you wish for it.

1. Choose the action "Set a data value".
2. Choose the taxonomy term reference field to set.
3. "Switch to the direct input mode" button to reveal the terms available in your taxonomy field.

---
Tags: 8, rules
---


# Question
Title: How to avoid Rules adding blanks to eMail Id subscribed via Simplenews?
The following rule works fine, only it adds always a blank before and after the emailaddress in the database table . And that gives an error when sending the newsletter.

```
{ "rules_webform_block_to_simplenews" : {
    "LABEL" : "Webform Block to simplenews",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules", "simplenews_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "webform-client-form-113",
          "selected_webform" : { "value" : { "webform-client-form-113" : "webform-client-form-113" } }
        }
      }
    ],
    "DO" : [
      { "simplenews_rules_action_subscribe" : { "mail" : "[data:e_mail-value]", "tid" : "211", "confirmation" : "2" } }
    ]
  }
}

```

# Answer
> 1 votes
You didn't mention in your question what the data type is for that e\_mail component. But you may want to experiment a bit to see if your problem is resolved by using token `[data:e_mail-value-raw]` instead of `[data:e_mail-value]`.

Here is a quote from the *description* (in the Rules UI) about such "raw" values:

> The raw value of the selected component, e.g. "email-value-raw". However this is not cleaned up by check\_plain(). This is raw user input so take care if you use this somewhere else.

If the above doesn't help, I'd also check if adding (some or all of) these Rules Actions would help (before your existing rules Action):

* Add a variable, eg `email_id`
* Set a data value for that `email_id`, to assign it the value `[data:e_mail-value]`
* Convert data type of that `email_id` field (which you then use in your existing Rules Action).

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


# Question
Title: How to override specific row classes in a view preprocess function
Have tried the following but it does not work

```
function THEMENAME_preprocess_views_view_unformatted(&$vars){
  $view = $vars['view'];
  if($view->name == "videos" && $view->current_display == "block_2"){
    $vars["rows"][0]["attributes"]["class"] = array_merge($vars["rows"][0]["attributes"]["class"],['testclass']);
  }
}

```

# Answer
For Example:

```
function THEMENAME_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $view_name = $view->id();

  if ($view_name = 'frontpage') {
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      if( in_array($id,[0]) ) { //first row only
        $attributes = $variables['rows'][$id]['attributes'];
        $attributes->removeClass('lol')->addClass('haha'); // changes "lol" to "haha"
        break;
      }
    }
  }

}

```
> 1 votes

---
Tags: views, theming
---


# Question
Title: I can't get the view ID/name in hook_preprocess_views_view_unformatted()
In this function I can't get view ID/name.

```
function THEMENAME_preprocess_views_view_unformatted($vars) {
  $view = $vars["view"];
  $id = $view->storage->id();
  $name = $view->name;
}

```

In `hook_preprocess_views_view_fields()`, it works properly. Why doesn't it work in `preprocess_views_view_unformatted()`?

# Answer
> 4 votes
This is the only way I could get view id (not sure why)

```
function THEMENAME_preprocess_views_view_unformatted($vars){
  $view = $vars["view"];
  //works
  $id = $view->id();
}

```

---
Tags: 8, views
---


title: RSS does not validate properly

text:
# Question
Title: RSS does not validate properly
I am trying to generate an RSS feed, but it does not validate. I googled around and found RSS Feed does not validate using Views RSS module, but unfortunately it's for Drupal 7, while I am using Drupal 8.4.4.

What a similar method for Drupal 8 would be? The XML I get has an empty line before `<?xml version="1.0" encoding="utf-8"?>`, which I believe it's the main problem.

```
<?xml version="1.0" encoding="utf-8"?>
  <rss version="2.0" xml:base="https://example.com/feeds.xml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:og="http://ogp.me/ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:schema="http://schema.org/" xmlns:sioc="http://rdfs.org/sioc/ns#" xmlns:sioct="http://rdfs.org/sioc/types#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#">
    <channel>
      <title>Title</title>
      <link>https://example.com/feeds.xml</link>
      <language>en</language>

      <item>
        <title>UAE Lenders Upbeat as Growth Prospects Surge</title>
        <link>https://halaltimes.com/uae-lenders-upbeat-growth-prospects-surge</link>
        <description>  <img src="/sites/default/files/styles/large/public/Article/growth-prospects-surge-in-uae.jpg?itok=VEwWB-9R" width="480" height="320" alt="" typeof="Image" class="image-style-large" />

```

# Answer
> 0 votes
Do you have a template for views-view-rss.html.twig in your theme folder? Try enabling the Twig debug feature if you are not sure.

The default one in core/modules/views/templates works properly (same core version).

---
Tags: feeds
---


title: Get node alias in template

text:
# Question
Title: Get node alias in template
I create a *about-us* with Basic Page content type, and with path alias aliased it to `\about-us`( nid = 2),Now in template file I want to get path alias

```
<li><a href="{{  ??????? }}">{{ 'About Us'|t }}</a></li>

```

in Drupal 7 I got it with `url("node/2")` but what is equivalent in Drupal 8? **what snippet I have to use to get path alias of nid 2 in template file ?**

# Answer
**In Summary** if you want to generate *Relative Url* use `path` and if you want to generate *Absolute Url* use `url` So the solution for this question is for relative URL

```
 path('entity.node.canonical', {'node': node.nid})

```

and for absolute URL

```
 url('entity.node.canonical', {'node': node.nid})

```

## Also, I've provided some details about the `path`, `url` and `link` functions to help other guys received this question ( as I received mine after 1 year)

### url($name, $parameters, $options)

> Generate an absolute URL given a route name and parameters:

```
<a href="{{ url('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>

```

> Generate an absolute URL to the current url:

```
<a href="{{ url('<current>') }}">{{ 'Reload'|t }}</a>

```

> Generate an absolute URL to the front page:

```
<a href="{{ url('<front>') }}">{{ 'Home'|t }}</a>

```

### path($name, $parameters, $options)

> Generates a **\[relative\]** URL path given a route name and parameters.

```
{# Link to frontpage view. #}
<a href="{{ path('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>

{# Link to user entity/profile page. #}
<a href="{{ path('entity.user.canonical', {'user': user.id}) }}">{{ 'View user profile'|t }}</a>

{# Link to node page. #}
<a href="{{ path('entity.node.canonical', {'node': node.id}) }}">{{ 'View node page'|t }}</a>

```

> The url and path function are defined in close parallel to those found in \Symfony\Bridge\Twig\Extension\RoutingExtension.

### link($text, $url, $attributes)

> This helper function accepts as first parameter the text and as second parameter the url

Examples:

```
{{ link(item.title, item.url, { 'class':['foo', 'bar', 'baz']} ) }}

```

### file\_url($uri)

> This helper function accepts a relative path from the root and creates a relative URI path to the file.

```
{{ file_url(node.field_example_image.entity.uri.value) }}

```
> 15 votes

# Answer
You can use `path('entity.node.canonical', {'node': dd.nid})` in the template file.

The markup in the template file would look like this.

```
<li><a href="{{path('entity.node.canonical', {'node': dd.nid})}}">{{ 'About Us'|t }}</a></li>

```

I haven't tried it, but it should work.
> 16 votes

# Answer
I don't like sticking node ids in templates (it's just asking for a user down the line to remove the node and end up re-creating the page with a new node id).

I've done this and it seems ok:

```
<a href="{{ path('<front>') ~ 'some/path/here' }}">My Link</a>

```

Note that by default the path returned by will be / so you don't want a leading slash in the text you append.

Someone more experienced than me may be able to chime in if it's a bad idea to use front as your base path.

EDIT: Obviously I'm aware this approach has it's issues too (what if some user changes the alias for the page and breaks the links in the template?). However, users have much easier control over aliases than they do node IDs. Delete a node and there's no way for a mere mortal to create a new node with the same ID again. Mess up an alias, and the regular (content editor) user can put it back right again without having to phone a developer.
> 1 votes

# Answer
You would have to do it in this way:

```
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/2');

```

**Create this variable in the template file and use this path-alias variable where ever you want the alias of the node.**

Source - https://www.drupal.org/node/1853148
> -4 votes

---
Tags: theming, 8, path-aliases
---


title: Altering comment data on publishing

text:
# Question
Title: Altering comment data on publishing
I have a boolean field ( field\_rejected ) in my custom comment implementation ,I need to set this field to false if this comment is published

I tried hook\_comment\_update and hook\_comment\_insert, This didn't work as it says in the documentation :

> "Note that hook implementations may not alter the stored entity data."

Then I tried doing this using hook\_entity\_presave but this also didn't work as it results in an infinite loading or error code 500.

This is the code I used:

```
function custom_comments_notification_comment_presave($comment) {
  if ($comment->isPublished() && !$comment->original->isPublished()) {
    $comment->set('field_rejected', 0, $notify = true);
    $comment->save();
  }
}

```

Note that this is implemented in custom module's .module file.

How can I solve this? How can change the boolean 'field\_rejected' after publishing a comment?

# Answer
Remove that $comment-\>save(); Because you are already in the save process and you will trigger it over and over again with this.
> 1 votes

# Answer
`$comment->save();` should not be there as a `save` will be done automatically (you are in a `_presave` hook)
> 0 votes

---
Tags: 8
---


# Question
Title: Creating node via REST POST gives "leaked cache metadata" error
I'm trying to create new nodes by `POST`ing to `/entity/node?_format=json`. This is the body I'm sending:

```
{
    "_links": {
        "type": {
            "href": "http:\/\/my.drupal.be\/rest\/type\/node\/group_of_documents"
        }
    },
    "title": [{
        "value": "Direct test - type 682"
    }],
    "body": [{
        "value": ""
    }],
    "field_owner": [{
        "value": "Symfony"
    }],
    "field_type": [{
        "target_id": "682"
    }]
}

```

And, in a way, this works. Because the document gets made, and everything is filled in.

But I keep getting an error:

```
A fatal error occurred:
The controller result claims to be providing relevant cache metadata,
but leaked metadata was detected.
Please ensure you are not rendering content too early.
Returned object class: Drupal\rest\ResourceResponse.

```

If I create a node without `field_type`, it doesn't throw an error.

`field_type` is the only field that has the **Reference type -\> Reference views -\> Reference method** set to `Views: Filter by an entity reference view`. Does that have anything to do with it?

# Answer
That's a core bug, see https://www.drupal.org/node/2626298 and https://www.drupal.org/node/2663638 (either of those two would avoid this).

The views reference thing is a good hint. Sounds something runs there that then triggers this exception. You could open an issue for that too if you can find the exact reason.
> 3 votes

# Answer
Try changing response to (maybe helps you) after you save node, because ResourceResponse is cachable...in this way we don't cache POST method.

```
return new ModifiedResourceResponse($node);

```

https://tutel.me/c/drupal/questions/249627/logicexception+node+save+via+resourcebase+post#
> 0 votes

---
Tags: nodes, 8
---


title: Adding notes to a custom form

text:
# Question
Title: Adding notes to a custom form
I have created a custom form and have put in some notes but I am wondering whether it's the correct 'Drupal' way. I have added the notes using the following format:

```
  $form['notes'] = array(
    '#markup' => 'A few notes.
      <ul>
        <li>Item i</li>
        <li>Item ii</li>
        <li>Item iii</li>
         <ul>'
   )

```

# Answer
You could use the preinstalled theme `item_list`:

```
  $form['notes'] = [
    '#theme' => 'item_list',
    '#title' => $this->t('A few notes.'),
    '#list_type' => 'ul',
    '#items' => ['Item i', 'Item ii', 'Item iii'],
  ];

```

See https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21item-list.html.twig/8.5.x
> 4 votes

# Answer
I suppose if there's such a thing as a 'Drupal' way for something like this, it's theming.

Add a theme item in your module/theme:

```
function MODULE_theme() {
  return [
    'MODULE_notes' => [
      'variables' => ['title' => NULL, 'items' => []],
    ],
  ];
}

```

Add a template at templates/MODULE-notes.html.twig:

```
{{ title }}
<ul>
{% for item in items %}
  <li>{{ item }}</li>
{% endfor %}
</ul>

```

And then use it:

```
$form['notes'] = [
  '#theme' => 'MODULE_notes',
  '#title' => 'A few notes',
  '#items' = [
    'Item i',
    'Item ii',
  ],
];

```

Obviously there are many things you could do to augment the way that works depending on your exact requirements.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: How can I display node fields contextually in a block with terms from two separate vocabularies based on node ID?
I've got a content type that has a file field and as part of custom content type that we use to display document links. As part of that content type I have taxonomy 1 "site section" that I'm using to categorize the documents from that field so that they are displayed in specific places on the site. That part is easy.

However, the client just requested an additional level of filtering because they want more fine-grain control over what documents are displayed on what page/node. So far, the best I can figure out is that this level of filtering should be based on a new taxonomy 2 "site sub-section" that I've created that will correspond to specific nodes in the site where the documents need to be displayed.

I'm trying to figure out how I can set my contextual filter so that it will display the resulting file field document results based both on taxonomy 1, and new taxonomy 2, based on the node ID, but I can't figure out the logic to make this happen.

I'm open to other options regarding contextual filters but the node ID is the only one I can think of that would give the specificity necessary to control how and where they're displayed. But, I also cannot figure out to to declare that "when the node ID is \[some node id\], display nodes with taxonomy terms y and z, and only those nodes."

Is there a way to do this within Views or should I just look to create a custom PHP piece to do this?

# Answer
My original goal here was to do this dynamically via contextual filters so I wouldn't need to create a bunch of individual blocks to control various displays. However, I never found a suitable solution for doing this dynamically via the contextual filters, so I ended up resorting to using different blocks with the different filters applied for each one appropriately. It makes a little more of a mess when it comes to managing blocks, but that's not that big a deal.
> 0 votes

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


# Question
Title: Features along with configuration synchronization
I am planning to use features to bundle some of my specific works. Example: I want to bundle article content types along with its views, fields and related other stuffs. Can I just use features to create new article module through features ui and use it? How would it behaves when there is already configuration related to article in my sync folder which contains entire site configuration? Does anyone has experience on working with both of them simultaneously?

Thanks,

CIsSharp

# Answer
> Can I just use features to create new article module through features ui and use it?

Except for some very trivial use cases: No. But Features still is a good starting point and a big time saver.

* Don't expect Features to produce ready-to-use modules of complex Features. It is a great code/stub generator, but be prepared for finetuning both before in Features UI and afterwards on file level.
* Plan your fields carefully: While single-use fields make it easier to create Feature modules, but reusing fields (or more exactly: reusing field storage) across different node types saved me a lot of work later in Views and themeing.
* I always use "Mark all config as required" and "Allow conflicts", and afterwards move the generated config from `config/install` to `config/optional`. I guess this is not the standard Features workflow, but I do this for 2 reasons:
    + It prevents clashes between Features and existing core `config/sync`. If an optional config setting already exists, it will silently be ignored instead of stopping with errors.
    + I found it way easier to manage larger but meaningful modules with some duplicated config, than to split everything into super-small modules with a dependency nightmare.

I'm not quite certain if my experiences are useful to you though, because we are a small company with me being the sole developer. We are trying to reuse Features across different projects, not to avoid collisions on the same project.
> 2 votes

---
Tags: 8, features, configuration
---


title: How do I write a config file manually?

text:
# Question
Title: How do I write a config file manually?
I need to find out how to manually create a configuration file, one which will be included with a custom theme as optional/required upon installation.

I know I need to create a file in themes/mytheme/config/optional for a block, but how do I know the exact filename and what to put in it?

# Answer
> 4 votes
Creating configuration files manually is tedious and like @Berdir mentioned in the comments it is better to export them.

First install your theme, so you can place the blocks for your new theme.

1. Create the blocks in the UI.
2. Make sure you have installed the module: Configuration Manager (already installed if you use Standard profile)
3. Export the configuration using the UI (`/admin/config/development/configuration/full/export`) or using Drush: `drush cex`
4. Depending on how you exported the configuration:
    1. If you used UI, you have a .zip that you must extract.
    2. If you used Drush, the files are exported to `sites/default/config_longname/sync`
5. The blocks file names are `block.block.BLOCK_MACHINE_NAME.yml`
6. Copy those block files that you created and put them `config/optional` in your theme folder.
7. Now open these files and remove the first line, looking something like: `uuid: f95127a4-7947-48e3-a0f1-1dae6c61940d`

That's it, if you move the theme to a new site and install the theme, the blocks will be installed and placed where you originally put them.

---
Tags: 8, configuration
---


# Question
Title: How to hide the label of a entity referenced image field
I am using drupal core 8.4.2 and lightning 8.x-2.23. I have a entity referenced image field that I am printing out like this {{ content.field\_main\_image\_2.0 }}. I think there was a change starting in drupal 8.4 that now the image label is displayed above the image even if you set it to hidden in the media image bundle. Looking at the source for theme template suggestions it says this.

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
* field--media--name--image.html.twig
* field--media--name.html.twig
* field--media--image.html.twig
 * field--name.html.twig
* field--string.html.twig
x field.html.twig
-->
<!-- BEGIN OUTPUT from
'themes/contrib/bootstrap/templates/field/field.html.twig' -->

<div class="field field--name-name field--type-string field--label-hidden field--item">name fish</div>

```

I want to remove the label "name fish" from appearing above the photo. My entity referenced field name is: field\_main\_image\_2 My content type is called: person How should I rename the template named field.html.twig? I tried renaming it to field--field\_main\_image\_2.html.twig and field--field-main-image-2.html.twig, but this didn't work. It says to use this method field--field-foo.html.twig. For now I placed the file field.html.twig in my template folder and it is being used but I dont see where I can remove the label. The template says Available variables: label\_hidden: Whether to show the field label or not.

# Answer
> 1 votes
Starting in Lightning 2.2.4, you can manage the label in the Media Entity's Manage Display tab.

See this issue for more information: https://www.drupal.org/node/2922289

> ## Include patch to omit media name
>
> Until this is fixed in core, it would be good to have the patch from \[#2912298: Make media name available on manage display\] included so that media name can be removed from display. This is especially crucial for lightning upgrades with existing media embeds.

---
Tags: 8, theming, media
---


# Question
Title: Validate and submit functions not calling on template.php
I have an user register form alter on my template.php and this is the code:

```
function mymodule_theme(&$existing, $type, $theme, $path){

  $hooks = array();
  $hooks['user_register_form'] = array(
    'render element'=>'form',
    'title' => 'Registro de candidatas',
    'template'    =>'templates/user-register',
  );
  return $hooks;

}

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  $form['mail'] = array(
    '#type' => 'textfield',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'placeholder' => t('Escribe tu correo electrónico'),
      'class' => array(
        'mymodule-form-email-input'
      )
    ),
    '#required' => true
  );
  $form['pass'] = array(
    '#type' => 'password',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'placeholder' => t('Escribe tu contraseña'),
      'class' => array(
        'mymodule-form-email-input'
      )
    ),
    '#required' => true
  );
  $form['captcha'] = array(
    '#type' => 'captcha',
    '#captcha_type' => 'recaptcha/reCAPTCHA',
    '#attributes' => array('class' => 'captcha')
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Regístrate ahora')
  );

  $form['#validate'][] = 'mymodule_form_user_register_form_validate';
  $form['#submit'][] = 'mymodule_form_user_register_form_submit';

  return $form;

}

function mymodule_form_user_register_form_validate($form, &$form_state) {

  var_dump($form_state);

  echo 'This is my function';
  drupal_set_message(t('AN ERROR OCURED'));

  if (empty($form_state['values']['mail'])) {
    form_set_error('mail', t('Escribe un correo electrónico'));
  } else {
    if(valid_email_address($form_state['values']['mail'])) {
      form_set_error('mail', t('Email invalido'));
    }
  }

  if (empty($form_state['values']['pass'])) {
    form_set_error('pass', t('Escribe una contraseña'));
  }

  /*
  if (!$form_state['values']['sendgift']) {
    form_set_error(NULL, '', TRUE);
    drupal_get_messages();
  }
  */

}

function mymodule_form_user_register_form_submit($form, &$form_state) {

  echo ('This is my custom message');
  /*
  $newuser = array(
    'pass' => $form_state['values']['pass']['pass2'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'status' => 1,
  );
  $user = user_save('', $newuser);
  $user->password = $pass; // Add plain text password into user account to generate mail tokens.
  _user_mail_notify('register_no_approval_required', $user);

  drupal_set_message('Tu registro ha sido procesado, ahora ve a tu email y activalo!');
  */

}

```

And I have the callbacks `mymodule_form_user_register_form_validate` and `mymodule_form_user_register_form_submit` inside `mymodule_form_user_register_form_alter` but these functions aren't called when I submit the form. Something wrong here? Please help. Thanks!

# Answer
> 0 votes
The hook *hook\_form\_FORM\_ID\_alter* does not return a variable. The *$form* variable is passed by reference so it can be modified inside the alter hook.

Remove the **return $form;** line from your **mymodule\_form\_user\_register\_form\_alter** function.

Make sure you clear your cache after code changes to any of those functions.

---
Tags: 7, forms, users
---


title: d8 preprocess commerce product entity

text:
# Question
Title: d8 preprocess commerce product entity
Where can i alter commerce product twig template variables? When i display commerce product `mymodule_preprocess` and `mymodule_preprocess_entity` never called.

Doesn't exist `mymodule_preprocess_node(&variables)` for commerce product entity?

Thanks Fabio

# Answer
You can use `hook_preprocess_commerce_product` like so:

```
function mymodule_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  ...
}

```
> 9 votes

---
Tags: 8, commerce
---


# Question
Title: AJAX 500 using In Place Editor to upload managed_file image
I have a plugin that allows the user to upload an image using managed\_file to use as a bg image. While using the In-Place editor, I get a Ajax 500 error when trying to upload. I will post my watchdog log below. When trying to edit the same page via admin\>structure\>pages\>content, I am able to do this perfectly fine. It also seems that, after uploading the file in admin\>structure\>pages\>content, I am able to swap this image on this block plugin using the in place editor, but trying to do this initially with the in place editor fails.

Watchdog:

```
a:6:{s:5:"%type";s:9:"Exception";s:8:"@message";s:84:"Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed";s:9:"%function";s:11:"serialize()";s:5:"%file";s:89:"/var/www/my_domain/web/core/lib/Drupal/Component/Serialization/PhpSerialize.php";s:5:"%line";i:14;s:17:"@backtrace_string";s:4943:"#0 /var/www/my_domain/web/core/lib/Drupal/Component/Serialization/PhpSerialize.php(14): serialize(Array)
#1 /var/www/my_domain/web/core/lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php(81): Drupal\Component\Serialization\PhpSerialize::encode(Array)
#2 /var/www/my_domain/web/core/lib/Drupal/Core/Form/FormCache.php(197): Drupal\Core\KeyValueStore\DatabaseStorageExpirable->setWithExpire('form-DsqsvPhU0k...', Array, 21600)
#3 /var/www/my_domain/web/core/lib/Drupal/Core/Form/FormBuilder.php(441): Drupal\Core\Form\FormCache->setCache('form-DsqsvPhU0k...', Array, Object(Drupal\Core\Form\FormState))
#4 /var/www/my_domain/web/core/lib/Drupal/Core/Form/FormBuilder.php(419): Drupal\Core\Form\FormBuilder->setCache('form-DsqsvPhU0k...', Array, Object(Drupal\Core\Form\FormState))
#5 /var/www/my_domain/web/core/lib/Drupal/Core/Form/FormBuilder.php(621): Drupal\Core\Form\FormBuilder->rebuildForm('panels_ipe_bloc...', Object(Drupal\Core\Form\FormState), Array)
#6 /var/www/my_domain/web/core/lib/Drupal/Core/Form/FormBuilder.php(314): Drupal\Core\Form\FormBuilder->processForm('panels_ipe_bloc...', Array, Object(Drupal\Core\Form\FormState))
#7 /var/www/my_domain/web/core/lib/Drupal/Core/Form/FormBuilder.php(212): Drupal\Core\Form\FormBuilder->buildForm('panels_ipe_bloc...', Object(Drupal\Core\Form\FormState))
#8 /var/www/my_domain/web/modules/contrib/panels/panels_ipe/src/Controller/PanelsIPEPageController.php(385): Drupal\Core\Form\FormBuilder->getForm('Drupal\\panels_i...', 'Featured FAQ', Object(Drupal\panels\Plugin\DisplayVariant\PanelsDisplayVariant), 'b9459017-7024-4...')
#9 [internal function]: Drupal\panels_ipe\Controller\PanelsIPEPageController->getBlockPluginForm('page_manager', 'home-panels_var...', 'Featured FAQ', 'b9459017-7024-4...')
#10 /var/www/my_domain/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
#11 /var/www/my_domain/web/core/lib/Drupal/Core/Render/Renderer.php(582): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#12 /var/www/my_domain/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#13 /var/www/my_domain/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
#14 [internal function]: Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#15 /var/www/my_domain/web/vendor/symfony/http-kernel/HttpKernel.php(153): call_user_func_array(Object(Closure), Array)
#16 /var/www/my_domain/web/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#17 /var/www/my_domain/web/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /var/www/my_domain/web/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /var/www/my_domain/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#20 /var/www/my_domain/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#21 /var/www/my_domain/web/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#22 /var/www/my_domain/web/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#23 /var/www/my_domain/web/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#24 /var/www/my_domain/web/core/lib/Drupal/Core/DrupalKernel.php(657): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#25 /var/www/my_domain/web/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#26 {main}";}

```

AJAX Error:

```
AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/panels_ipe/variant/page_manager/home-panels_variant-0/block_plugins/CTA/block/0b850df7-0e57-4b46-acc7-386dd294ff13/form?element_parents=flipper/front/settings/ablecore_style/background/bg_image/image&_wrapper_format=drupal_ajax&ajax_form=1
StatusText: 500 Service unavailable (with message)
ResponseText: The website encountered an unexpected error. Please try again later.
ajax.js:110:32

```

I was assuming it was related specifically to this issue

> a:6:{s:5:"%type";s:9:"Exception";s:8:"@message";s:84:"Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

And found someone with a similar issue here

https://stackoverflow.com/questions/45154697/serialization-of-uploadedfile-is-not-allowed

But it was in a non drupal context so I wasn't sure where to go from there. Could the In Place Editor ajax error have to do with the UploadedFile error? And if so how would I resolve this?

# Answer
> 4 votes
It looks like Drupal is trying to cache a form with an attached UploadedFile object in it.

Is your custom Plugin a Block with a file element in it?

In your **blockForm** function try:

```
$form_state->disableCache()

```

# **UPDATE 1**

Based on @Aaron's feedback I updated buildForm to blockForm above.

---

**Note:** Disabling caching for a form does have performance implications.

In general you can disable caching for a form anywhere you create or alter a form. Those functions typically have at least two parameters:

```
@var array &$form
@var \Drupal\Core\Form\FormStateInterface $form_state

```

---
Tags: blocks, panels, files, plugins
---


# Question
Title: How to add google_tag script to header with custom environment variables?
I'm trying to add Google Tag Manager to the `<head>` of my document.

Unfortunately, the way I'm doing it with an HTML tag render element, the ampersands (&) are being escaped.

```
function mymodule_page_attachments(array &$page) {
  $config = \Drupal::config('mymodule.config');
  $gtm_id = $config->get('google_tag_manager_id');
  $gtm_auth = $config->get('gtm_auth');
  $gtm_preview = $config->get('gtm_preview');

  /** @var \Drupal\mymodule\AnalyticsUtility $utility */
  $utility = \Drupal::service('mymodule.utility');

  if (!empty($gtm_id) && !empty($gtm_auth) && !empty($gtm_preview) && $utility->isAdminPage() === FALSE) {

    $script = "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&gtm_auth={$gtm_auth}&gtm_preview={$gtm_preview}&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{$gtm_id}');\n";

    $page['#attached']['html_head'][] = [
      ['#tag' => 'script', '#value' => $script],
      'google_tag_manager',
    ];
  }
}

```

This results in ampersands in the code.

```
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&gtm_auth=testrWktRcmjpViiQKW&gtm_preview=env-6&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-K53TEST');</script>

```

There are two modules with Google Tag Manager and they both add the code using `hook_page_attachments()`.

The recommendation for adding JavaScript is to use an external file; yet, the Google Tag Manager documentation recommends adding the script in `<head>`.

Is there a way to do this with Drupal settings and a javascript file in my custom module? Alternatively, is there a way not to convert the ampersands to HTML entities?

# Answer
> The recommendation for adding javascript is to use an external file

That is not always the case and it is more of a guideline than a hard rule.

There is a way to do what you ask, but you shouldn't because the google\_tag module does exactly what you to want to do. It also allows you to include the GTM snippet inline or as a file.
> 2 votes

---
Tags: 8, javascript
---


title: Related Content entity query

text:
# Question
Title: Related Content entity query
I'm a little new. I need to create a view for related content between different content types, some have same taxonomies field other no. It is a multi language site. So, the view was a little complex, then I am trying with EntityQuery. This search needs to be updated each time that the user update a taxonomy

How can I present the result of my entity query in a node? in a custom block? where can I put my code ?

I asking for a structure or a way to do it this.

# Answer
How I solved my issue with this structure.

---

I created a manager here my\_module/scr/Pluging/myManager.php

*Here I have a function with a entityQuery that return a list of nodes.*

---

I created a block here my\_module/scr/Pluging/Block/myBlock.php

*Here in my build function a call my function in myManager.php and I pass the name of the theme, and a variable with my list of nodes*

---

I updated my .module here my\_module/my\_module.module

*In hook function my\_module\_theme() I add my theme and varibles to be pass.*

---

I created a twig here my\_module/templates/block-related.html.twig

*Here I just do a for to display all field of each node.*

---

Then in my admin/stucture/block I added my block to display in Content section in specific content type.
> 1 votes

# Answer
IMO, the best way to handle related content is for the content admins to manually associate related nodes via a content reference field. There are probably many ways to programmatically relate content, but nothing will be as reliable and accurate as a human making the content relations.

All you need really is a couple nodes associated with each piece of content, then you can drill down as far as you need through related products in your view...

I'll admit this approach may not be feasible for sites that already have a lot of content. But if you are starting off, I feel you should start off this way if you need related content. Just associate some related nodes every time you create a new piece of content.

Then you would create a views block, and show that block on your node.
> 0 votes

---
Tags: views, 8, theming, database, blocks
---


# Question
Title: How to send auto email for new unapproved comments?
How do I config to send auto email for new unapproved comments.

I enabled the comments module and anonymous user can create comments in some content types.

But, I want to receive in an specific email acount a notification for each new comment.

Any suggestion ?

# Answer
## using simple\_comment\_email\_notification

and will send email notification to the site email configured at `admin/config/system/site-information` without any configuration

## using rules

Rules module allows you to **Add reaction rule** by going to `admin/config/workflow/rules/reactions/add`

> React on event \> After saving new comment

And add action

> system \> send email

**NOTE:** rules is still in alpha stage at this time so some things might not work as expected if at all (above procedure has not been tested)
> 1 votes

---
Tags: 8, emails, comments
---


# Question
Title: Access denied for user anonymous for node retrieve service
I have installed services module and added a service. And then, enabled the retrieve and index resources for node. I also enabled the permission to view the published content for anonymous users. cache is also cleared. When i call the retrieve or index service, i am getting the below response.

> http://example.com/endpoint/node/1.json

Response:

`["Access denied for user anonymous"]`

Is there any thing i missed here?

Version D7 - Services 7.x-3.20

Update: It was issue with domain module. Domain strict module was enabled. After disabling, it started working.

# Answer
It was issue with domain module. Domain strict module was enabled. After disabling, it started working.
> 1 votes

# Answer
Make sure node/1 status must be published, otherwise you will get this error.
> 0 votes

---
Tags: 7, services
---


title: Show Entity List Builder in Block base?

text:
# Question
Title: Show Entity List Builder in Block base?
I am making a custom block in Drupal 8 and I want to show my entity list builder in it.Is there any example or certain way by which I can show my entity list in the block.

# Answer
render() builds are renderable array for a table:

```
  public function build() {
    return \Drupal::entityTypeManager()->getListBuilder('entity_type')->render();
  }

```

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityListBuilder.php/function/EntityListBuilder%3A%3Arender/8.5.x
> 3 votes

---
Tags: 8, entities, blocks
---


# Question
Title: onClick attribute striped out in rendered html
I have below code in my Form. But after rendering i could not see the onClick attribute in the link.

```
$form['step2_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
    '#prefix' => '<div class="left"><a onClick="javascript:back_callback(1);" href="javascript:void(0)" class="back_btn">'.t('Back').'</a></div><div class="right">',
    '#suffix' => '</div>',
    '#name' => 'step2',
    '#attributes' => array('class' => array('enabled-for-ajax')),
    '#ajax' => array(
                'callback' => '::myajaxmethod',
              )
);

```

But i got the below output, without `onClick` attribute and `javascript:` in the output.

```
<div class="left"><a class="back_btn" href="void(0)">Back</a></div>

```

Is this restricted? If so, how to achieve this in drupal 8?

# Answer
> 1 votes
Try this code:

```
$form['cancel'] = [
  '#markup' => '<div class="left"><a onClick="javascript:back_callback(1);" href="javascript:void(0)" class="back_btn">' . t('Back') . '</a></div>',
];
$form['step2_submit'] = [
  '#type' => 'submit',
  '#value' => t('Next'),
  '#prefix' => '<div class="right">',
  '#suffix' => '</div>',
  '#name' => 'step2',
  '#attributes' => ['class' => ['enabled-for-ajax']],
  '#ajax' => [
    'callback' => '::myajaxmethod',
  ],
];

```

---
Tags: theming, javascript
---


title: How can I replace "English" with "EN"?

text:
# Question
Title: How can I replace "English" with "EN"?
I have 3 languages in my Drupal 8 site. All works fine, without the language switcher. Replacing *German* with *DE* worked, but replacing *English* with *EN* didn't work.

How can I replace *English* with *EN* in Drupal 8?

# Answer
> 4 votes
I use this, it's a little bit more dynamic then if you would hardcode the language code yourself. Hope it helps. This example works with the language switcher block.

```
function theme_preprocess_links__language_block(&$variables) {
    foreach(array_keys($variables['links']) as &$code){
        $variables['links'][$code]['link']['#title'] = $code;
    }
}

```

# Answer
> 2 votes
This is a Drupal 8 bug. I have had the same issue.

Add the following function to MYTHEME.theme file. (It should be located in the theme directory.) Replace MYTHEME with the machine name of your theme.

```
function MYTHEME_preprocess_links__language_block(&$variables) {
  $variables['links']['en']['link']['#title'] = 'EN';
}

```

# Answer
> 1 votes
Assuming you are using the language switcher block, you could change this in your template MYTHEME.theme file using an preprocess function.

```
/**
 * Implements hook_preprocess_block().
 */
function MYTHEME_preprocess_block(&$variables) {
     if ($variables['elements']['#id'] == 'taalkeuze') { //My sites default language is Dutch hence the id 'taalkeuze' in Dutch.
         $variables['content']['#links']['en']['title'] = 'EN';
     }
}

```

I also tried an implementation of hook\_language\_switch\_links\_alter, but this did not work. I'm not sure why it didn't.

# Answer
> 1 votes
I have the same problem. And as temporary solution I've used this js:

```
(function ($) {
  $(document).ready(function() {
    $("#block-languageswitcher li.fr a").text("FR");
    $("#block-languageswitcher li.de a").text("DE");
  });
})(jQuery);

```

# Answer
> 1 votes
This is not a bug, it's a feature.

All you have to do is to have the `locale` module disabled before adding another language. So now *translations don't get imported automatically*. Afterwards simply enable locale again. And rename the language as you did.

That's it.

# Answer
> 0 votes
The below snippet changes text of the language switcher block to a desired shortcode.

```
/**
 * Change the link title of the language block.
 */
function theme_preprocess_links(&$variables) {
  if ($variables['theme_hook_original'] === 'links__language_block') {
    $variables['links']['nl']['link']['#title'] = 'nl';
    $variables['links']['fr']['link']['#title'] = 'fr';
  }
}

```

# Answer
> -1 votes
If you want that "EN" preffix appear in your URL, go to Administration \> Configuration Regional and language \> Languages \> Detection and selection , and click "configure" in URL. There, you have to add "EN" preffix to english path.

If you want that "EN" preffix appear in your language switcher block, you can use Language Switcher Dropdown module with has an option to change long names as "English" for its internacional code ("EN"). I've only used D7 version.

---
Tags: i18n-l10n
---


# Question
Title: How do enable panelizer support for a custom entity?
I've programmatically created an entity. I'd like to panelize it. What plugins do I need to write to accomplish this?

Thanks!

# Answer
> 0 votes
Just create a **PanelizerEntity** Plugin in your module. Ex if your entity type id (or machine name) is '**course**'. Create a file **PanelizerCourse.php** in *your\_module/src/Plugin/PanelizerEntity/*

This file should extends PanelizerEntityBase like that:

```
<?php

namespace Drupal\your_module\Plugin\PanelizerEntity;

use Drupal\panelizer\Plugin\PanelizerEntityBase;

/**
 * Panelizer entity plugin for integrating with courses.
 *
 * @PanelizerEntity("course")
 */
class PanelizerCourse extends PanelizerEntityBase {

}

```

---
Tags: entities, panels
---


# Question
Title: A way to push notification to desktop and mobile from a website?
I'm looking for a way to push notification to desktop and mobile from a website built with D8. All modules I could find are abandoned sandbox or for D7... If I well understood, the way to push notification to desktop are different from the one to mobile.

Any help?

# Answer
> 0 votes
If you're looking for a ready-to-use solution, I don't think you're going to have much luck at this moment in time.

If you're willing to get your hands dirty and write some code, I would suggest looking at Pushbullet and its API. It's very easy to get started with and it can send push notifications to smartphones, web browsers and desktops (as long as they're running the requisite app or extension).

You could incorporate something as simple as this into a custom module:

```
$title = 'Some title text';
$body = 'Some body text';

$client = \Drupal::httpClient();
$request = $client->post('https://api.pushbullet.com/v2/pushes', array(
  'headers' => array(
    'Access-Token' => 'your_access_token_here',
  ),
  'json' => array(
    'type' => 'note',
    'title' => $title,
    'body' => $body,
  ),
));

```

You're not limited to simple text notifications either; it can push links and files as well.

---
Tags: 8, notifications
---


# Question
Title: Drush 9 can't find installed module, yields CommandNotFoundException
On my newly installed Drupal 8.4.4 sandbox installation, I've installed Drush 9 and the Devel module:

```
composer require drush/drush:^9
composer require drupal/devel

```

After running these commands, I installed the Devel module using the Extend tab in Drupal.

Drush seems be be installed correctly:

```
www-data@39e134dc7690:~/html$ /var/www/html/vendor/bin/drush version
Drush version : 9.1.0

```

The Devel modules seems to be installed correctly:

```
www-data@39e134dc7690:~/html$ grep -r devel-container-service /var/www/html/modules/contrib/devel/
/var/www/html/modules/contrib/devel/src/Commands/DevelCommands.php:   * @aliases devel-container-services,dcs,devel-services
/var/www/html/modules/contrib/devel/drush/devel.drush8.inc:  $items['devel-container-services'] = array(

```

But Drush doesn't seem to find the devel module:

```
www-data@39e134dc7690:~/html$ /var/www/html/vendor/bin/drush devel-container-services
[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "devel-container-services" is not defined.

```

Are there any path settings I need to tweak to get Drush to find the Devel module?

# Answer
> 1 votes
I looks like I simply had forgotten to enable (i.e install) the module in /admin/modules. I had just ran "composer require", but not actually enabled it.

# Answer
> 0 votes
I encountered this issue when attempting to port an older global Drush command. While following the porting instructions generated the necessary Drush code, the command was not discovered by drush because it wasn't part of an enabled module.

If this is your issue, either create a module\_name.info.yml file manually, or run `drush generate module`, then enable the module in question. The drush command no longer threw a `CommandNotFoundException`.

---
Tags: 8, drush
---


# Question
Title: How do I get the currently logged-in user?
I have a site running on Drupal 8 with a login module. I want to get the user ID for the currently logged-in user to later execute a database query.

This is the code I am using.

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$uid = $user->get('uid')->value;
echo $uid;

```

In the controller of a custom module, this code works only between all using and the class controller uses the following code.

```
namespace Drupal\CoopMatha_adh_apport\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Node\Entity\Node;
use Drupal\CoopMatha_adh_apport\Repository;
use Drupal\matha_tools\Controller\ListeController;
use Drupal\matha_tools\Controller;

$userCurrent = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($userCurrent->id());
$uid= $user->get('uid')->value;
echo $uid;

class RapportsController extends ControllerBase {

  // I want the user ID here.
  public function filtrer($firstLetter='', $nbr_ligne='') {
    // …
  }

}

```

How do I get the currently logged-in user ID in the controller class?

# Answer
> How do I get the currently logged-in user ID in the controller class?

Controllers have a `currentUser` method:

```
public function filtrer($firstLetter='', $nbr_ligne='') {
  $current_user_id = $this->currentUser()->id();
}

```
> 3 votes

---
Tags: 8, authentication-authorization
---


# Question
Title: How to send an e-mail to a user selected in a webform via a user reference field?
I have a webform, that the HR use. I have a form component of the users, that is a user reference field.

I would like to use Webform Rules to send an e-mail notification to the selected user.

If I use: `[data:{component}-display]`, then after the username \[1\] appears, that refers to the link to the user.

# Answer
Even though your question doesn't say so (yet), I'm assuming (as per your "*... I have a form component of the users, that is a user reference field...*") that you're also using the Webform References module. Some details about that module (from its project page):

> Provides a webform component that can reference a node/term/user in Webform. It provides "Select List", "Autocomplete", "Checkbox" and "Radio" as widget.

If you also have the Webform Rules module enabled, then it is possible to create a rule (using Rules), which does what you're asking for. Here is an export of a rule that will send an eMail to the eMail Id of the referenced user:

```
{ "rules_email_submitted_webform_to_referenced_user" : {
    "LABEL" : "eMail submitted webform to referenced user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains the field labeled \u0022[data:demoform_userref-title]\u0022 which has value \u0022[data:demoform_userref-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_userref-value-raw]" },
          "PROVIDE" : { "variable_added" : { "referenced_user_txt" : "Referenced user" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "referenced-user-txt" ] },
          "PROVIDE" : { "conversion_result" : { "referenced_user_uid" : "Referenced User Uid" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "referenced-user-uid" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "drupal_message" : { "message" : "referenced_user_txt: [referenced-user-txt:value] AND referenced_user_uid: [referenced-user-uid:value] AND\r\n\r\nUser fetched: uid=[user-fetched:uid] name=[user-fetched:name] mail=[user-fetched:mail]" } },
      { "mail" : {
          "to" : [ "user-fetched:mail" ],
          "subject" : "Hey [user-fetched:name] you have new mail ...",
          "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some more details about this rule (prior to trying to import this rule in your own site, make sure to adapt (rename) what's needed to fit your case):

* The form ID I'm using is `191`.
* All form components have machine names starting with `demoform`.
* The machine name of the reference user is `demoform_userref`.

The Rules Event and Rules Condition should be straight forward, though the actual Rules *magic* happens in the Rules Actions:

1. `Show a message` on the site (just for demo purposes).
2. `Add a **text** variable` (to capture "some" webform data about the selected user, has to be text ...).
3. `Convert a variable` from a **text** to an **integer** variable (we need an integer for the next Rules Action, text won't work ...).
4. `Fetch an entity by ID` (the integer variable, to fetch the user with that ID).
5. `Show a message` on the site (just for demo purposes).
6. `Send an eMail` (**to** the eMail ID from the *fetched user*).

### Demo

After submitting my demoform, the messages shown are like so:

```
The webform submitted contains the field labeled "User" which has value "123".
referenced_user_txt: 123 AND referenced_user_uid: 123 AND User fetched: uid=123 name=Pierre.Vriens mail=pierre.vriens@somewhere.com

```

Moreover, an eMail got delivered to pierre.vriens@somewhere.com ...

*Subject*:

```
  Hey Pierre.Vriens you have new mail ...

```

*Message*:

```
  The webform submitted contains these fields:
   * the field labeled "Title" which has value "Some title".
   * the field labeled "Text" which has value "Some text".
   * the field labeled "Number" which has value "7".
   * the field labeled "Option" which has value "C".

```
> 0 votes

---
Tags: 7, users, rules, webforms, emails
---