# Question
Title: Set height and width of image field being rendered with views PHP
The context: drupal 7, views, views PHP, rendering some fields with PHP because there's no other way.

```
$nodo = node_load($row->nid);
$strmn  = '<div class="post-block">';
$strmn .= '<div class="post-image">';
$image = field_get_items('node', $nodo, 'field_image');
$preout= field_view_value('node', $nodo, 'field_image', $image[0]);
$linko= url('node/'. $nodo->nid);
$strmn .= '<a href="' . $linko . '">' . render($preout) . '</a>';

```

After a lot of googling I've been able to write this.

It's very probably crude but it works, except I can't find a proper way to set height and width for the image. I don't want to create a style in drupal, it would be no good as it won't be used anywhere else. I also don't want, if at all possible, to rework my code to do something like:

```
$image = theme('image_style',array(
    'style_name' => 'mail_image_big',
    'path' => $image_obj['uri'],
    'attributes' => array('style' => 'border:1px solid #aaa;')
  )
);

```

Because my php is sketchy at best and the knowledge of the drupal API is null. Every change costs me a lot of time and energy because, honestly, I lack the basics and I'm not sure of what I'm doing until I do it right.

Finally: how do I set the $display array in field\_view\_value so that height and width are set the way I want them in my output html? I can't find an example or a list of valid properties I can set in the $settings array to save my life. :)

# Answer
> 1 votes
> The context: drupal 7, views, views PHP, rendering some fields with PHP because there's no other way.

There definitely is another way, you're just not aware of it, this article was written 5 years ago:

> As of this writing, 44,497 site maintainers have read that warning and chosen to ignore it. They’ve chosen to put their PHP into a non-revisioned, difficult-to-access place, and to enable PHP input in a module that was never designed for security. They’ve left their site at risk of a very difficult to diagnose and even harder to fix WSOD.

I suggest that you fully read and understand that article and rethink your position about there being no other way.

> Because my PHP is sketchy at best and the knowledge of the drupal API is null. Every change costs me a lot of time and energy because, honestly, I lack the basics and I'm not sure of what I'm doing until I do it right.

Welcome to Drupal, it's a steep learning curve and if your knowledge of PHP is poor then you stand no chance of being able to understand Drupal, perhaps you could edit your question or provide a comment of what you're trying to achieve? I'm always surprised that beginner Drupalers dive straight into coding their way round a problem before investigating whether there is a non-code solution.

Finally, who cares whether an image style is going to be used anywhere else or not? It's not they are hard to set-up or cost anything.

---
Tags: 7, views
---


# Question
Title: How work BigPipe cache around block views?
I have 2 blocks with swiper.js around.

This 2 blocks are from the views module.

I need to print them in the theme like i want so, i load them into the preprocess\_page.

```
$block1 = \Drupal\block\Entity\Block::load('views_block__test_1');
$variables['block1'] = \Drupal::entityTypeManager()
                    ->getViewBuilder('block')
                    ->view($block1);

```

And the second :

```
$block2 = \Drupal\block\Entity\Block::load('views_block__test_2');
$variables['block2'] = \Drupal::entityTypeManager()
                    ->getViewBuilder('block')
                    ->view($block2);

```

They have exactly the same configuration in views and block config.

But for block 1 swipper work, not for the block2 every time i load the page.

If i look at the source i got this for the second block :

```
<span data-big-pipe-placeholder-id="callback=Drupal%5Cblock%5CBlockViewBuilder%3A%3AlazyBuilder&args%5B0%5D=views_block__test_2&args%5B1%5D=full&args%5B2%5D&token=3_VvuYGr92bR7BowQRNlDa4VjOC0ugQafPxRFmxKk9E"></span>

```

For the block 1 i got the HTML render.

I don't know why the second block is cached by big-pipe and not the first block.

But my js on the ready state work every time on the first block, and depend if i clear the cache but it's not everytime, work on the second block the first time i load the page.

The callback (in the bigpipe attributes) call something at the bottom of the page after the js include.

That why my second block doesn't work ? it's not clear.

What's happen ?

# Answer
> I don't know why the second block is cached by big-pipe and not the first block.

This depends on the auto placeholder conditions defined in services.yml and the cache metadata of the block:

```
auto_placeholder_conditions:
  # Max-age at or below which caching is not considered worthwhile.
  #
  # Disable by setting to -1.
  #
  # @default 0
  max-age: 0
  # Cache contexts with a high cardinality.
  #
  # Disable by setting to [].
  #
  # @default ['session', 'user']
  contexts: ['session', 'user']
  # Tags with a high invalidation frequency.
  #
  # Disable by setting to [].
  #
  # @default []
  tags: []

```

As mentioned in the comments, when the module BigPipe is enabled you need to use Drupal.behaviors for your javascript, see:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
> 1 votes

---
Tags: views, 8, blocks, caching
---


# Question
Title: Get the node title conditionally in a view rewrite field
How can I get the field for the title of the content?

In twig I need to do this (for jssor slider) :

```
{% if field_titre_url_externe is not empty  %}
  {{ field_titre_url_externe }}
{% else %}
  {{ field_title }}
{% endif %}

```

but **field\_title** is showing nothing, so what is the name of this?

EDIT :

I'm talking about the title of a node , article or content type

In my frontend, the title has the class **views-field-title**

See this image for more details (that's what I want to do):

Access the field\_url\_externe is not working actually... Accessing this field will solve my problem

# Answer
This is the correct value for the `rewrite field`:

```
{% if field_url_externe is not empty  %}
  {{ field_url_externe }}
{% else %}
  {{ title }}
{% endif %}

```

You can see the available fields in the "Replace Patterns" expandable link.
> 1 votes

# Answer
Is title a field you made or do you mean the node title? Node title can be printed with either `{{ label }}` or `{{ node.getTitle() }}`.

Fields that you created on the node, they are rendered out as:

`{{ content.field_title }}`

Which can be checked as:

```
{% if node.field_title_external is not empty  %}
  {{ content.field_title_external }}
{% else %}
  {{ node.getTitle() }}
{% endif %}

```

You can also use `{{ label }}` instead of `{{ node.getTitle() }}`.
> 2 votes

---
Tags: views, 8, nodes
---


title: node_save() null tid column

text:
# Question
Title: node_save() null tid column
I am trying to create a node programatically like so,

```
$newNode = (object) NULL;
$newNode->type = 'job';
$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->tid = 0;

$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][2] = 2;
$newNode->field_job_category['und'][4] = 4;

//die(print_r($newNode));
// save node
node_save($newNode);

```

Here I have potentially 4 taxonomies to pick from (their id indicated in brackets) Creative (2), Technical (3), Marketing (4), Client Services (6).

On `node_save` I am getting the following error,

> 500 Internal Server Error : An error occurred (23000): SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'tid' cannot be null

How do I overcome this this I would have thought setting the `field_job_category` to the id of the taxonomy would be enough?

# Answer
> 1 votes
If you have one tid by node use:

```
$tid = 0;
$newNode->taxonomy[0]->tid = $tid;

```

if the node can have more than one term use:

```
$tids = [0, 3, 4, 5];
$i = 0;
foreach ($tids as $tid) {
  $newNode->taxonomy[$i]->tid = $tid;
  $i++;
}

```

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


# Question
Title: Import/export configuration and translations
I downloaded the .po file for loading the Italian language and installed it on my local version of Drupal.

Then, I launched the config:export command with drush and I committed the created configuration files

When I imported the configuration on the target machine (via jenkins) I did not find all the translations loaded

In particular, compared to about 7,000 exported translations, I find only 600 imported ones

Why did this happen?

# Answer
> 1 votes
The translations are not part of the configuration.

You can configure and export the source of translation files. One option is to have the local filesystem as the source. The translation files are stored locally in the `sites/default/files/translations directory`, but can change this directory on the File system configuration page.

What you could also configure and export how frequently you want to check for new interface translations for your currently installed modules and themes. At `/admin/config/regional/translate/settings`

Check for updates

* Never (manually, this is the default)
* Weekly
* Monthly

You can manually download the translations at: `/admin/reports/translations/check?destination=/admin/reports/translations`

---
Tags: 8, i18n-l10n, importing-exporting
---


title: db_select get value of the field

text:
# Question
Title: db_select get value of the field
I have order form with field reference number. when a new order is submitted i need to get the last reference number. I did something similar long time ago in Drupal 7 but now i need to do it in Drupal 8 and i don't know how. I noticed that fields in database are written as 'node\__field\_ref\_number'

```
DRUPAL 7
$query = db_select('field_data_field_order_reference_number', 'f');
$query->condition('f.bundle', 'order', '=');
$query->fields('f', array('field_order_reference_number_value'));
$query->orderby('field_order_reference_number_value','DESC');
$query->range(0, 1);
$query->execute();
$result = $query->execute();
$record = $result->fetchAssoc();
//drupal_set_message('previous order №: ' .print_r($record['field_order_reference_number_value'], true));
$title =($record['field_order_reference_number_value']) + 1;
//drupal_set_message('order №: ' .print_r($title, true));
$form_state['node']->field_order_reference_number['und'][0]['value'] = $title;
$form_state['node']->title= 'reference number ' .$title;

```

So far i can get only nid of nods of that type (content\_type\_order)

```
DRUPAL 8
$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'content_type_order');
$results = $query->execute()->fetchAll();
drupal_set_message('value' .print_r($results, true));

```

# Answer
If I understood correctly, this snippet would get you the number:

```
use Drupal\Core\Database\Database;

$query = \Drupal::database()->select('node__field_order_reference_number', 'f');
$query->fields('f', ['field_order_reference_number_value']);
$query->orderBy("revision_id", 'DESC');
$query->range(0, 1);
$last_order_reference_number = $query->execute()->fetchCol()[0];

```

If you need to further understand the database schema related to your field, you could try these commands:

mysql\> show tables like '%order\_reference\_number%';

```
+----------------------------------------------+
| Tables_in_drupal8 (%order_reference_number%) |
+----------------------------------------------+
| node__field_order_reference_number           |
| node_revision__field_order_reference_number  |
+----------------------------------------------+
2 rows in set (0.00 sec)

```

mysql\> describe node\__field\_order\_reference\_number;

```
+------------------------------------+------------------+------+-----+---------+-------+
| Field                              | Type             | Null | Key | Default | Extra |
+------------------------------------+------------------+------+-----+---------+-------+
| bundle                             | varchar(128)     | NO   | MUL |         |       |
| deleted                            | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                          | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                        | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                           | varchar(32)      | NO   | PRI |         |       |
| delta                              | int(10) unsigned | NO   | PRI | NULL    |       |
| field_order_reference_number_value | varchar(255)     | NO   |     | NULL    |       |
+------------------------------------+------------------+------+-----+---------+-------+
7 rows in set (0.23 sec)

```

mysql\> select * from node\__field\_order\_reference\_number;

```
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| bundle | deleted | entity_id | revision_id | langcode | delta | field_order_reference_number_value |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| page   |       0 |        17 |          28 | en       |     0 | 123                                |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
1 row in set (0.00 sec)

```
> 1 votes

# Answer
you can try

```
$query = \Drupal::database()->select('node_field_data', 'n');
$query->fields('n', array('nid', 'title'));
....

```

or you can try with Drupal::entityTypeManage

```
$entity = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
$entity ->condition('type','node_type');
$nids = $entity->execute();

```
> 0 votes

---
Tags: 8, database
---


title: Is referential integrity supported?

text:
# Question
Title: Is referential integrity supported?
Does Drupal 8 support referential integrity? Can I tell Drupal what it should do if a parent row in a content type is deleted? For example:

* I could tell Drupal not to allow the deletion of a parent row if it has child rows
* I could tell Drupal to delete all child rows that belong to a parent row when that parent row is deleted

By *row* I mean an item of a content type. For example, if the content type is *Book*, a row is the data about one book.

# Answer
> 1 votes
No, there's no such feature out of the box.

For D7, there is a module for that, but I haven't see a Drupal 8 version: https://www.drupal.org/project/erri.

We did build something like that ourself based on the entity\_usage module, we alter the node delete form and display a warning that shows where the node is used.

---
Tags: 8
---


title: Sub-theme preprocess inheritance

text:
# Question
Title: Sub-theme preprocess inheritance
I am attempting to create a subtheme using showcase\_lite as a base theme. For now there will be mostly just CSS alterations in the subtheme.

To start, I created just an .info.yml file to start with:

```
name: My Subtheme
type: theme
description: 'Subtheme for testing'
core: 8.x
base theme: showcase_lite

```

Most inheritance works fine (CSS / JS / Twig), but it seems that the preprocess functions in the base .theme file are not called anymore. I am talking about \_preprocess\_html() for example.

Is this expected behaviour? If so, how could I have these be called from my own theme, without copypasting them all?

# Answer
Subtheme inheritance is a bit different in D8. I believe you are running into expected Drupal 8 Theming behaviour.

In D7, the parent theme's functions were called, followed by the subtheme's preprocess functions - I hope this is still the case, but it seems from your troubles that it might not be.

When in doubt, just duplicate the corresponding file in your subtheme.

Here's some more reading on the subject:
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to read data from nodes and display in this complex table?
I have some nodes in my site

```
Day         Color   Type    Value
01-01-2018  blue    A       4
02-01-2018  yellow  B       3
02-01-2018  orange  C       2
03-01-2018  red     B       8

```

I need to show this data in the following way (NOT USING VIEWS):

Does anyone knows if it's possible using the table theme in Drupal? I don't think it's possible to have the double header either.

Is there any other way to achieve this?

# Answer
> 1 votes
You'll have to flatten the data yourself, as you're grouping by date (you'd have to regardless of the double header and colspans), but yes, `theme_table` can accommodate that.

I haven't tested this but it should be at least near to working. The key points to note are `colspan`, which does what you'd think, and `header`, which will mark a cell to be rendered as `<th>` rather than `<td>`. Meaning you can stuff the second row of headers into the body. Not ideal, as they'll be inside a `<tbody>`, but I suspect good enough.

```
$header = [
  [
    'data' => '',
    'colspan' => 2,
  ],
  [
    'data' => 'Type',
    'colspan' => 3,
  ],
];

$rows = [
  [
    [
      'data' => 'Day',
      'header' => TRUE,
    ],
    // Other header rows here, with 'header' => TRUE
  ]
];

// Loop through your grouped data
foreach ($data as $item) {
  $rows[] = [
    $item->date,
    $item->colours,
    $item->type_a,
    $item->type_b,
    $item->type_c,
  ];
}

$build = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

```

---
Tags: 7
---


# Question
Title: Unexpected error during import . . . plugin does not exist error on drush config import
This is an issue I've had occasionally when trying to delete a plugin in a custom module. In this example, once a filter format filter plugin has been enabled it's impossible to remove. If you disable it and remove the plugin class from the codebase, it still shows up in the "filter.format.full\_html.yml" config.

If you try to edit this file to remove the dependency and then do drush cim, you get an error:

```
Unexpected error during import with operation update for filter.format.basic_html: The "examplefilter" plugin does not exist.

```

How do you get rid of this dependency if it shows up in the config when disabled and you can't remove it from the config and import the config without getting a fatal error that the plugin is missing?

# Answer
> 6 votes
I was able to solve this with an update hook. By deleting the config and then reimporting it this way, it doesn't trigger the unexpected error. You need to run "drush updb" first, before "drush cim" for this to work.

```
use Drupal\Core\Config\FileStorage;

/**
 * Reimport filter.format.full_html and filter.format.basic_html.
 *
 * This is to remove the dependency on the examplefilter filter
 * which is being deleted.
 */
function mymodule_update_8003() {

  $config_ids = [
    'filter.format.full_html',
    'filter.format.basic_html',
  ];

  foreach ($config_ids as $config_id) {
    Drupal::configFactory()
      ->getEditable($config_id)
      ->delete();

    $config_path = config_get_config_directory('sync');
    $source = new FileStorage($config_path);
    $config_storage = \Drupal::service('config.storage');
    $config_storage->write($config_id, $source->read($config_id));
  }
}

```

---
Tags: drush, configuration
---


# Question
Title: Is there advanced configuration for CKEditor in Drupal 8?
In Drupal 7 I was able to add config rules to CKEditor in the admin (like `config.allowedContent = true;` for example). I can't find this option in Drupal 8. Is it possible to do something similar?

# Answer
> 12 votes
In regards to "allowedContent", this is set to true if you don't check "Limit allowed HTML tags and correct faulty HTML"( or another filter of type of FilterInterface::TYPE\_HTML\_RESTRICTOR) on your text format, otherwise it outputs the tags you have added there.

For more info on this, you can view:

ckeditor/src/Plugin/CKEditorPlugin/Internal:getConfig()

and

ckeditor/src/Plugin/CKEditorPlugin/Internal:generateACFSettings()

If wanted to override the Internal:getConfig method, you could create a new class that extends it and then replace the class using hook\_ckeditor\_plugin\_info\_alter().

```
function mymodule_ckeditor_plugin_info_alter(array &$plugins) {
  $plugins['internal']['class'] = 'Drupal\mymodule\Plugins\CKEditorPlugin\CustomInternal';
}

```

And then your custom override class:

```
<?php

namespace Drupal\mymodule\Plugins\CKEditorPlugin;

use Drupal\ckeditor\Plugin\CKEditorPlugin\Internal;
use Drupal\editor\Entity\Editor;

/**
 * Allow custom config settings.
 *
 * @CKEditorPlugin(
 *   id = "custom_internal",
 *   label = @Translation("Custom CKEditor core")
 * )
 */
class CustomInternal extends Internal {

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {

    $config = parent::getConfig($editor);

    // Put your custom configs here.
    $config['allowedContent'] = TRUE;

    return $config;
  }

}

```

# Answer
> 4 votes
Sorry to add this as an answer. I'll try to move it to a comment as soon as I've got enough "Drupal 8 Stack Exchange Cred" to comment (\***ugh*** reputation ***grumbles**\*)

**OP:** Did you ever get an answer on whether there is any module or easy way to add this "CKEditor Advanced Configuration" field back in to Drupal 8's text filter settings page? Drupal 7 had it - and it's a super useful thing. Drupal 8 seems to have regressed in this regard :/

I've searched high and low and it seems no one has implemented anything to return this option to text formats in Drupal 8.

There is a module called CKEditor Config, which comes close ( https://www.drupal.org/project/ckeditor\_config ), but it only allows overriding CKEditor configuration globally (for all text profiles).

If there's nothing else out there, I'll try posting an issue asking the author of that module if he would consider adding support for per-text format configuration (or look into adding it myself one day). It seems that everyone else has opted for the approach of overriding CKEditor configuration with various hook implementations in custom modules, but an "advanced configuration" field would be a valuable time-saver now, considering Drupal 8's snazzy config management abilities.

---
Tags: 8, wysiwyg
---


# Question
Title: How to alter a form element to include it inside a fieldset
I am using field\_attach\_form() to display an entity's form. When I call this function, it automatically builds the form, which does not contain any fieldsets, just ungrouped form elements.

Before the form is displayed I would like to take some of the form elements and group them into fieldsets. If I have something like this:

```
$form array:
    form element 1
        attributes
    form element 2
        attributes
    fieldset1
        attributes
    fieldset2
        attributes

```

Is there a form element attribute or special function that will allow me to tell Drupal to automatically place "form element 1" into "fieldset1"?

Alternatively, can this be done at the core/entity level, not the custom module, so that when field\_attach\_form() is called the fieldsets are automatically created?

# Answer
You can use `$form['#pre_render'][] = 'yourfunction';` and move the fields to the fieldset in this function.
> 3 votes

# Answer
This code might help you out.

```
   $form['date_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Select Start and End dates'),
        '#collapsible' => TRUE,
//        '#tree' => TRUE,
    );

    $form['date_fieldset']['date_inactive_start'] = array(
        '#title' => t('Start date'),
        '#type' => 'date_popup', // Provided by the date_popup module
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '0:+1',
        '#required' => TRUE,
        '#size' => 8,
        '#default_value' => date('Y-m-d', time()), // Default value must be in 'Y-m-d' format.
    );

    $form['date_fieldset']['date_inactive_end'] = array(
        '#title' => t('End date'),
        '#type' => 'date_popup', // Provided by the date_popup module
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '0:+2',
        '#required' => TRUE,
        '#size' => 8,
        '#default_value' => date('Y-m-d', time()), // Default value must be in 'Y-m-d' format.
    );

```
> 5 votes

# Answer
If someone is looking for a complete example on how to do this:

```
// hook_form_BASE_FORM_ID_alter to target only article node edit forms
function my_module_form_article_node_form_alter(&$form, &$form_state, $form_id) {

    $form['#pre_render'][] = 'add_to_fieldset';

}

function add_to_fieldset($form) {
    // Adding element to the publishing options fieldset on node form

    $form['options']['element_to_add'] = $form['element_to_add'];
    unset($form['element_to_add']);

    return $form;

}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to use HTML tags in form error messages
I'm using **\Drupal\Core\Form\FormState::setError()** in a form validation hook to display a message if the validation fails. I want to include some HTML on it, but the second parameter of **setError()**, the error message, is escaped. As a result, the HTML code is visible in the message box. How can I avoid this and have HTML in the box?

# Answer
> 10 votes
All errors added to the form state will be finally handled by `drupal_set_message`.
That means that you can either use strings, or any class that implements the `MarkupInterface`.
Looking at that list I would say that what you are looking for is `FormattableMarkup` or even better `TranslatableMarkup`.

An example would then be:

```
$your_error = new TranslatableMarkup('<b>@message!</b>', array('@message' => 'A bold error'));
$form_state->setError($element, $your_error);

```

Good luck!

# Answer
> 5 votes
The other answer does not allow HTML inside the `@message`, here is what worked for me.

```
  $message = '<b>A bold error</b>';
  $rendered_message = \Drupal\Core\Render\Markup::create($message);
  $error_message = new TranslatableMarkup ('@message', array('@message' => $rendered_message));
  $form_state->setErrorByName('field_name', $error_message);

```

**Important:** For security reasons, make sure that `$message` value is authored by an admin only; otherwise, you cannot use this answer!

**Note:** You have to declare the new dependency at top of your class.php file, or you will receive an error and WSOD in browser:

```
use \Drupal\Core\StringTranslation\TranslatableMarkup;

```

---
Tags: 8
---


# Question
Title: How do I create a dynamic query that filters on month and day?
I want to get the list of the nodes, whose content type is *Donors*, where the date in the field\_data\_field\_donor\_date\_of\_birth matches today (except the year).

How can I achieve it using a dynamic query or the `EntityFieldQuery` class?

This is the code I tried so far.

```
$query = db_select('node', 'node');
$query->fields('node', ['nid','title'])
  ->condition('node.status', 1)
  ->condition('node.type', 'CONTENT_TYPE_DONOR');

$query->innerJoin('field_data_field_donor_date_of_birth',
 'field_donor_date_of_birth'
, 'field_donor_date_of_birth.entity_id = node.nid');
$query->condition('field_donor_date_of_birth.field_donor_date_of_birth_value', $birth_date, '=');

$result = $query->execute();

```

# Answer
I was able to query the date by using a where clause instead of condition. Example, replace

```
 $query->condition('field_donor_date_of_birth.field_donor_date_of_birth_value', $birth_date, '=');

```

with

```
$time = format_date(time(), 'custom', 'm-d');
$query->where("DATE_FORMAT(field_donor_date_of_birth.field_donor_date_of_birth_value, '%m-%d') = '$time'");

```
> 1 votes

---
Tags: 7, database
---


title: Drupal 8 Custom front page issue

text:
# Question
Title: Drupal 8 Custom front page issue
I have created a custom front page in my theme (`page--front.html.twig`) and put some custom content which is coming up as expected as long as I am not logged in. But when I log in as admin, I cannot browse the homepage anymore. Rather Drupal always takes me to `eventcloud.dd:8083/user/1`. Even if I manually modify the URL to `eventcloud.dd:8083/` it gets redirected to the above URL, i.e. with `user/1`.

To double check I created an Authenticated User (without administrative rights) and logged in with this account. Same thing happens. Why the system navigates to another page and not staying on the homepage? How to fix this so that homepage only loads up homepage?

I initially created a page `upcoming-events` and set it up as my default homepage from admin/config/system/site-information. I removed that and presently there is no homepage defined separately.

Please advice.

# Answer
> 0 votes
Try going to `admin/config/system/site-information` and set the default front page to `/node`. I think what you describe is related to the Views module which provides the default frontpage in Drupal 8.

---
Tags: theming
---


# Question
Title: error with phpunit execution: how to set PHP Test class path in phpunit.xml?
I installed the conditional\_fields module:

the tree is the following:

```
root project
  - phpunit.xml
  - web
    - modules
      - conditional_fields
        - tests
          - src
            - FunctionalJavascript
            - Unit
              - ConditionalFieldControllerTest.php

```

and this is the declaration of the php class I want to test:

```
<?php

namespace Drupal\Tests\conditional_fields\Unit;

use Drupal\Tests\UnitTestCase;

use Drupal\conditional_fields\Controller\ConditionalFieldController;

    /**
     * ConditionalFieldController units tests.
     *
     * In unit testing, there should be as few dependencies as possible.
     * We want the smallest number of moving parts to be interacting in
     * our test, or we won't be sure where the errors are, or whether our
     * tests passed by accident.
     *
     * @ingroup conditional_fields
     *
     * @group conditional_fields
     */
    class ConditionalFieldControllerTest extends UnitTestCase {
     ....
    }

```

In the phpunit.xml file I wrote this:

```
<?xml version="1.0" encoding="UTF-8"?>

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="vendor/autoload.php"
         verbose="true"
        >
    <testsuites>
        <testsuite name="drupal-composer-project tests">
            <directory>web/modules/conditional_fields/tests/src/Unit</directory>
            <file>ConditionalFieldControllerTest</file>
        </testsuite>
    </testsuites>
</phpunit>

```

but I get this error:

```
Fatal error: Class 'Drupal\Tests\UnitTestCase' not found in C:\xampp\htdocs\drupaltest2\web\modules\conditional_fields\tests\src\Unit\ConditionalFieldControllerTest.php on line 21

```

# Answer
You must point in the phpunit.xml file to drupal's bootstrap.php file. See a working phpunit.xml file example for Drupal 8 here: http://cgit.drupalcode.org/permissions\_by\_term/tree/tests/phpunit.xml.dist
> 2 votes

---
Tags: 8, testing
---


title: Issue with the cognito module

text:
# Question
Title: Issue with the cognito module
I am running into the below issue :

> The website encountered an unexpected error. Please try again later.InvalidArgumentException: Class "\Drupal\cognito\Form\Email\UserLoginForm" does not exist. in Drupal\Core\DependencyInjection\ClassResolver-\>getInstanceFromDefinition() (line 24 of core/lib/Drupal/Core/DependencyInjection/ClassResolver.php).

1. I installed the Cognito module.
2. Its not properly built yet hence on installing it throws an error did not allow me to login into back end.
3. I tried to manually uninstall the module by deleting the folder and then i cleared the cache through drush.
4. Tried re-installing and un-installing the cognito module with Drush commands as well but still throws the same error.

But this is the error that i get even on clearing the cache.

# Answer
You can't uninstall modules by deleting them. You need to run the uninstall routine. Via UI (which doesn't work in your case as you can't log in) or via CLI (Drush or Drupal Console).

---

1. Put the module back.
2. Uninstall it via Drush.
3. Log in.

---

1. `drush pm:download cognito`
2. `drush pm:uninstall cognito`
3. Log in.
> 0 votes

# Answer
There was no better way of resolving this.Since i am using acquia cloud i had an option to restore my DB backup for a day prior. Acquia platform does take daily backup which turned out to be useful.
> 0 votes

---
Tags: 8, dependency-injection
---


# Question
Title: Grandchild nodes (of a nested taxonomy term) on node page
Every time I think I understand relationships… Got desperate and cannot make work following context:

A node has a reference (field\_a) to a term 1A of vocabulary A. That term 1A itself has a reference (field\_b) to another term 1B of vocabulary B.

vocabulary A \> vocabulary B

TERM 1A \> TERM 1B

TERM 2A \> TERM 2B

TERM 3A \> TERM 1B

TERM 4A \> TERM 2B

NODE 1 \> TERM 1A (\> TERM 1B)

NODE 2 \> TERM 2A (\> TERM 2B)

NODE 3 \> TERM 3A (\> TERM 1B)

NODE 4 \> TERM 4A (\> TERM 2B)

On the node page I would like to have a block that shows all nodes that have the same (term) grandchild relationship to 1B (respectively 2B or any term of vocabulary B).

Or schematically (adding other cases)

BLOCK on NODE 1 PAGE shows related NODE 1 and 3

BLOCK on NODE 2 PAGE shows related NODE 2 and 4

BLOCK on NODE 3 PAGE shows related NODE 1 and 3

BLOCK on NODE 4 PAGE shows related NODE 2 and 4

Could someone please give my a hint?

# Answer
> 1 votes
You can start with Content Views that show all nodes tagged with term from Vocabulary A, then add relationships to Taxonomy information, including the reference between terms from vocabularies A and B, and the one introducing content tagged with those terms.

1. Create a new Views of type Content showing Fields, add a Block Display to the View, change its name to something meaningful you can recognize later on Blocks page
2. Add a Filter to limit to your desired Content types
3. Add a new Relationship **Taxonomy term referenced from field\_a** and **Require this relationship**

This one merely introduces more information about the Vocabulary A term that the current node is referencing.
4. Add a new Relationship **Taxonomy term referenced from field\_b**, make it use the first Relationship and **Require this relationship**

This one introduces information about the term from Vocabulary B that is referenced by the term that node is tagged with.
5. Add a new Relationship **Taxonomy term using field\_b**, make it use the second Relationship and **Require this relationship**

This one goes reverse, back from Vocabulary B to terms from Vocabulary A that reference specific term from B
6. Add a new Relationship **Content using field\_a**, make it use the third Relationship and **Require this relationship**

This one introduces nodes that are tagged with terms from A that also reference term from B that is referenced by term from A that the current node is tagged with.
7. Add a new Contextual filter **ID** from `Content` Category and configure:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Content**
\[your relevant CTs\]

This one just gives Views information about the current node.
8. Edit the `Content: Title` Field you already have and make it use the fourth relationship (it will actually be the only one available). Now the Title won't be showing the Title of the current node, but the Title of the node that is related to the current node through A \> B \> A "relation path".

You should now see a list of nodes related to the current node through the "grandparent" term.

---
Tags: taxonomy-terms, blocks
---


# Question
Title: How to get a count of number of nodes created per week in views and show the week
I am creating a view to breakdown the number of node published per week using views. I were able to create a view that will show me the breakdown day or month but there is no option for week. How will I do that?

and the result

Also how do I make it show the first day of that week or the first item publish for that week.

Any help is appreciated.

\** update\**

I were able to get the right mysql query:

```
SELECT COUNT(DISTINCT node.nid) AS nid, MIN(node.nid) AS nid_1, 'node' AS field_data_field_published_at_node_entity_type, YEARWEEK(DATE_FORMAT((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL -14400 SECOND), '%Y%m%d')) AS node_created_yearweek FROM node LEFT JOIN field_data_field_published_at field_data_field_published_at ON node.nid = field_data_field_published_at.entity_id AND field_data_field_published_at.entity_type = 'node' WHERE (( (node.status = '1') )) GROUP BY field_data_field_published_at_node_entity_type, node_created_yearweek ORDER BY node_created_yearweek DESC LIMIT 55;

```

How can I add the query to the view?

**update 2** base on you answer it is grouping by day showing week:

**update 3**

and the list is still the same grouping by day showing week.
The numbers in parenthesis are the number of item published that/a day of the week.
Example on week 21 we published item 6 days in that week and in the parenthesis is the number of item published for each day.

**upate 4** some progress
removed sort criteria

expected output but all years (last 3 years) are combine

# Answer
## Contextual Views Summary

You can show weekly results using a Contextual filter.

In D7 you can add a new Contextual filter `Content: Created week` and configure it with these options:
`When the filter value is NOT available`
**Display a summary**
`Sort by` **Date**
`Format` **List**
`Base path` (you *must* enter the Page path if this isn't the first Page Display in your Views)
**Display record count with link**
**Override number of items to display** to `0` to have an infinite number of weeks show. Use this if you want the Pager to control the number of nodes shown for each week (if there are many). Otherwise, the Pager will apply to the number of weeks as well as nodes!

This way you get a list of weeks by their number, each week links through to a list of nodes created during that week:

The Sorting criteria you add to the Views will affect the list of nodes you see after you click through a summary week link. If you add the `Content: post date` criteria, the nodes will show as the oldest first if you set it to `ascending`.

---

## Aggregation

For more control, you can use Aggregation to count the results, but it involves a lot more steps to recreate the Summary like above.

After you turn on Aggregation simply change one of the Fields that is unique (for example Node ID) to `Count DISTINCT` and it will show the number of results.

You'd have to combine it somehow with the Contextual weekly filter if you wanted to display something different from the Summary, possibly create one Views display for the first node of the week, then in an Attachment do the counting and attach it to the week.

Adding a set query to Views is a bit of an overkill since the purpose of Views is to build queries (through an interface).
> 3 votes

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


# Question
Title: OpenDialogCommand how to include Buttons in dialog_options
How can I inlcude buttons in OpenDialogCommand?

```
$options = [
        'dialogClass' => 'my-dialog-class',
        'width' => '700px',
        'buttons' => [
          'text' => 'Continue',
          'class' => 'btn-primary ok-button',
          'click'=> "function() { $(this).dialog('close'); }",
  ],
      ];

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

```

This seems not to work. The class is set, but no buttons are shown.

# Answer
In the $options array the element "buttons" must be a "multiple" array. For example:

```
$options = [
  'dialogClass' => 'my-dialog-class',
  'width' => '700px',
  'buttons' => [
    [
      'text' => 'Continue #1',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
    [
      'text' => 'Continue #2',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
  ],

```
> 0 votes

---
Tags: 8, ajax, javascript
---


# Question
Title: How to add twig template suggestions per display mode with custom module?
I have a custom module where I am trying to use custom twig templates based on the *user* *view mode*. The templates files I am trying to add to my theme are:

* `user.html.twig`
* `user--compact.html.twig`
* `user--token.html.twig`

These reside in a folder called `MYMODULE/templates/`.

This is my current module code:

**module\_name.module:**

```
/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user' => [
      'template'  => 'user',
      'base hook' => 'user',
    ],
    'user__compact' => [
      'template'  => 'user--compact',
      'base hook' => 'user',
    ],
    'user__token' => [
      'template'  => 'user--token',
      'base hook' => 'user',
    ],
  ];

}

```

# Answer
The `hook_theme_suggestions_HOOK_alter()` is more suited to alter existing suggestions.

In this case, if you are just adding a suggestion, not altering the pre-existing ones, you could use the hook\_theme\_suggestions\_HOOK.

```
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function MYMODULE_theme_suggestions_user(array $variables) {
  return [
    'user__' . $variables['elements']['#view_mode']
  ];
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user' => [
      'template'  => 'user',
      'base hook' => 'user',
    ],
    'user__compact' => [
      'template'  => 'user--compact',
      'base hook' => 'user',
    ],
    'user__token' => [
      'template'  => 'user--token',
      'base hook' => 'user',
    ],
  ];
}

```
> 3 votes

# Answer
The fix was ensuring to add the theme suggestions via `HOOK_theme_suggestions_HOOK_alter()`, as well as switching one template from `user` to `user__full`. Below is the updated module code:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_user_alter(&$suggestions, $variables) {

  $view_mode = $variables['elements']['#view_mode'];
  $suggestions[] = 'user__' . $view_mode;
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user__full'    => [
      'template'  => 'user--full',
      'base hook' => 'user',
    ],
    'user__compact' => [
      'template'  => 'user--compact',
      'base hook' => 'user',
    ],
    'user__token'   => [
      'template'  => 'user--token',
      'base hook' => 'user',
    ],
  ];
}

```
> 3 votes

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


# Question
Title: How to display current pages the media entity is referenced during deletion?
We are using Media Entity module that provides a `Document` media bundle. On our `Article` content type, we have created an Entity Reference field to `Media` that is set to `Document` media bundle.

When you click Delete on this `Document` media entity, you are taken to a `Are you sure you want to delete the media <media name>?` page for confirmation (not sure of the official name, but let's call it Confirm Deletion page). On this page we would like to display all the pages where this media entity is currently being referenced.

How would we display the list of nodes that are referencing the media that content editors are attempting to delete?

# Answer
Additionally to the comment, here's the snippet we used based on the entity\_usage module in a hook\_form\_alter():

```
  $object = $form_state->getFormObject();
  if ($object instanceof ContentEntityDeleteForm) {
    $entity = $object->getEntity();
    $usage_data = \Drupal::service('entity_usage.usage')->listSources($entity);

    if (!empty($usage_data)) {
      $count = 0;

      foreach ($usage_data as $usage) {
        $count += count($usage);
      }

      $form['usage_warning_message'] = [
        '#type' => 'container',
        '#markup' => t('This content is used in <a href="@usage_url" target="_blank">@count</a> places.', [
          '@usage_url' => Url::fromRoute('entity_usage.usage_list', [
            'entity_type' => $entity->getEntityTypeId(),
            'entity_id' => $entity->id(),
          ])->toString(),
          '@count' => $count,
        ]),
        '#attributes' => [
          'class' => ['messages', 'messages--warning'],
        ],
        '#weight' => -100,
      ];
    }
  }

```
> 2 votes

---
Tags: 8, entities, hooks, media
---


# Question
Title: Why is Rules Action "Create Linked Drupal User Account" not working?
I’m using Drupal **7.56** and CiviCRM **4.6.31**.

I’ve been using Rules in Drupal to create a Drupal User Account linked to the CiviCRM contact created. But it's failing. I'm getting the following error:

> Cannot create user, email: invalid!!

This is the **export** of the Rule:

```
{ "rules_create_a_drupaluser_for_an_civicrmcontact" :
    {
        "LABEL" : "Create a Drupal user for an CiviCRM contact",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "REQUIRES" : [ "civicrm" ],
        "ON" : { "civicrm_contact_create" : [] },
        "IF" : [
          { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm_contact" ] } }
        ],
        "DO" : [
          {
            "civicrm_entity_action_create_user" : {
              "USING" : {
                "civicrm_contact" : [ "civicrm_contact" ],
                "is_active" : "1",
                "notify" : "0",
                "signin" : "0",
                "username_format" : "email"
              },
              "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
            }
          }
        ]
    }
}

```

It was working some time ago.

The link where I downloaded the civicrm\_entity (release 7.x-2.0) is: *https://www.drupal.org/project/civicrm\_entity/releases*

For your convenience I've added the source code for the Rules Action `civicrm_entity_action_create_user`:

```
function civicrm_entity_action_create_user ($contact, $is_active, $notify = FALSE, $signin = FALSE, $username_format = 'first last') {

  if (!is_array($contact)) {

    // Perhaps we should be accepting object rather than array here?
    $contact = (array) $contact;
  }

  // We'll use the civicrm sync mechanism to see if Civi can match the
  // contact to an existing user.

  // Don't think this is a great approach but will use for now - could
  // just create the user but no great support for that yet.

  if (empty($contact['display_name']) || empty($contact['email']) || empty($contact['first_name']) || empty($contact['last_name'])) {

    $contact = civicrm_api('contact', 'getsingle', array(
      'version' => 3,
      'id' => $contact['id'],
      'sequential' => 1,
      'return' => 'email,display_name,first_name,last_name',
    ));
  }

  if (!is_string($contact['email']) && isset($contact['email'][0]->email)) {

    $contact['email'] = $contact['email'][0]->email;
  }

  // @TODO What happens if they don't have an email at this point?

  // An email is a pre-requisite for a Drupal account, so the action
  // fails if they don't have an email.

  if (filter_var($contact['email'], FILTER_VALIDATE_EMAIL) === FALSE) {

    drupal_set_message(filter_xss("Cannot create user, email: " . $contact['email'] . " invalid!!") , 'error');

    watchdog('civicrm_entity', 'Cannot create user, email %mail invalid.', array('%mail' => $contact['email']), WATCHDOG_ERROR);
    return FALSE;
  }

```

And here is where the error raises.

These is the **Rules evaluation log**:

```
Reacting on event CiviCRM Contact has been created.

 Evaluating conditions of rule Create a Drupal user for an CiviCRM contact.

 The condition civicrm_entity_user_exists evaluated to FALSE

 AND evaluated to TRUE.

Rule Create a Drupal user for an CiviCRM contact fires.

   Rule Create a Drupal user for an CiviCRM contact fires.

   Evaluating the action civicrm_entity_action_create_user.

   Evaluating the action devel_debug.

   Rule Create a Drupal user for an CiviCRM contact has fired.

Finished reacting on event CiviCRM Contact has been created.

```

And the Log Message gets this Error:

```
MESSAGE "**Cannot create user, email invalid.**"

```

Does anyone have any clue about what might be happening?

# Answer
The explanation for the issue you're facing is within the comment lines of the Rules Action you included iin your question, i.e.:

```
  // @TODO What happens if they don't have an email at this point?

  // An email is a pre-requisite for a Drupal account, so the action
  // fails if they don't have an email.

```

The eMail ID for the CiviCRM contact you're using appears to be missing. So try again with a similar testcase, but make sure that for the CiviCRM contact some eMail Id is entered.

This probably also explains the "*It was working some time ago*": chances are that it was working, since you were using a CiviCRM contact for which an eMail ID was available.
> 0 votes

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


# Question
Title: Display field inputs side-by-side in node edit form
I have quite a few Field Collections on my node edit form that each have three text input boxes. By default drupal displays them one on top of the other which makes for a very long page:

Ideally I'd like to display the three fields in a single row. Do I have to override this with CSS or is there a setting I'm missing? It's a pai to Google a solution because I keep getting article about in-place editing or theming webforms.

# Answer
If you are using Field Collections you can have them displayed in a few different ways, one of which is a table, which is more relevant for some situations than others. Have a look at Field Collection Table and see if it suits your needs.

It will, in your example, put the three fields side by side - but in table cells.
> 0 votes

# Answer
If you use the Display Suite module with Display Suite Forms sub-module enabled this is pretty easy.

On the Structure-\>Field Collections-\>Manage Fields page, select your layout to be "3-column equal width" (or whatever layout you prefer). Click Save to update the layout options.

Then drag your fields into the appropriate columns, click Save again and it will now show the fields side-by-side. You can also easily put multiple fields in each column this way if you like.
> 0 votes

# Answer
CSS would be the appropriate solution. Some suggestions to try:

CSS float option:

```
.wrapper-class-name .field-item {
    width: 33.3333%;
    float: left;
}

fieldset {
    clear: both;
}

```

CSS inline-block option:

```
.wrapper-class-name .field-item {
    width: 33.3333%;
    display: inline-block;
    margin-right: -5px;
}

```

CSS grid option:

```
.wrapper-class-name {
    margin: 20px 0;
    display: flex;
    flex-wrap: wrap;
    display: grid;
    -ms-grid-template-columns: repeat(3, 1fr);
    grid-template-columns: repeat(3, 1fr);
    grid-auto-rows: auto;
    grid-gap: 15px;
    align-items: top;
}

```

*\*using CSS grid with Drupal in my experience almost always requires updating the markup through template modifications, Drupal tends to add wrapper elements and CSS Grid needs direct descendants.*

The problem with this situation is that you are typically viewing form fields like this in an **administration** theme, so if you're needing to update the **administration** theme you will need to add your CSS to the **administration** theme. I think the question may be, do you want to manage the CSS modifications of a contributed theme? Nothing wrong with it, just something to keep in mind.
> 0 votes

# Answer
Sorry CSS is the only way to do that. You might need to add something to limit the form field and then float them, I did something like this:

```
div.field-your-field-name .field-item {
float: left;
margin-right: 0.75em;
}

```

But I had no label, so you might need to change the css for the label too. Remember to add a

```
    clear: left;

```

for the next element css otherwise the next element might be floated too.
> -1 votes

---
Tags: entities
---


# Question
Title: How to pass variable of paragraphs type to another preprocess function
I want to override the fontawesomeicons.html.twig (Fontawesome Module). But I only want to do this for "my-very-special-paragraphs-type" and not in general. I think it is a good idea to declare a variable of "my-very-special-paragraphs-type" in a preprocess function and use the variable in the twig-file.

```
function mytheme_preprocess() {
  $var = my-very-special-paragraphs-type
}

```

the fontawesomeicons.html.twig:

```
{% if var == 'my-very-special-paragraphs-type' %}
<div class="fontawesome-icons pb-4 t-a-c">
    <span class="fa-stack fa-4x">{{ icons }}</span>
</div>
{% else %}
<div class="fontawesome-icons">
   {% if layers == '1' %}
      <span class="fa-layers fa-fw">{{ icons }}</span>
   {% else %}
      {{ icons }}
   {% endif %}
</div>
{% endif %}

```

But I do not know how to do this. Can anybody help?

This is the hook of fontawesome module:

# Answer
> 1 votes
This was quite a ride.

First of all: I didn't got this running in the theme. I needed to create a custom module AND move its implementation of the fontawesomeicons hook last.

Next thing was: `hook_preprocess_fontawesomeicons` doesn't contain a hint of the parent entity the icons are used in. So I used `hook_preprocess_field` first to pass the paragraph type over to `drupal_static()` and retrieved it back then in `hook_preprocess_fontawesomeicons`.

```
/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {

  if ($hook == 'fontawesomeicons') {

    // Run MYMODULE_preprocess_fontawesomeicons() last.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

/**
 * Implements hook_preprocess_field__FIELD_TYPE().
 */
function MYMODULE_preprocess_field__fontawesome_icon(&$variables) {

  if ($variables['element']['#entity_type'] == 'paragraph') {

    $paragraph = $variables['element']['#object'];

    $ptype = &drupal_static('paragraph_type', TRUE);
    $ptype = $paragraph->getType();
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_fontawesomeicons(&$variables) {

  $ptype = &drupal_static('paragraph_type', FALSE);

  if ($ptype) {
    $variables['paragraph_type'] = $ptype;
  }
}

```

Inside any variation of `fontawesomeicons.html.twig` you now can:

```
{% if paragraph_type == 'my-very-special-paragraphs-type' %}
  {# do your magic here #}
{% endif %}

```

---

I never heard of `drupal_static()` until today. Read more:

---
Tags: 8, theming, paragraphs
---


# Question
Title: How to add another navigation bar/block at the top of your site?
I want to add a custom header/navigation block at the very top of my page like so, it's essentially a menu item. For example, it has two items: Home and Business. Once clicked it stays highlighted and menu items below it change.

The default is Home, and it has its own header and page underneath. If a user clicks 'Business', it will load another page with a different header/menu items.

I am wondering: How would I do this in drupal? Would I do it all in the navigation block? Would customization be required and where exactly? Any advice on how I can approach this best?

For example, These two menu items will be the top parents of every page.

```
Home
|
|___menu item/page 1
|   |
|   |__Another page, etc
|___menu item 2/page 2
|___menu item 3/page 3

Business
|
|___a different menu item/page 1
|___a different menu item/page 2
|___a different menu item/page 3

```

# Answer
> 0 votes
The layered navigation that you're asking about (where you always see primary menu items, but the secondary items are related to a particular primary item and they only show when their parent is active) is called Primary and Secondary menu in Drupal.

## Drupal 7 Menu settings Primary and Secondary navigation

In Drupal 7 and older there was a Menu setting where you could choose which menu to use as Primary and Secondary level of navigation:

You could use separate Menus for Primary and Secondary levels, but it makes more sense to create one Menu with two or more levels (depths):

Then you would choose the same Menu under both Menu settings and Drupal would automatically only use the first level for Main links and lower levels for the Secondary links.

When you have that set up, and if you have the Main and Secondary links available and enabled in your theme:

you will see the Secondary items related to the parent item when you visit the parent page. Secondary items will appear in the place where the theme predicted it. In Bartik it's at the top right corner of the Header:

Check out this question: How can I make my menu children display horizontally below my main menu?

## Drupal 8 Menu blocks configuration

Drupal 8 made changes to this system: Global menus (primary links, secondary links) have been converted into blocks.

This means that in Drupal 8 you still create a Menu with more than one level for your navigation, but the theme won't have a setting to display them or not (under Appearance). Instead, you will go straight to Blocks and place two of the same `Main navigation` blocks in regions of your choice. You can even include it twice in the same region which can be useful in your case where you want them one below the other.

Then configure each Menu block differently. The first one should always be visible and only show one level (image from D8 Docs: Menu Configuration):

The second one should only show when the parent from first level becomes active:

Although there are no theme settings anymore to turn on special areas that are styled specially as primary and secondary links, themes can still provide this through special regions. Bartik in Drupal 8 has regions called `Primary menu` and `Secondary menu` that look very similar to what they looked like in Drupal 7:

If you're creating your own custom theme you might want to create a special region for the two menus that would be displayed on top of the page.

---
Tags: blocks, navigation
---


# Question
Title: How can I avoid the installation directory appears in the site URLs?
I installed Drupal 7 through the hosting service tools, which installed Drupal inside the *drupal1* folder. All the site URLs contain the folder name.

How can I avoid the URLs contain that folder name? For example, instead of http://example.org/drupal1/about-us, the page should be available as http://example.org/about-us.

I've been able to only set the default front page alias to the root.

# Answer
## Set server DocumentRoot to Drupal folder

As mentioned by @leymannx you have to configure your server virtual host to use the `drupal1` as the DocumentRoot.

```
<VirtualHost *:80>
    ...
    DocumentRoot /path/to/drupal1/

    <Directory /path/to/drupal1>
      AllowOverride All
    </Directory>
    ...
</VirtualHost>

```

## RewriteBase on a shared host (in Drupal `.htaccess`)

If you're on a shared host you won't have access to change DocumentRoot. Instead, you can adjust RewriteBase in Drupal `.htaccess` file (or `$base_url` in `settings.php`).

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
RewriteBase /drupal1

```
> 1 votes

---
Tags: 7, uri
---


# Question
Title: How do I store the values submitted in a form in the session?
I want to submit a form and store the submitted values in the session. In Drupal 7 I just used `$_SESSION['key'] = $value;` but how do I correctly implement this in Drupal 8?

# Answer
> 13 votes
In D8 the session data is provided by a symfony session object, which is attached to the request. See this comparison of D7 against D8:

**Drupal 7:**

```
function mymodule_session_counter_increment() {
  if (!isset($_SESSION['mymodule_count'])) {
    $_SESSION['mymodule_count'] = 0;
  }

  return $_SESSION['mymodule_count']++;
}

```

**Drupal 8:**

```
class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

```

Change record: Access session data through the Request object

Session management has not changed. You don't need to do anything, because Drupal starts a session for each request automatically and you can use it right away.

Examples how to get the session:

**Procedural**

In procedural code get the request from the static wrapper `\Drupal`:

```
$request = \Drupal::request();
$session = $request->getSession();
$session->set('mymodule_value', $value);

```

**Controller**

In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from `UserController`:

```
  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    ...
    $session = $request->getSession();
    $session->set('pass_reset_hash', $hash);
    $session->set('pass_reset_timeout', $timestamp);
    ...
  }

```

It's not necessary to define the route parameter in the route definition. The request is always available.

**Form**

In a form method get the request from `getRequest()`:

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $session = $this->getRequest()->getSession();
    $session->set('mymodule_form_value', $form_state->getValue('value'));
  }

```

---

**Private Tempstore**

The private tempstore is not a replacement for sessions. It depends on the session id and it's not possible to use it without a session. So you can store the values directly in the session as well. Drupal core uses the private tempstore for big amount of data and only for authenticated users who already have a session. For anonymous users it's not easy to get a private tempstore started, because drupal uses dummy session id's until it starts a real session. If you start a private tempstore in custom code it has the wrong session id.

# Answer
> 4 votes
To temporary store data in the session, in Drupal 8.5 and higher there is the *tempstore.private* service that, for example, is used from the node edit form to temporary store the node preview.

```
  public function form(array $form, FormStateInterface $form_state) {

    // Try to restore from temp store, this must be done before calling
    // parent::form().
    $store = $this->tempStoreFactory
      ->get('node_preview');

    // Attempt to load from preview when the uuid is present unless we are
    // rebuilding the form.
    $request_uuid = \Drupal::request()->query
      ->get('uuid');
    if (!$form_state
      ->isRebuilding() && $request_uuid && ($preview = $store
      ->get($request_uuid))) {

      /** @var $preview \Drupal\Core\Form\FormStateInterface */
      $form_state
        ->setStorage($preview
        ->getStorage());
      $form_state
        ->setUserInput($preview
        ->getUserInput());

      // Rebuild the form.
      $form_state
        ->setRebuild();

      // The combination of having user input and rebuilding the form means
      // that it will attempt to cache the form state which will fail if it is
      // a GET request.
      $form_state
        ->setRequestMethod('POST');
      $this->entity = $preview
        ->getFormObject()
        ->getEntity();
      $this->entity->in_preview = NULL;
      $form_state
        ->set('has_been_previewed', TRUE);
    }

    /** @var \Drupal\node\NodeInterface $node */
    $node = $this->entity;
    if ($this->operation == 'edit') {
      $form['#title'] = $this
        ->t('<em>Edit @type</em> @title', [
        '@type' => node_get_type_label($node),
        '@title' => $node
          ->label(),
      ]);
    }

    // ...

  }

  /**
   * Form submission handler for the 'preview' action.
   *
   * @param $form
   *   An associative array containing the structure of the form.
   * @param $form_state
   *   The current state of the form.
   */
  public function preview(array $form, FormStateInterface $form_state) {
    $store = $this->tempStoreFactory
      ->get('node_preview');
    $this->entity->in_preview = TRUE;
    $store
      ->set($this->entity
      ->uuid(), $form_state);
    $route_parameters = [
      'node_preview' => $this->entity
        ->uuid(),
      'view_mode_id' => 'full',
    ];
    $options = [];
    $query = $this
      ->getRequest()->query;
    if ($query
      ->has('destination')) {
      $options['query']['destination'] = $query
        ->get('destination');
      $query
        ->remove('destination');
    }
    $form_state
      ->setRedirect('entity.node.preview', $route_parameters, $options);
  }

```

Before Drupal 8.5, the service is *user.private\_tempstore*, which will be removed in Drupal 9.0.

Since you want to store the submitted values, which I assume are used only for a limited period of time and aren't necessary anymore after the user logs in or logs out, I would use the same approach used from Drupal core to show a preview of a node before it gets created/saved. It has also the pro that deleting the data is automatically done.

# Answer
> 3 votes
Here is an article on how to use the appropriate service to store data in the session: http://atendesigngroup.com/blog/storing-session-data-drupal-8

There are two methods described in the article, here's the first one which doesn't use dependency injection. (code is not mine)

> To set temporary data:

```
// For "mymodule_name," any unique namespace will do.
// I'd probably use "mymodule_name" most of the time.
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

```

> To read temporary data:

```
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$some_data = $tempstore->get('my_variable_name');

```

# Answer
> 1 votes
Sessions (Drupal 8) are used via the simple Session implementation of SessionInterface interface.

Symfony sessions are designed to replace several native PHP functions. Applications should avoid using session\_start(), session\_regenerate\_id(), session\_id(), session\_name(), and session\_destroy() and instead use the APIs in the following section.

Sessions Drupal 8

Example:

```
use Symfony\Component\HttpFoundation\Session\Session;

$session = new Session();
$session->start();

// set and get session attributes
$session->set('name', 'Yash');
$session->get('name');

// set flash messages
$session->getFlashBag()->add('notice', 'Profile updated');

// retrieve messages
foreach ($session->getFlashBag()->get('notice', array()) as $message) {
    echo '<div class="flash-notice">'.$message.'</div>';
}

```

# Answer
> 1 votes
You can use "\Drupal::service()".

To set temporary data:

```
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

```

To read temporary data:

```
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$some_data = $tempstore->get('my_variable_name');

```

You can refer to this tutorial for more details.

# Answer
> 1 votes
Before you go rolling your own, see if the Session Node Access module does what you need.

# Answer
> 0 votes
how about ? :

```
    $session = new Session();
    $session->set('key', 'value');

    $key= $session->get("key");
    var_dump($key);

```

---
Tags: 8, sessions
---


# Question
Title: How to override page title by content type
I'm using the `pagetitle` core module to render a page title. However, for certain content types I want the ~~page~~ main title to be the **content type label** (e.g. "News") and not the **node label** (e.g. "Drupal 8 released!").

Is there a simple way to achieve it? My first guess was to use the `template_preprocess_page_title` but `$variables` has no context whatsoever about node, node type, etc...

# Answer
> 27 votes
As mentioned by Ivan Jaros You can use `hook_preprocess_page_title`.

You just have to load the node from the route first, to get some context.

```
function yourtheme_preprocess_page_title(&$variables) {

  // Load the node entity from current route
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Load the label of the bundle
    $bundle_label = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($node->bundle())
      ->label();

    // Set the page title
    $variables['title'] = $bundle_label;
  }
}

```

If you just want to use this with certain content types, you can use `$node->bundle()` to get the machine-readable name and check against it.

# Answer
> 5 votes
Linus got it right for the preprocess function, but I'd personally use this to get the current node (as it's shorter and seem easier...)

```
$node = \Drupal::request()->attributes->get('node')

```

Then to access the node title, use :

```
$title = $node->getTitle()

```

or to access another custom field (with a value) :

```
$node->get('field_MYFIELD')->value

```

Actually, access everything the way you'd access these datas in a regular node preprocess function :)

# Answer
> 3 votes
Use the Metatag module it is D8-ready already and supports what you need.

# Answer
> 1 votes
Make a small module. Two files required:

File name: liveeventtitles.info.yml

```
name: Live Event Titles
description: Programmatically generates titles for event node bundles.
package: Custom
type: module
version: 1.0
core: 8.x
dependencies:
  - node

```

File: liveeventtitles.module

```
<?php
/**
 * @file
 * Modify the node create/edit form and automatically generate a node title for event nodes.
 */
define('LIVEEVENTTITLES_PLACEHOLDER', '%LiveEventTitle%');
/**
 * Implements hook_form_alter().
 */
function liveeventtitles_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_event_form' || $form_id == 'node_event_edit_form') {
    $title_widget = &$form['title']['widget'][0];
    $default = (!empty($title_widget['value']['#default_value'])? $title_widget['value']['#default_value'] : LIVEEVENTTITLES_PLACEHOLDER);
    $title_widget['value']['#default_value'] = $default;
    $title_widget['value']['#type'] = 'value';
    $title_widget['value']['#required'] = FALSE;
    $form['title']['#access'] = FALSE;
  }
}
/**
 * Implements hook_node_presave
 */
function liveeventtitles_node_presave(Drupal\node\Entity\Node $node) {
  $type = $node->getType();
  if ($type == 'event') {
    // Load the artist node to get the title
    if ($artist_id = $node->field_artist->getString()) {
      $artist = \Drupal\node\Entity\Node::load($artist_id);
      $artist_name = $artist->title->getString();
    }
    // Load the Venue to get the title
    if ($venue_id = $node->field_venue->getString()) {
      $venue = \Drupal\node\Entity\Node::load($venue_id);
      $venue_name = $venue->title->getString();
    }
    if (!empty($venue_name) && !empty($artist_name)) {
      $node->setTitle($artist_name . ' at ' . $venue_name);
    }
  }
}

```

I probably have more than I need, such as I don't think I need a default value and PLACEHOLDER in the hook\_form\_alter() but I need to give someone a reason to vote this down (-;

# Answer
> 1 votes
In THEMENAME\_preprocess\_html(&$variables) {} there is the $variables\['head\_title'\] which is the highest hand - instance for the page title (Structured title: $variables\['head\_title\_array'\] ). There are also other interesting array keys like $variables\['page'\]\['content'\] and $variables\['node\_type'\] based on which the title can be processed.

Final thought: $variables\['head\_title'\] = \['title\_part1','title\_part2'\]; since in the html.html.twig

```
<title>{{ head_title|safe_join(' | ') }}</title>

```

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


# Question
Title: Is there an equivalent of view modes for form editing?
I have a content type with a lot of fields. End users need to create content of this type, so I want to provide them with a simplified form so that they can create a content item and edit it without knowing about the majority of the options. Then those who want to dive into the complexity could have an advanced form which exposes them.

View modes looked like the kind of thing I'm trying to do, so I used `hook_entity_info_alter` to create a custom view mode and started trying to figure out how to control the view mode used by `node/add/my-content-type`. After digging into the code I've realised that view modes are used by `node_view` and that adding or editing a content item uses `drupal_get_form` instead.

Is there some "form mode" which allows different field type and grouping configuration for different "views" onto a form?

# Answer
> 4 votes
# 1 - Panels/Page Manager

If you're using Panels and Page Manager (part of Chaos Tools) then you can break up the `node/add` form by enabling/overriding the *node\_edit* page manager handler and creating a Panels layout to show the individual fields.

Just set a variant to only react on creation of your particular content type, and then arrange the form fields as you wish. This will let you split out any form fields, as well as provide a *General form* pane that will add any fields that you've missed out.

**IMPORTANT NOTE COURTESY OF LETHARION**

Something I didn't realise due to the fact that I always put the general form on the page, is that if you DON'T output ALL fields, then "*form api will interpret it as "the user deleted the content of those fields*" and will send back empty values. This could result in the loss of existing data, so be careful.

---

# 2 - Solely Fields/Field contrib

You could also try Field Permissions if the form is permissions based, or use a Field group with some collapsed fieldsets or tabs etc to initially hide the fields if they are not permission based.

# Answer
> 1 votes
There are several options I believe could work for you....

http://drupalize.me/videos/rearrange-node-edit-form

https://drupal.org/project/msnf

https://drupal.org/project/mforms

# Answer
> 1 votes
The flexiform module can provide this feature for you. http://www.drupal.org/project/flexiform

# Answer
> 0 votes
A partial solution, which is good enough for me at present but doesn't properly deal with things like entity references, is to "borrow" a view mode's configuration in `hook_form_alter`.

```
function MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // Since this is specific to FORM_ID, I don't need to extract the entity type
  // from the form / form_state
  $type = 'the_entity_type';
  $view_mode = custom_logic_here();
  foreach (array_keys($form) as $key) {
    $instance = field_read_instance('node', $key, $type);
    if (isset($instance['display']) &&
        isset($instance['display'][$view_mode]) &&
        $instance['display'][$view_mode]['type'] === 'hidden') {
      unset($form[$key]);
    }
}

```

# Answer
> 0 votes
I believe "form modes" were added to D8 core a few months back.

There is no direct equivalent to view modes for form editing in Core.

Generally, you would use form alters to modify forms in D7.

# Answer
> 0 votes
You can use https://www.drupal.org/project/form\_mode\_manager to use form mode implemented in core D8

---
Tags: 7, forms, entities
---


title: How to change node add form

text:
# Question
Title: How to change node add form
I'm wondering how I can change the layout of the node add form in Drupal 8. in Drupal 7 I worked with Panopoly and could overwrite the url in Page Manager and add a Panels Variant. I thought it would work the same way in Drupal 8 but in the Panels variant I cannot add the form items. Thus I get a blank page on activating the variant.

Any ideas?

# Answer
> 3 votes
In drupal 8 there are new display modes. They are not only to view the node (view mode). They are also for the node add form (form mode).

For example to change the node add form of the content type article you go to:

```
/admin/structure/types/manage/article/form-display

```

Here you can select which fields you want to show and how they are formatted (field widgets). You can make more adjustments with php in form alter hooks or with twig in templates.

By default you have one form mode for each content type. You can create more if you go to the admin interface of display modes:

```
/admin/structure/display-modes

```

If you want to use different form modes for different users you can use this module:

Form mode control

Readme:

> WHAT FOR ?
>
> Form Mode Control allows you to use the form modes for any bundle / entity, per role and for edition / modification. Which means using different forms (fields, order, widgets, etc.) for different roles.
>
> HOW TO USE IT ?
>
> A - DEFAULT FORM MODES
>
> 1 - You must at first add form mode for content entities. Ex. : go to "www.your-site.com/admin/structure/display-modes/form/add" to add a new form mode.
>
> 2 - Activate the form mode for the related bundle of the right entity. Ex.if we want to activate a form mode named Super 2 (machine name = super\_2) for an article (entity type : Node, Bundle : Article). Go to www.your-site.com/admin/structure/types/manage/article/form-display and activate it.
>
> 3 - Go to www.your-site.com/admin/people/permissions, a section named Form modes control was added for all form modes activated (and only activated), So , configure all permissions and give roles permissions to access form modes. NB, the permission Access all form modes allow you to access to all form modes linked to bundle and entity type.
>
> 4 - Then configure on the Form mode control administration page (www.your-site.com/admin/structure/display-modes/form/config-form-modes) and give for each role a default form modes for creation / edition (of course, each role must have access to the form mode). B - ACCESS DIRECTLY FORM MODES You can also use it with a simple extra query in the URL (?display=machine\_name\_of\_the\_form\_mode) if the role is allowed to see it. Of course, the user must have the right permission for it. Ex. : if you want to access to super\_2, go www.your-site.com/node/add/article?display=super\_2.

# Answer
> 1 votes
Or using a the best and secure form mode system using routing with : https://www.drupal.org/project/form\_mode\_manager

---
Tags: forms, 8, panels
---


# Question
Title: How to get the current path, keeping the langcode?
For my button I need to specify the destination path, as my site is multilingual it is imporatnt for me to keep the langcode in the path. So how can I get from

```
 drupal-site/fr/page_1

```

to

```
 drupal-site/fr/page-2 ?

```

By just appending /page-2 I lose my language settings.

# Answer
> 1 votes
You can try code:

```
$langcode ='en';
$node_url = $node->getTranslation($langcode)->toUrl('canonical', ['absolute' => TRUE])->toString();

```

# Answer
> 1 votes
I figured it out

```
$path = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();

```

It returns exactly the base route with the langcode

---
Tags: 8, uri
---


# Question
Title: Keep track of which user fully downloaded a file
I'm looking for a solution to check which users fully downloaded a specific download/file. I found several solutions to detect whether a download/file is completed. F.e. https://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download But this use case is quiet different. I need to retrieve a list of people who downloaded the file afterwards.

Thanks in advance.

# Answer
> 1 votes
If you have file\_entity installed, you can use hook\_file\_transfer() with a custom function my\_custom\_registration($file, $user) that registers which user downloaded which file The starting code for that is :

```
/**
 * Implements hook_file_transfer().
 *
 * @param type $uri
 */
function my_module_file_transfer($uri) {
  global $user;
  $files = file_load_multiple(array(), $conditions = array('uri' => $uri));
  if (!empty($files)) {
    $file = reset($files);
    my_custom_registration($file, $user);
  }
}

```

hope this helps

---
Tags: 7
---


title: load paragraph in graphql

text:
# Question
Title: load paragraph in graphql
i have a content type with "artist" and i have a paragraph type with "album" name. in album i have two field 1. name 2. release date. i create a field with "field\_album" name in "artist" content type that this field reference to paragraph. now i want write a query that show artist name and all albums with name and release date. I create this query to load artist but i cant load paragraph.

```
    query{
  nodeQuery(filter: {conditions:[{field:"title",value: ["artistname"], operator: EQUAL}]}){
    count
    entities {
      ...on NodeArtist{
        nid
        title
      }
    }
  }
}

```

# Answer
for load paragraph query must like this

```
query{
  nodeQuery(filter: {conditions:[{field:"title",value: ["artistname"], operator: EQUAL}]}){
    count
    entities {
      ...on NodeArtist{
        nid
        title
        fieldAlbum {
          entity{
            ... on ParagraphAlbum {
              fieldName
              fieldReleaseDate
            }
          }
        }
      }
    }
  }
}

```

https://github.com/drupal-graphql/graphql/issues/676#issuecomment-423912937
> 1 votes

---
Tags: paragraphs
---


# Question
Title: user_role_revoke_permissions() for administrator
I am using EU Cookie Compliance module. During module installation, permission has been set to admin also. I need to revoke that permission which is assigned to Admin as cookie pop-up is coming-up for admin also. In Permissions, it is `grayed-out`. So I can't able to disable that permission.

When I used below code, it is revoking permission for all other roles but not working for Admin.

```
user_role_revoke_permissions('administrator', [
      'display eu cookie compliance popup',
    ]);

```

Please suggest me a solution how to revoke that permission for admin.

# Answer
Here is the snippet code works for @Saba `original author of the post` in case someone needs it.

```

function YourModuleName_eu_cookie_compliance_show_popup_alter(&$show_popup) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if (in_array('administrator', $roles)) {
    $show_popup = FALSE;
  }
}

```
> 1 votes

---
Tags: 8, users
---


# Question
Title: Load library dynamically depending on settings
My theme has a few settings that can be adjusted, one of them is style.

I want to load the libraries depending on the styles, but without writing them in the `.libraries.yml`

```
function my_theme_library_info_build() {
  $libraries = [];

  return $libraries;
}

function my_theme_library_info_alter(&$libraries, $extension) {
  $tmp_theme = theme_get_setting( 'my_theme' );

  $libraries['my_theme.theme']['css']['theme'] = [
      'css/themes/' . $tmp_theme . '.min.css' => [],
  ];
}

```

This is what I've got so far but I have to clear the cache after changing the style.

# Answer
I would implement this slightly differently. What you can do is combine all the different style css files into one, and use a className prefix instead of a file name prefix. So instead of having `foo.min.css` and `bar.min.css` you'll have 1 css file that's always included but has `body.foo {}` and `body.bar {}` styles in them.

Of course this gets easier with a preprocessor such as SASS: for every element you want to style you can wrap it in their respective `body.foo` or `body.bar` parents, without having to manually write `body.foo` in front of every element you want to style. So I highly recommend you use something like SASS for this, but it's not required at all.

The advantage of this method is *I think* it avoids problems with caching different CSS files since you're using only one. Also if your original goal of having separate CSS files was to keep them neat and separate then you can do that with your SASS files and they can be compiled into a minified single CSS file by your SASS processor.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Getting a 403 error in REST & 8.2.3 has no permission set for REST for GET of content
1. Enable modules (including REST UI):

2. Enable the Content in REST resources:

3. Give permissions on `/admin/people/permissions#module-rest` ??:

4. Request returns `403 Forbidden` error:

Reference: Getting a 403 error in REST

# Answer
This is a known issue with the REST UI module. REST UI has issues with Drupal 8.2 and up. There is an open issue specifically regarding this, and a much longer discussion to look into. I'd post this as a comment, rather than an answer, but I'm a new user here. Best of luck. I'm having the same problem.

## UPDATE:

I think REST UI is just a no-go for 8.2.3. Bear with me. I don't have enough reputation to post links :-/

Here is what I did to get some requests to work:

### Setting up the REST configurations

In the place of step 2 above, it seems that you need to edit the yml for the entity type you're trying to change the rest configurations for. For example, the node entity would use rest.resource.entity.node.yml (look here for some help: https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview#practical). I've been given the impression that RESTUI really just isn't useful with 8.2+, so you gotta do it by hand. Once you've created this file to your liking, you need to import it to your site.

I still can't figure out how to do this "correctly"; I don't know if you need to use the configuration importer (which will throw a UUID error) or include it in a theme or in /default/site or what. I *did* get it to work. I ended up using the Features Module to create a feature package for REST Resource Configuration (admin/config/development/features/edit), downloaded, unzipped, and installed the module created by the changes.

I then manually edited the config files in the created module's directory (DRUPAL\_ROOT/modules/MODULE\_NAME/config/install/rest.resource.entity.node.yml) to have the settings I wanted. Finally, I implemented the changes by updating the feature from the features config page (admin/config/development/features/ click on the "changed" next to the module you created, click on the checkbox next to the changes, and click "Import Changes").

There HAS to be a simpler way to handle the import, but it works for me on 8.2.3.

### User Permissions

Once your REST configurations are set up, the entity types should follow the permissions you have set in /admin/people/permissions/. So, if anonymous users can view published nodes, they should be able to GET published nodes as well, etc. (At least, according to \[the documentation\]\[1\].)

If you're still having problems, you need to make sure to include the token header usually.

### The csrfToken

A GET request to the endpoint YOUR\_SITE.DOMAIN/rest/session/token will provide you with a token which you can set as the X-CSRF-Token' header on your GET or POST request. A typical and simple example using jQuery to GET the first entry might look like this:

```
function getFirstNode() {
  jQuery
    .get('YOURSITE/rest/session/token')
    .done(function (data) {
      var csrfToken = data;
      jQuery.ajax({
        url: 'YOURSITE/web/node/1?_format=hal_json',
        method: 'GET',
        headers: {
          'Content-Type': 'application/hal+json',
          'X-CSRF-Token': csrfToken,
        },
        success: function (node) {
          console.log(node);
        }
      });
  });
}

```

### If all else fails

I've also had success setting up GET endpoints using the Views Module. This article does a pretty good job explaining the process: http://redcrackle.com/blog/rest-export-views-drupal-8. It won't work for POST requests, but it should help.

I hope this helps. It's a really sticky problem for what should be a simple request, and the documentation does NOT do a great job of making this accessible. Good luck!
> 1 votes

# Answer
After

I have found that the solution for the *403 Forbidden error* is to use this combination:

**URL**

```
http://example.com/node?_format=hal_json

```

**Raw request body**

```
{
  "_links": {
    "type": {
      "href": "http://website.com/rest/type/node/article"
    }
  },
  "title":[{"value":"test article55"}],
  "body": [{"value":"test body"}]
}

```

**Headers**

```
Authorization: Basic ....
Content-Type:application/hal+json

```
> 1 votes

# Answer
I was confused by this as well. Thanks to your post and some other reading, I figured out how to get the REST API working though.

It appears the REST UI module is still not working correctly to enable the API.

So, as already mentioned in another answer, the REST config file `rest/config/optional/rest.resource.entity.node.yml` is required to make the REST API active in Drupal 8.2+, but it's in the `optional` directory, so it doesn't appear to get applied by default (even though I think it should, if the dependencies are enabled?).

The only thing I'm adding to your answer is that the easiest way I found to update and enable the `rest.resource.entity.node` configuration is using the `drush cim` command.

I copied the `rest.resource.entity.node.yml` to a temporary directory `/app/drush/test/sync/`, edited it, and imported it using this command (from the docroot):

```
$ drush cim --partial --source=/app/drush/test/sync/

```

You can check that it worked by running this command:

```
$ drush cget rest.resource.entity.node

```

In Drupal 8.2+ users should have the same permissions to access entities via the REST API as via the web (HTML). If you set the `rest.settings` option `bc_entity_resource_permissions` to `true` however (the old style), you will need to set access permissions for the API in the Permissions panel.
> 0 votes

---
Tags: 8
---


# Question
Title: 403 Forbidden when creating a page with RESTful API
Referencing this tutorial, I am trying to create a page with RESTful API:

```
{
  "_links":{
    "type":{
      "href":"http://www.example.com/drupal/rest/type/node/page"
    }
  },
  "title":[
      {
        "value":"My first page"
      }
    ]
}

```

The POST request is: http://203.80.250.46/drupal/entity/node

The POST request headers are:

* Content-Type: application/hal+json
* PHP\_AUTH\_USER: (admin\_username)
* PHP\_AUTH\_PW: (admin\_password)

But Drupal responded with: **403 Forbidden** (Access Denied in response HTML)

Drupal 8 is installed at: http://www.example.com/drupal/

Enabled: HAL, HTTP Basic Authentication, RESTful Web Services, Serialization, REST UI

What did I miss?

# Answer
The tutorial example using Dev Client is probably what is throwing you off because `PHP_AUTH_USER` and `PHP_AUTH_PW` are not valid request headers for Drupal 8 REST. The tutorial does give a curl command using the `--user` parameter which should do the correct behavior - add an `Authorization` header. I demonstrated this by manually adding that request header in User login REST format.

```
Content-Type: application/hal+json
Accept: application/hal+json
Authorization: Basic admin_username:admin_password

```
> 1 votes

# Answer
Had the same problem and solved it in Drupal 8.6.1 (using Postman for testing):

1. Must use in the POST command the url like http://website.com/entity/node?\_format=hal\_json
2. make sure you enabled HAL and HTTP Basic Authentication, then in the Configuration REST, Enable Content rest for POS hal\_json and Basic Authentication
3. Don't know if help but made the suggested feature in Getting a 403 error in REST & 8.2.3 has no permission set for REST for GET of content
4. put Headers:

```
Authorization: Basic ....
Content-Type:application/hal+json

```
5. the Body raw looks like:

```
{
  "_links": {
    "type": {
      "href": "http://website.com/rest/type/node/article"
    }
  },
  "title":[{"value":"test article55"}],
   "body": [{"value":"test body"}]
}

```
> 1 votes

# Answer
out of the tutorial

> You should create also a new authenticated user for testing purposes. If you test your API with User 0 administrator account credentials, you will likely miss permission settings that you need to be set.

have you set permissions ?? try to create a new role with one user and make sure to give the according permissions from your content type.
> 0 votes

# Answer
I know this question is already old but I found it while diving into a quite similar situation. In your case it could be the lack of a X-CSRF Token header which is important. As indicated in the tutorial, you must visit http://www.example.com/drupal/rest/session/token and use the returned string as value for your **X-CSRF-Token** header key along with your authentication credentials.
> 0 votes

# Answer
If you're getting an HTML response in spite of specifying `Accept: application/hal+json`, it may mean that your server is blocking the request and not even sending it to Drupal. Check your Drupal's recent log reports to see if there's any error. If there is no mention of any access denied or similar errors, then you'll probably find the error in the Apache (or any other webserver) logs.

In my case, support for `PATCH` and `DELETE` had to be explicitly enabled by putting the following in my Drupal root `.htaccess` file:

```
<IfModule mod_headers.c>
  Header always set Access-Control-Allow-Methods "POST, GET, PUT, PATCH, DELETE"
</IfModule>

<Limit GET POST PUT DELETE HEAD OPTIONS PATCH>
  Order allow,deny
  Allow from all
</Limit>

```

The error I got in my Apache log was this:

```
AH01797: client denied by server configuration:

```

It does seem slightly odd for `POST` to be disabled, but this should put you on the right track to figuring out what's going wrong.
> 0 votes

---
Tags: 8
---


# Question
Title: Update entity properties fetched with entityTypeManager()->getStorage
I am loading all entity types I need to update like below

```
$current_fruit = \Drupal::entityTypeManager()->getStorage('fruit')->loadByProperties(['status' => '1']);

```

Then I update them in a way that I loop through the object and if particular value is matched I update some properties.

Thing is I am wondering is it possible to not loop through all of them, but just use some "magic" get method to find entity within loaded entities and then updated it, or is the foreach best method to do this? Something like

```
$fruit = $current_fruit->name->getByValue("Apple);

```

and then I could just use

```
$fruit->set('price', $40);
$fruit->save();

```

# Answer
> 0 votes
You can actually use `loadByProperties` as that filter, you just need to extend your search:

```
$apples = \Drupal::entityTypeManager()
  ->getStorage('fruit')
  ->loadByProperties([
    'status' => '1',
    'name' => 'Apple'
  ]);

```

If you need to filter an existing, broader list, then just use `foreach`, `array_filter`, etc; Drupal doesn't have any special methods for it.

---
Tags: 8, entities
---


# Question
Title: Group users and display the group on the profile page
How can I create a group/role/taxonomy term or anything else to group specific users ? I also want to display the "group/role/taxonomy term or anything else" on the users profile.

For example: I go to example.com/user/1 and I see all of his details **AND** that he has the administrator-"group/role/taxonomy term or anything else".

Thanks in advance (I am a noob here)

# Answer
> 1 votes
Roles have a set of permissions, so they are ideal if you will have a set of users editing certain types of content, like blog posts, and another group of user commenting on the content. You can create both new roles and permissions.

* Roles: `/admin/people/roles`
* Permissions: `/admin/people/permissions`

You can also add fields to the users, like a taxonomy where they choose whether they are a *dog person* or a *cat person*.

* Manage fields: `/admin/config/people/accounts/fields`
* Manage form display: `/admin/config/people/accounts/form-display`

Then, you can choose which fields will be displayed on the *user profile page*

* Manage display: `/admin/config/people/accounts/display`

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