# Question
Title: Programmatically delete one entry from one field on one entity
What's the proper way to programmatically delete one specific field entry for a multi-entry field from one specific entity? (that's specific fields and specific entities, not field types or instances and entity types)

Here's some possibilities I've looked into which don't work:

* Loading the entity with `entity_load()`, setting the field entry to =null or =array(), then saving with `field_attach_update()`. It's the closest I've found but it leaves a zombie null field entry in the database which shows up as a blank row on forms until the form is saved and `hook_field_is_empty()` can kick in (`hook_field_is_empty()` is configured such that =null or =array() will flag as empty).
* Loading the entity with `entity_load()`, unsetting the field entry by key, then saving with `field_attach_update()`. This seems to do nothing - it seems that Drupal interprets the entry not being there as a sign to not modify it. (strangely I also sometimes get maximum query time expiration timeouts when trying this approach)
* `field_attach_delete()` \- this is much too blunt: it kills all fields for the entity
* `field_purge_data()` \- better, but still too blunt: it kills all entries of the field, not specific entries

So to clarify, I've got code that finds (and loads) an entity which has a field that has multiple entries, and finds a specific entry on that field that needs to be removed. I want to remove that entry completely, without touching any other entries or any other fields on the entity.

# Answer
> 24 votes
If you're able to rely on the entity API module you should be able to use code similar to the following:

```
// Load some entity.
$entity = entity_load_single($entity_type, $id);

// Remove the field value.
unset($entity->field_FIELD_NAME[LANGUAGE_NONE][$index]);

// Reset the array to zero-based sequential keys.
$entity->field_FIELD_NAME[LANGUAGE_NONE] = array_values($entity->field_FIELD_NAME[LANGUAGE_NONE]);

// Save the entity.
entity_save($entity_type, $entity);

```

# Answer
> 1 votes
I needed to do this as part of a Drupal8 migration cleanup.

After some experimentation, I found that iterating and then using unset() on the delta could kill it. My example was removing a tag (hence I search for 'target\_id', not 'value' as you often would for other fields.

```
/**
 * Removes a term from a field.
 *
 * @return bool
 *   success
 */
private function removeTerm(\Drupal\node\NodeInterface $object, \Drupal\taxonomy\TermInterface $term, $field_name) {
  // Check if tag value exists already.
  // Remember they may be multiples.
  /** @var @var \Drupal\Core\Field\FieldItemList $field_values */
  $field_values = $object->get($field_name);
  foreach ($field_values as $delta => $field_value) {
    if ($field_value->getValue()['target_id'] == $term->id()) {
      unset($field_values[$delta]);
      return TRUE;
    }
  }
  return FALSE;
}

```

And afterwards, if success, then `$object->save();`

# Answer
> 0 votes
For Drupal 8, to delete a field from an entity:

```
$entity = Node::load($nid);
unset($entity->field_name);

```

This will call the magic method \__unset() from ContentEntityBase:

```
public function __unset($name) {
    // Unsetting a field means emptying it.
    if ($this->hasField($name)) {
        $this->get($name)->setValue([]);
    }
    // For non-field properties, unset the internal value.
    else {
        unset($this->values[$name]);
    }
}

```

Don't forget that, to persist your changes, you need to call

```
$entity->save();

```

After you've done all your changes.

# Answer
> -1 votes
This is better way:

```
> $user = user_load($user->uid);
> $user_wrp = entity_metadata_wrapper('user', $user);
> $user_wrp->{'field_data_multiple'} = array();

```

# Answer
> -2 votes
the current preferred method would employ the entity\_metadata\_wrapper

```
$node_wrapped = entity_metadata_wrapper('node', node_load($nid));

unset($node_wrapped->$field_name[$index];

```

this is the best tutorial on the EMW that i've seen http://deeson-online.co.uk/labs/programatically-access-field-data-using-entitymetadatawrapper-drupal

---
Tags: 7, entities
---


title: Behaviour attach triggering twice

text:
# Question
Title: Behaviour attach triggering twice
At some point in an update in the last few months, Drupal (7) started routinely triggering attached behaviours twice.

At first I thought "this is my fault, my behaviours should check to see if they've been run in this context already", and I set about using jQuery's `once()` (and other such solutions).

However I'm convinced now that this is a wider problem. e.g. the `admin_menu` module generates 2 admin menus.

Has anyone found this and the cause of it and a solution (beyond patching every module in use to check for duplicate calls)? I'm not sure where to start looking!

Nb. I've said "drupal" is doing this, I suppose it could be a contrib module that's causing the behaviour. I've seen it across several sites (I manage a dozen or so)

# Answer
> 1 votes
I put a breakpoint on one script's attach behaviours and inspected the call stack both times it was called.

The first time was expected, from drupal.js, and the second turned out to be from a call in the EU Cookie Compliance module. This turned out to be a bug in the EU Cookie Compliance module.

Thanks for comments. I'll leave this here in case anyone else of the 70.5k users of that module experience the same issue!

---
Tags: 7
---


# Question
Title: Error when upgrading to Drupal 8.7.1 on module menu_link_content
When running database updates (on domain.com/update.php) from 8.6.15 to 8.7.1, I got the following error:

```
module menu_link_content
Update make_menu_link_content_revisionable
Custom menu links have been converted to be revisionable.
Failed: InvalidArgumentException: Placeholders must have a trailing [] if they are to be expanded with an array of values. in Drupal\Core\Database\Connection->expandArguments() (line 735 of /baseserverpath/public_html/web/core/lib/Drupal/Core/Database/Connection.php)

```

I can see the error "Placeholders must have a trailing \[\] if they are to be expanded with an array of values" happens on several different occasions in Drupal 8, as there are some different posts on the issue dating back to 2016. But I cannot find it related specifically to module 'menu\_link\_content'. I wonder if the problem could be related to a special character that cannot be correctly escaped.

The upgrade doesn't work and some other database upgrades get stuck in the queue, since this one for 'menu\_link\_content' cannot be completed.

# Answer
> 0 votes
I got this error, but when I had run the update with **drush updatedb -y** command, I resolved that.

---
Tags: database, navigation, upgrading
---


# Question
Title: Date is wrong in storage but correct on display?
I am trying to programmatically load a node and get its date time value. The default format is HTML5 date, long date. I load it and I get the field value with the following code.

```
dpm($record['nid_value']);
$entity = \Drupal\node\Entity\Node::load($record['nid_value']);
dpm($entity->get('field_date_range')->value);

```

The output is the following one.

```
740
2018-02-23T02:00:00
734
2018-02-23T00:00:00

```

Why is it stored as *2018-02-23T02:00:00* when the real date is *Thursday - February 22, 2018 - 4:00pm to 5:00pm*?

The field type is *date range*; the display type is *smart range*. When you view the node, it looks perfect. The display is correct. If I create a view, it also outputs the incorrect date, no matter what format I chose on the field output. Time zone has been forced.

Can anyone point me in the right direction here?

**UPDATE - Here was the solution to my problem**

```
$nid = 411;
$entity = \Drupal\node\Entity\Node::load($nid);
$dval = $entity->get('field_date_range')->value();
$dt = new DateTime($dval, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone('America/Los_Angeles'));
$date_to_print = $dt->format('g:ia \o\n l jS F Y');
//$date_to_print = $dt->format('m-d-Y h:m:i');
echo $date_to_print;
//output: 12:00pm on Saturday 24th February 2018

```

# Answer
Datetime and Daterange fields are stored in UTC in the database (the storage) and converted to the time zone on output. This is done because the system supports users across the world, so everything is normalized to UTC.

Basically, when you use the UI the field widget takes the input value, and converts it from the user's time zone per system configuration to UTC (see `DateTimeWidgetBase::massageFormValues()`). The actual format in storage is the ISO equivalent to the PHP format *Y-m-d\TH:i:s*.

When output, it takes loads the UTC value, and converts it to the user's time zone per system configuration or uses the forced time zone (the time zone override). See `DateTimeDefaultFormatter::formatDate()` for an example, and also `DateFormatter::format()`.

By default, views output field values using the formatters, so the same rules apply.
It sounds like you may have an override in the view settings for the field.
> 5 votes

# Answer
I solved the issue like that for type Time Range field.

I also using a custom format because the format is different for each language (translate format). /admin/config/regional/date-time

```
$from = \Drupal::service('date.formatter')->format($range['from'], 'custom_time_format', '', 'UTC');
$to = \Drupal::service('date.formatter')->format($range['to'], 'custom_time_format', '', 'UTC');

```
> 0 votes

---
Tags: 8, datetime
---


# Question
Title: Are there specific cache tags which get reset on user login?
**Scenario**

I'd like to invalidate a set of caches based on user id upon user login. I'd like to avoid creating new tags, and limit new code as much as possible. Presumably the way to do this is with cache tags.

The specific use case is to cache a user-specific web service response, per user, for the duration of a user session.

Are there any existing cache tags (or something to similar effect) which are invalidated upon successful user login, so that I don't have to implement `hook_user_login()` to manually invalidate the cache?

# Answer
> 1 votes
No, there aren't any cache tags invalidated upon login. And even if there were, they wouldn't be tied to your cache. Instead, you should act on hook\_user\_login(), and expire the cache yourself.

Cache invalidation isn't really something you would piggy back onto something non-relevant. Rather, you set up elements with cache tags/contexts etc, and then if necessary you add your own cache invalidation on relevant events.

---
Tags: caching
---


title: Redirecting old file URLs (no pattern)

text:
# Question
Title: Redirecting old file URLs (no pattern)
running Drupal 7.65.

Our previous website manager moved us from Drupal 6 to Drupal 7 and cleaned up the file structure on our server.

While all the files that are now on our website have clean and organised URLs, and all general URLs on our website are now clean, Google still has indexed our old URLs.

e.g.:

> old: domain.com/program-name
>
> new: domain.com/programname

and

> old: domain.com/sites/default/files/documents/owl-final-final3.pdf
>
> new: domain.com/sites/default/files/folder1/folder2/owlguide.pdf

So if someone googles 'program name' or googles for our 'owl guide', the Google result takes them to the old URLs (broken links) rather than the new URLs.

Is there a way I can redirect these broken links to e.g. a search page on our website, rather than the "404 page not found" page?

For some of the old URLs to our pages (e.g. /program-name rather than /programname) I've been able to set up URL aliases to redirect people but don't know how I can do so for the files when there are so many that I wouldn't be able to work out.

Sorry if I haven't used the right words, I'm not a web developer! I looked into Pathologic but don't think it addresses the problem we're having...

# Answer
Goto `http://YOURSITE/admin/config/system/site-information` and under "ERROR PAGES " change "Default 404 (not found) page" to your search page. In this way, Drupal will redirect all 404 pages to the page that you have provided.
> 0 votes

---
Tags: search, redirection
---


# Question
Title: How to call a function in a form from another form?
I have 2 forms: `distribution_inscription_table_form` and `distribution_inscription_for_user_form` in the same custom module (`amap`).

```
namespace Drupal\amap\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DistributionInscriptionTableForm extends FormBase {
  public function getFormId() {
    return 'distribution_inscription_table_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    some code...
    $rows = $this->_listEnrolments();
    some code...
    return $form;
  }
  public function _listEnrolments() {
    some code...
    return $rows;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {
    some code...
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    some code...
  }
}

namespace Drupal\amap\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DistributionInscriptionForUserForm extends FormBase {
  public function getFormId() {
    return 'distribution_inscription_for_user_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $rows = ????_listEnrolments(); <--------
    return $form;
  }
}

```

As they share a significant part of code; I put this code in a public function `_listEnrolments` located in the first form.
How can I call this function from the other form?

# Answer
> 1 votes
> As they share a significant part of code; I put this code in a public function \_listEnrolments located in the first form.

If it's functionality that two classes share equally, neither class should own it; it should be in a service, and the service should be injected into each form class. Otherwise you'll have to do something pretty awkward (and not good practice) to get an instance of the form class which implements the method to work with.

The Dependency Injection for a Form docs page should get you most of the rest of the way.

# Answer
> 2 votes
I created `amap.services.yml`

```
services:
  listenrolments:
    class: Drupal\amap\ListEnrolments
    arguments: []

```

and `ListEnrolments.php`

```
<?php
namespace Drupal\amap;
class ListEnrolments {
  public function __construct() {
  }
  public function list() {
    some code...
    return $rows;
    }
}

```

and in my two forms, inserted

```
$rows = \Drupal::service('listenrolments')->list();

```

at the right place.
And it works!

---
Tags: 8, forms
---


title: Editing CSS without module/plugin

text:
# Question
Title: Editing CSS without module/plugin
I am working on a website developed by a previous developer so I am studying how I can edit the style without source code or any extension... is there any possibility to do it?

# Answer
No, that's not possible; Drupal doesn't have an interface for editing CSS out of the box.

You'll either need to get into the code, or install/develop a module like CSS Editor.
> 0 votes

---
Tags: blocks
---


# Question
Title: Enabling a contributed module under certain path only
Is it possible to enable a certain custom module under specific path only e.g. `/store`, and not load under other sections of a website? I am using Drupal 7.

# Answer
Well yes you can ... **but you shouldn't** you may want to think of the code quality of the custom module, because it should only be responsible for the exact functionality you require.

I say you can because yes:

```
//Enable.
$modules = ['custom_scarry_module'];
module_enable($modules, TRUE);

// Disable.
if (module_exists('custom_scarry_module')) {
  module_disable(['custom_scarry_module']);
}

```

But again perhaps **rethink the "why"** aka what Jaypan said.
> 0 votes

# Answer
Drupal looks for modules in the following directories inside the Drupal root directory. (The directories are listed in the order they are used when looking for modules.)

* modules
* profiles/$profile/modules
* sites/all/modules
* $conf/modules

*$profile* is the name of the profile used for the installation; *$conf* is the directory containing the *settings.php* file used for the site, which normally is sites/default.

Outside of those directories, and their sub-directories, Drupal doesn't look for modules.

Editing the sites.php file, you could tell Drupal the *settings.php* file to use is /store/settings.php. In that case, Drupal would look for modules in /store/modules, but also in the other directories I listed, including the *modules* directory, where Drupal core modules are.

To answer the question: No, it's not possible to make Drupal install and enable modules that are only in a specific directory and not other directories.
> 0 votes

---
Tags: 7
---


# Question
Title: What is needed to keep parent menu element active while browsing subpages (Bartik Theme)
Let's say we have 2 sections with pages like this structure:

```
/section1 *
/section1/page1-1 **
/section1/page1-1/page1-1-1 **
/section1/page1-1/page1-1-2 **
/section1/page1-2 **
/section1/page1-3 **

/section2 *
/section2/page2-1 **
/section2/page2-2 **

```
* = Link in main menu / \** = Link in custom menu (sidebar)

and so on.

The main menu of Bartik theme is not supporting sub-links, so I created custom menus, which are visible to each section (content type pages) in the sidebar.

Now I want to have the main navigation element of section1 root (/section1) be always having css-class "active" if any subpage of section1 is being browsed.

Any tips? I'm new to Drupal and don't want to mess up my installation.

# Answer
> 0 votes
There are differences in how to handle navigation levels between Drupal 7 and 8.

It's customary in both versions to create one menu even when you have "sub-items", you just indent the sub-items so they "belong" to another item as a "child-parent" relationship (use the `Edit > Parent Link` and `Show row weights` if you're not using drag and drop (javascript) in your interface).

## Use Menu settings in Drupal 7

In Drupal 7 you have Menu settings where you can choose which Menu to use as Main links and which to use as Secondary links. In the case where you created one menu for both you select the same Menu for both options:

## Use Block Menu levels in Drupal 8

In Drupal 8 there are no Menu settings for navigation levels. Instead, you configure the Blocks for your Menu with the **Menu levels** options:

**Initial visibility level**
**Number of levels to display**

Add *the same* Menu Block *twice*, but configure the levels differently.

For the first level of navigation those Block Menu level numbers should be:

1
1

and for the Secondary level that only shows up when the "parent" is active they should be:

2
2

---

You can read a bit more in this article: Primary and Secondary Navigation in Drupal 8

---
Tags: navigation
---


# Question
Title: 'image_style' entity with ID 'media_library' already exists
Recently updated Drupal to 8.7.1 and I am seeing the following error when running database update:

```
www-data@php.container:/var/www/html/web $ drush updb -y
The following updates are pending:

media_library module :
  8701 -   Create the 'media_library' image style.
  8702 -   Updates the media library view widget display (contextual) filters.

comment module :
  Add comment settings.

media_library module :
  Create and configure Media Library form and view displays for media types.
  Add a table display to the media library view and link gridtable displays.

media module :
  Keep media items viewable at media{id}.

menu_link_content module :
  Update custom menu links to be revisionable.

system module :
  Initialize 'expand_all_items' values to system_menu_block.
  Clear the menu cache.   @see https:www.drupal.orgprojectdrupalissues3044364

taxonomy module :
  Update taxonomy terms to be revisionable.
  Remove the 'hierarchy' property from vocabularies.

views module :
  Update exposed filter blocks label display to be disabled.
  Rebuild cache to allow placeholder texts to be translatable.

Do you wish to run all pending updates? (y/n): y
'image_style' entity with ID 'media_library' already exists.                                          [error]
Performing media_library_update_8701                                                                     [ok]
Failed: 'image_style' entity with ID 'media_library' already exists.                                  [error]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.                                                                             [ok]

```

# Answer
I was able to fix this by doing the following:

Removing the media\_libary (I'm using git but if not you can move it somewhere):

```
rm image.style.media_library.yml
rm views.view.media_library.yml

```

Run configuration import:

```
drush cim -y

```

Now run database update:

```
drush updb -y

```

Now add the removed config items back in:

```
git checkout ./

```

Run configuration import again:

```
drush cim -y

```

Now you should be all set.
> 1 votes

---
Tags: 8, media
---


# Question
Title: How do I provide a field storage definition for hook_entity_bundle_field_info?
The documentation says:

> Bundle fields either have to override an existing base field, or need to provide a field storage definition via hook\_entity\_field\_storage\_info() unless they are computed.

How can I do that?

I tried something like this:

```
/**
 * Implements hook_entity_field_storage_info().
 */
function km_mod_entity_field_storage_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $definitions['field_metatags'] = \Drupal\Core\Field\BaseFieldDefinition::create('metatag')
      ->setName('field_metatags')
      ->setLabel(t('Metatags'))
      ->setTranslatable(TRUE)
      ->setCardinality(1)
      ->setTargetEntityTypeId($entity_type->id());
    return $definitions;
  }
}

/**
 * Implements hook_entity_bundle_field_info().
 */
function km_mod_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {

  if ($entity_type->id() === 'node') {
    $fields = [];

    $fields['field_metatags'] = BaseFieldDefinition::create('metatag')
      ->setLabel(t('Metatags'))
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'metatag',
        'weight' => 50,
      ));

    return $fields;
  }
}

```

It does not work as intended though. The field does not appear during Form display, and when trying to save:

```
Drupal\Core\Entity\EntityStorageException: Table mapping contains invalid field field_metatags. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save()

```

I've checked the field storage config yaml (by creating the field manually) and it doesn't really look any difference to how I try to configure it:

```
uuid: 4c6ecbd5-49b3-4305-8f47-518f76a917f7
langcode: sv
status: true
dependencies:
  module:
    - metatag
    - node
id: node.field_yaay
field_name: field_yaay
entity_type: node
type: metatag
settings: {  }
module: metatag
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

I have run `drush entity-updates` as well, with no luck.

**So what am I doing wrong?**

# Answer
I ran into the same issue. It looks like there might be a problem with Core.

This patch attached to the issue "Hook entity\_field\_storage\_info is broken" fixed things for me.
> 1 votes

# Answer
For fix this error i created a class *FieldStorageDefinition*

```
use Drupal\Core\Field\BaseFieldDefinition;

class FieldStorageDefinition extends BaseFieldDefinition {

  /**
   * {@inheritdoc}
   */
  public function isBaseField() {
    return FALSE;
  }

}

```

for created the fields use the class **FieldStorageDefinition** not **BaseFieldDefinition**

```
$fields['field_metatags'] = FieldStorageDefinition::create('metatag')

```
> 1 votes

---
Tags: 8
---


# Question
Title: Using hook_entity_base_field_info for adding new field
Is it fine to implement `hook_entity_base_field_info` to add a new field to the advanced group in each node?

If so, how is the storage handled by default for base fields? Should I need to create a schema to store the field value.

# Answer
As said in the other answer, the entity storage internally handles the schema.

Here is an explanation for it, taken from the documentation

> If your field doesn't have any special requirements Entity Field API can take care of the database storage and update the database schemas accordingly. This is the default for fields that are not marked as being a computed field (setComputed(TRUE)), or has specifically indicated to provide its own field storage (setCustomStorage(TRUE)).

Say you want to add a new base field to all Node entities that contains a simple boolean value to indicate whether the content is "highlighted".

```
<?php
/**
 * Implements hook_entity_base_field_info().
 */
function MYMODULE_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();

  // Add a 'Highlight' base field to all node types.
  if ($entity_type->id() === 'node') {
    $fields['highlight'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Highlight'))
      ->setDescription(t('Whether or not the node is highlighted.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
      ))
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}
?>

```

Now all it takes is to visit update.php to run the database updates, and an additional 'highlight' column will be added to the tables holding the node data.

To run this database update automatically when your custom module is enabled or disabled, you can trigger it by executing the event listeners that are responsible for performing these updates in your hook\_install() and hook\_uninstall() implementations:

```
<?php
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Create field storage for the 'Highlight' base field.
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getFieldStorageDefinitions('node')['highlight'];
  $entity_manager->onFieldStorageDefinitionCreate($definition);
}

/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getLastInstalledFieldStorageDefinitions('node')['highlight'];
  $entity_manager->onFieldStorageDefinitionDelete($definition);
}
?>

```
> 12 votes

# Answer
Deleting field definitions in `hook_uninstall` like suggested leads to conflicts. My working solution in Drupal 8.7 (can also be used for drupal 9)

mymodule.module:

```
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = [];

  if ($entity_type->id() === 'my_entity') {
    $fields['newfield'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('New field'))
      ->setSetting('target_type', 'node')
      ->setSetting('handler', 'default')
      ->setRequired(FALSE);
  }

  return $fields;
}

```

mymodule.install:

```
<?php
/**
 * Implements hook_install().
 */
function mymodule_install() {
  $entity_type = \Drupal::entityTypeManager()->getDefinition('my_entity');
  \Drupal::entityDefinitionUpdateManager()->updateEntityType($entity_type);
}

/**
 * Implements hook_uninstall().
 */
function mymodule_uninstall() {
  $entity_type = \Drupal::entityTypeManager()->getDefinition('my_entity');
  \Drupal::entityDefinitionUpdateManager()->updateEntityType($entity_type);
}

```
> 4 votes

# Answer
I did as SpadXIII's comment suggested, and it worked for me with Drupal 8.5.1.

In my custom module, I added the mymodule\_update.php file, with the following code.

```
function mymodule_post_update_someName() {
  $field_manager = \Drupal::service('entity_field.manager');
  $field_storage_manager = \Drupal::service('field_storage_definition.listener');
  $definition = $field_manager->getFieldStorageDefinitions('table_name')['field_name'];
  $field_storage_manager->onFieldStorageDefinitionCreate($definition);
}

```
> 2 votes

---
Tags: entities, 8
---


title: Stale Pathauto Alias

text:
# Question
Title: Stale Pathauto Alias
I'm just curious how other Drupal developers handle nested path aliases when they are based on another page's url pattern.

I have a product landing page (it's a "basic page" node). When it's created, right now, the url is:

`/product`

For my product nodes, I set up a path alias to be

`/product/[node:title]`

This makes my product detail pages nicely nested under "product." This works fine for a while. But later, if someone changes the product landing page url, the alias for the product nodes will not match.

Say someone edits the product landing url to be:

`/widgets`

Then I have a `/widgets` landing page and a bunch of product nodes with urls like `/product/product-name`.

Is there a nice way to handle this? Or is it up to content creators to just know they need to update it?

# Answer
You should use Pathauto if you aren't already.

This has a feature (tab) that lets you bulk update the content type urls to `/widgets/[node:title]`.

You should also install the Redirect module, so that all your former `/products/[node:title]` automatically redirect to `/widgets/[node:title]`. This is for SEO purposes, you don't want your Google listing pointing to a broken link, non-existent page.
> 1 votes

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


# Question
Title: How should I configure the trusted hosts setting?
I am trying to add the Trusted Host setting. I copied the code directly from the settings.php file, making sure I removed the * and changed the example to my domain. Using the first example

```
$settings['trusted_host_patterns'] = array(
  '^www\.example\.org$',
);

```

The site would not load....got an error stating domain was disallowed

Today using this code and

```
$settings['trusted_host_patterns'] = array(
  '^example\.org$',
  '^.+\.example\.org$',
);

```

I am getting an unexpected error and the site won't load

This is a new site on a shared host. It can't be this difficult! I must be missing something!

# Answer
I don't know if I was introducing a problem by editing the settings.php off line and then uploading it but decided to edit it with the editor in the file manager on cpanel. I first changed the permissions on the default folder to 755 and opened the folder. Then I highlighted the settings file and changed the permissions to 755. Then I clicked the edit button and located the Trusted Host settings and copied the code. I then pasted it AT THE END of the settings.php file and made the necessary changes to reflect my domain and saved the file and closed the setting file. In a different window, I had the website status page loaded and just refreshed it. IT worked! I don't know why doing it this way worked (editing the file on the server vs offline and uploading it.) but it did! Then I just change the file permissions back to what they were .
> 2 votes

# Answer
Be sure that the uncommented lines are NOT within the original comments. For example, the following will NOT work, even though they have been "uncommented", because they are still within the opening /\** and closing \*/ comments

```
/**
 * Trusted host configuration.
 *
 * For example:
 * @code
 * $settings['trusted_host_patterns'] = array(
 *   '^www\.example\.com$',
 * );
 $settings['trusted_host_patterns'] = array(
   '^www\.realsitename\.com$',
 );
 * @endcode
 * will allow the site to only run from www.example.com. *
 *
 */

```

Adding it after the closing \*/ (or at the very end, but that makes it hard to find) will work:

```
/**
 * Trusted host configuration.
 * (snipped)
 */
 $settings['trusted_host_patterns'] = array(
   '^www\.realsitename\.com$',
 );

```
> 0 votes

# Answer
Use the following code at the end of `sites/defaut/settings.php` file

```
/**
 * Trusted host configuration.
 * (snipped)
 */
 $settings['trusted_host_patterns'] = [
 '^localhost$',
 '^127\.0\.0\.1$',
 ];

```

You need to look at this link also For a status check reports
> 0 votes

---
Tags: 8
---


# Question
Title: JSON:API to Migrating Taxonomy References isn't mapping
OK, for a number of reasons I'm doing a Drupal 8 - Drupal 8 migration using the JSON:API module on the source site. I've run into an issue attaching taxonomy terms to nodes. Here's as far as I've gotten :

1) I created a vocabulary called "Photo Categories"

2) I've created and run import\_drupal\_taxonomy\_photo\_categories to import the terms. This works perfectly. I have manually checked to ensure they all get in. I use the UUID as the migration's unique identifier.

3) I have a content type called Photos, it has a field called Photo Category which references the Photo Categories vocabulary.

4) From the source JSON in the relationships section I see this:

```
"field_photo_category": {
   "data": [
     {
       "type": "taxonomy_term--photo_categories",
       "id": "84c1e8bd-16f7-429f-b299-50fe43297d47"
     },
     {
       "type": "taxonomy_term--photo_categories",
       "id": "00931a31-d129-4c55-a962-f7ba11fed5a4"
     }
  ],
  "links": {
    "self": "https:\/\/seanreiser.com\/jsonapi\/node\/photo\/1396b571-0ece-4a07-ab17-7327e030dfb5\/relationships\/field_photo_category",
    "related": "https:\/\/seanreiser.com\/jsonapi\/node\/photo\/1396b571-0ece-4a07-ab17-7327e030dfb5\/field_photo_category"
  }
}

```

5) In the source \> Fields section of import\_drupal\_type\_photo I have:

```
-
  name: field_photo_category
  label: 'Field Photo Category'
  selector: /relationships/field_photo_category/data

```

6) In the process section I have:

```
  field_photo_category:
    plugin: iterator
    source: field_photo_category
    process:
       plugin: migration_lookup
       migration: import_drupal_taxonomy_photo_categories
       source: id

```

As I understand it this should loop through the field\_photo\_category.data and do a migration lookup on each id. But nothing is getting mapped.

I have verified that the ids match the ids in the data section match the UUID from the taxonomy term JSON. I have checked the database and verfied that ids appear in migrate\_map\_import\_drupal\_taxonomy\_photo\_categories.soure1 and they map to the appropriate tids.

I have installed the migrate devel module and when I run the migration with --migrate-debug this is what the destination section look like:

```
  'field_photo_category' => array (2) [
        array (1) [
            'source' => string (36) "84c1e8bd-16f7-429f-b299-50fe43297d47"
        ]
        array (1) [
            'source' => string (36) "00931a31-d129-4c55-a962-f7ba11fed5a4"
        ]
    ]

```

So, my question, what am I doing wrong? I have the rest of this part of my migration laid out and this seems to be the final obstacle.

Thanks in Advance

# Answer
Entity reference fields need to fill their `target_id` column

```
field_photo_category:
  plugin: sub_process
  source: field_photo_category
  process:
    target_id:
       plugin: migration_lookup
       migration: import_drupal_taxonomy_photo_categories
       source: id

```
> 4 votes

---
Tags: taxonomy-terms, migrations
---


# Question
Title: Only display profile edit button on personal profile page
I'm using the profile module and am trying to display a profile edit button on your personal profile page.

my profile.html.twig:

```
<div class="m-section__content a-container">
{% if is_current_user %}
  <div class="a-container u-margin-bottom">
    <div class="a-cta ">
      <a class="a-cta__container" href="{{ url }}/edit">
        <span class="icon-arrow-right a-cta__icon"></span>
        <span class="a-cta__text">{{ "Edit profile"|t }}</span>
      </a>
    </div>
  </div>
  {% endif %}
  <div class="u-grid u-grid--with-margins">
    <div class="u-grid__col-7-12">
      <table class="m-table">
        <tbody>
          <tr>
          {{ content|without('field_image', 'field_extra', 'field_tags') }}
          </tr>
        </tbody>
      </table>
      <p>{{ content.field_extra }}</p>
    </div>
    <div class="u-grid__col-5-12">
      {{ content.field_image }}
      {{ content.field_tags }}
    </div>
  </div>
</div>

```

The a-container div may only be displayed if the current user id is equals to the user id of the user linked to the profile that's being displayed.

I'd like to make this check in a preprocess function and return a bool 'is\_current\_user' to profile.html.twig but I'm stuggling to find the right hook for the profile page.

I'm on drupal 8.7.1.

Thanks in advance!

# Answer
> 0 votes
Found the answer in access the user associated with a profile.

It was simply **THEME\_preprocess\_profile**.

---
Tags: theming
---


# Question
Title: Different front page for anonymous users and authenticated users
I have an app in Drupalgap. I would like to display a different frontpage for anonymous users and authenticated users, for example /dashboard for the first and /user\_listing for the last.

I have read "Display Different Text for Anonymous and Authenticated Users", but it is not the same scenario. (`/user_listing` has `['access user profiles']` as `access_arguments`.)

I also have tried with `drupalgap_goto()` without succeed.

How can it be done?

# Answer
You can achieve this using Context Reaction: Front page module, which extends the great Context module.

Create a new context and:

1. Add a condition for *User role*
2. Add a reaction *Front page* putting the path for the roles you want to affect.

Save the context and all should be done.
> 1 votes

# Answer
You can use the same page for both, and then render different things depending on if they are logged in or not:

```
function my_front_page_callback() {
  var content = {};
  if (!Drupal.user.uid) {
    content.foo = {
      markup: '<p>You are NOT logged in...</p>'
    };
  }
  else {
    content.bar = {
      markup: '<p>You are logged in...</p>'
    };
  }
  return content;
}

```
> 1 votes

# Answer
drupalgap\_goto() worked for me.

I have front page set to go to qleva\_start which has this page callback:

```
function qleva_start_page() {
  try {
    if (drupalgap_user_has_role('authenticated user')) {
      drupalgap_goto('qleva_start_auth');
    }
    else {
      drupalgap_goto('user/login');
    }
  }
  catch (error) { console.log('qleva_start - ' + error); }
}

```

so if anon, front is login page and if authenticated, it is qleva\_start\_auth
> -1 votes

---
Tags: javascript
---


# Question
Title: Why is my website often put in maintenance mode by itself?
My website in maintenance mode by itself. But other sites is work well, only this site has this problem. Some people encountered this kind of situation? Thank for help..

# Answer
Usually, a Drupal site enters in maintenance mode by itself because is having problems to access to its database or when is set on that mode through the option located at "admin/config/development/maintenance".

If you are not able to log in on the site, that could indicate Db problems.

Check...:

* at "admin/config/development/maintenance" is checked the option "Put site into maintenance mode". Or with drush: drush vget maintenance\_mode
* the settings.php if the Drupal database parameters are ok.
* the status of the Drupal database, (if the user:password are correct, if the database server is online).
* the error logs (MySQL, PHP, Drupal).
> 1 votes

# Answer
The problem is with the Backup and Migrate module. For some reason, sometimes something fails with the backup every once in a while. The problem is the site is put into maintenance mode, then the issue happens and then the site is not taken out of maintenance mode.

**Solution**: Go to the profile section in Backup and Migrate module. Click into your profile and in the 'Advance Settings' section "uncheck" the put site into maintenance mode option. Done.
> 1 votes

---
Tags: maintenance-mode
---


# Question
Title: How do I a custom entity operation with a webform submission?
My lack of D8 experience is going to show by just how many unknowns I have here. I hope someone can link some of the pieces for me.

I created a custom action using `hook_entity_operation_alter()` on the *admin/structure/webform/manage/dis\_document\_generator/results/submissions* page as you can see below. I'm guessing this will show up on various other pages to which is fine.

Currently as you can see the url is set to the current page but this needs to change once I have a controller redirect to. Also, it would be nice to add this operation through a controller instead of a hook but that's not important at the moment.

```
    /**
     * Implements hook_entity_operation_alter()
     */
    function dis_doc_gen_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity) {
      if ($entity->getEntityTypeId() === 'webform_submission' && $entity->bundle() === 'dis_document_generator') {

        static $operation;
        static $permission;

        if (is_null($operation)) {
          $user = \Drupal::currentUser();
          $permission = $user->hasPermission('utilize mq client');

          $url = \Drupal\Core\Url::fromRoute('<current>');

          $operation = [
            'title' => t('Send XML'),
            'weight' => 8,
            'url' => $url,
          ];
        }

        if ($permission) {
          $operations['send_xml'] = $operation;
        }
      }
    }

```

I was using **WebformSubmissionNotesForm.php** as a sample to create a controller because it looked relatively simple but I'm not sure if it's a best choice because I don't actually need a form. I'm just going to perform an action and then return however using it for now.

The router for it is this:

```
entity.webform_submission.notes_form:
  path: '/admin/structure/webform/manage/{webform}/submission/{webform_submission}/notes'
  defaults:
    _entity_form: 'webform_submission.notes'
    _title_callback: '\Drupal\webform\Controller\WebformSubmissionViewController::title'
  requirements:
    _entity_access: 'webform_submission.notes'

```

With my module being called dis\_doc\_gen I gather that my router details should look like this?:

```
dis_doc_gen.webform_submission.sendxml:
  path: '/admin/structure/webform/manage/{webform}/submission/{webform_submission}/sendxml'
  defaults:
    _entity_form: 'dis_doc_gen.sendxml'
    _title_callback: 'Send XML'
  requirements:
    _entity_access: 'dis_doc_gen.utilize_mq_client'

```

where my permission is called `utilize mq client` and so I believe it would be represented here as `dis_doc_gen.utilize_mq_client`.

Finally, *WebformSubmissionNotesForm.php* sits under `webform/src`. The one plugin I managed to do for my webform had to go under `webform/src/Plugin/WebformHandler` so I'm wondering since this is off a webform submission whether I need to place a controller at:

* `webform/src` or
* `webform/src/Plugin/WebformHandler` or
* `webform/src/Plugin/WebformSubmissionHandler`.

Last, webform defines `WebformSubmissionNotesForm` in it's header like this:

```
<?php
/**
 * Defines the WebformSubmission entity.
 *
 * @ingroup webform
 *
 * @ContentEntityType(
 *   handlers = {
 *     "form" = {
 *       "notes" = "Drupal\webform\WebformSubmissionNotesForm",

```

Since I can't have that hardcoded like that for my new controller I gather that's fine because I can just attach my controller through the interface.

# Answer
> 1 votes
It seems the answer came from spending a day (and a bit) just studying the inner workings of D8 and realizing just how much is done for you that wasn't the case in D7.

Ultimately I want to send the action to a Controller, not a plugin and the primary source for getting enough grounding to figure it out came from the following:

---
Tags: 8, webforms
---


# Question
Title: How to keep my Bootstrap sub-theme without using the CDN?
I created a sub-theme bootstrap version of CDN.

I based on "Journal" version "3.3.6" and I personalized my style.css file with 900 lines.

https://bootswatch.com/

I no longer wish to use the CDN, but I like to keep my current theme "Journal" and my custom style sheet.

How can I do this without using "less"?

What I want is to work with CSS

I asked this question several weeks ago but I still have not found a solution :

Install without Bootstrap CDN

Zuzuesque thank you your solution works, but I am having display problem :

* I no longer have the "glyphicons"
* The menu bar is not displayed correctly
* The admin menu is hidden by the menu bar

# Answer
You will need to switch the module you are using - Bootstrap Library is not suited to be used without CDN. The main function this module provides is connection to a CDN of your choice - not provide a theme (or css) itself.

The module you will want to use is the Bootstrap Theme. This one provides a sub-theme you can expand upon.

To get the Bootstrap Theme going:

1. Disable your old Journal theme + move it from the theme folder - that's important. (Maybe make a backup somewhere).
2. Download the Bootstrap Theme from the Drupal site and put it in your theme folder. (And leave it there)
3. Create a subtheme following the instructions for the less-starterkit (you wont need to touch less no worries) here: Sub-Theming Bootstrap. Basically you copy the `bootstrap_subtheme` folder from the bootstrap theme into your theme folder and rename the folder to *journal* (your theme name). You also rename `./journal/less.starterkit` to `./journal/journal.info`.
4. Open your new .info file and change name + description. (You can copy it from your old theme.)
5. Download the latest 3.x.x version of the of Bootstrap Framework Source Files into your new sub-theme. After it has been extracted, the folder should read ./journal/bootstrap. (Don't modify the files in this folder, this folder allows you to later update Bootstrap without overwriting your changes.)
6. Download the journal theme css from bootswatch. Copy it into your `journal/css` folder. (This is the file which was previously provided by the CDN.) It should now read `journal/css/bootstrap.min.css`
7. Open your `.info` file again, find the line `stylesheets[all][] = css/style.css`and **add** a line right above it: `stylesheets[all][] = css/bootstrap.min.css`. This will load the default journal css.
8. Now you need to copy your custom changes into the new theme. Copy your custom css into `css/style.css` and your template files (if you have any custom template files) into the `journal/templates`folder.
9. Enable your new Journal theme.

---

**Glyphicons**

Check your subtheme... there should be a folder `fonts`. If there is no such folder create one. Then navigate to the bootstrap source files you put in the `bootstrap` folder of your theme, find the font folder there and copy all font files in your own `font` folder. (This is needed because the default css looks for the fonts under `../fonts/font-name`)

**Headermenu**

Have you checked the settings of your new theme in the UI? It has a couple of menu bar settings, maybe you are just using the wrong one. Generally bootstrap works nicely with the admin menu, at least on all sites I have it on. It is possible, that some of your custom css is interfering with the default bootstrap theme setup. In that case you would need to do some debugging on your custom css. From what I see though it might be enough for the front end to give the main-container a top margin of 60-70px.
> 6 votes

# Answer
I was able to disable use of the CDN in Drupal Bootstrap 7.x-3.25 in a subtheme we can call `subtheme_name`.

First I loaded the site with the CDN enabled, and then went into the browser developer tools, looked at the network tab, reloaded the page, then copied the URLs for `bootstrap.css`, `drupal-bootstrap.css` and `bootstrap.js`. I then downloaded those files from the CDN and put them into the `subtheme_name/bootstrap/css/` and `subtheme_name/bootstrap/js/` directories I created.

I added these lines to the `Stylesheets` section of `subtheme_name.info`:

```
stylesheets[all][] = bootstrap/css/bootstrap.css
stylesheets[all][] = bootstrap/css/drupal-bootstrap.css

```

I added this line to the `Scripts` section of `.info` file:

```
scripts[] = 'bootstrap/js/bootstrap.js'

```

I uncommented `settings[bootstrap_cdn_provider] = ''` in that file, then ran `drush cc all` to clear the cache. Network tools now say that the files come from the site, not the CDN.
> 0 votes

---
Tags: 7, theming
---


title: How can I show node Hits (statistics)?

text:
# Question
Title: How can I show node Hits (statistics)?
How can I show Node Hits (Statistics\_Counter) in Drupal 8 in a specific place?
I enabled `statistics` module and I now want to show user hits of a node (node view number/node visits count) in the submitted area instead of in the node links area.

I do this already in Drupal 7 with below code in node.tpl.php:

```
<?php print (int) $content['links']['statistics']['#links']['statistics_counter']['title']; ?>

```

What is the equivalent code for Drupal 8?

# Answer
Drupal 8 uses twig templates so variables are handled/printed in different way.

Node links sections is handled separately because of which we can not hide/remove statistics in **node.html.twig** file. So to print node statistics count in submitted area, you'll first need to add that to base level of node template like content, author\_picture, etc. You can do this by implementing template\_preprocess\_node() in your theme. Below is sample code which adds new variable containing node statistics count.

```
function [THEME_NAME]_preprocess_node(&$variables) {
  // Get statistics count for current node.
  $statistics = statistics_get($variables['node']->id());
  $variables['node_stats'] = \Drupal::translation()->formatPlural($statistics['totalcount'], '1 view', '@count views');
}

```

Change THEME\_NAME with theme you're using. This will add **node\_stats** variable which you can use inside **node.html.twig** file for printing node statistics count. Below is how you can print it inside template file.

```
{% if display_submitted %}
  <div class="node__meta">
    {{ author_picture }}
    <span{{ author_attributes }}>
      {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
    </span>
    <span class="node__stats">
      {{ node_stats }}
    </span>
    {{ metadata }}
  </div>
{% endif %}

```

This will print the node statistics count in submitted area of content. Links section will still show the node statistics count, to remove this, you will need to create new template file (if not already created) named as **links.html.twig**. You can copy existing file from "Core =\> themes =\> classy =\> templates =\> navigation =\> links.html.twig". After which you can exclude the statistics count from printing. Make sure to rebuild cache after adding new template file. See sample output below:

```
  <ul{{ attributes }}>
    {%- for key, item in links|without('statistics_counter') -%}
      <li{{ item.attributes.addClass(key|clean_class) }}>
        {%- if item.link -%}
          {{ item.link }}
        {%- elseif item.text_attributes -%}
          <span{{ item.text_attributes }}>{{ item.text }}</span>
        {%- else -%}
          {{ item.text }}
        {%- endif -%}
      </li>
    {%- endfor -%}
  </ul>

```

We've removed statistics count from links while printing using **without()** function **links|without('statistics\_counter')**
> 7 votes

# Answer
`statistics_get()` has been deprecated in Drupal 8.2.x and it will be removed before Drupal 9.0. While it is possible to use `statistics_get()` in all the Drupal 8 branches, if you want to write code that requires less changes to be ported to Drupal 9, you should use code similar to the following one.

```
function mymodule_preprocess_node(&$variables) {
  $variables['node_view_count'] = 0;
  if (!empty($variables['node'])) {
    // Get the number of times the current node has been viewed.
    /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
    $statistics = \Drupal::service('statistics.storage.node')
      ->fetchView($variables['node']->id());
    if ($statistics instanceof StatisticsViewsResult) {
      $variables['node_view_count'] = $statistics->getTotalCount();
    }
  }
}

```

Since `\Drupal::service('statistics.storage.node')->fetchView($variables['node']->id())` can return `FALSE` if there isn't any data about the node, it's necessary to verify what it returned to avoid getting an error about accessing a method from a variable not containing an object.

In the node.html.twig template, the *node\_view\_count* value can be used using code similar to the following one.

```
  <header>
    {{ title_prefix }}
    {% if label and not page %}
      <h2{{ title_attributes.addClass('node__title') }}>
        <a href="{{ url }}" rel="bookmark">{{ label }}</a>
      </h2>
    {% endif %}
    {{ title_suffix }}
    {% if display_submitted %}
      <div class="node__meta">
        {{ author_picture }}
        <span{{ author_attributes }}>
          {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        </span>
        {% if node_view_count %}
          {% trans %}
            Viewed {{ node_view_count }} time
          {% plural node_view_count %}
            Viewed {{ node_view_count }} times
          {% endtrans %}
        {% endif %}
        {{ metadata }}
      </div>
    {% endif %}
  </header>

```
> 3 votes

# Answer
Of course @Yogesh solution was correct and still is correct but `statistics_get()` is deprecated and it's better to use Drupal services instead of old-fashion calling functions, as in the following line.

```
$statistics = \Drupal::service('statistics.storage.node')->fetchView($vars['node']->id());
$totalCount  = $statistics->getTotalCount();
$dayCount  = $statistics->getDayCount();
$timestampCount  = $statistics->getDayTimestamp();

```

**Note:** Current version of Drupal is **8.4**
> 1 votes

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


# Question
Title: Passing data from outer preprocess to inner template
I have two templates: \- a child that is printing each item in a list; \- and a parent that calls it there is also an intermediate Field template that is not involved.

The parent has preprocess access to node field data that each child (node teaser) call needs to use. The child is printing items in a multivalue entity reference field.

How can the child get the data from the parent felds so it can print the right html?

Edit: Just in case it's not clear, the situation is:

```
paragraph_entity        <== preprocess hook can see field_settingsN which change how "B" and "A" render (e.g. add/change attrs, class).
  -> field_settings_1
  -> field_settings_2
  -> field_references   <== have a defined template "B"
    -> 1.. entity refs to nodes
      -> node           <== have a defined (teaser) template "A"

```

# Answer
Done this a couple times, but really got the caching better last time so that it works perfectly... I've put in some fairly verbose comments, but if anything is unclear just shout.

```
/**
 * Implements HOOK_preprocess_paragraph().
 */
function HOOK_preprocess_paragraph(array &$vars) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $vars['paragraph'];
  // Change 'content_reference' to be your paragraph bundle's machine name.
  if ($paragraph->bundle() === 'content_reference') {
    // Instead of 10 set that to be the max number of references in the field.
    foreach (range(0, 10) as $i) {
      // Change all references to 'field_content_reference' to use your field's
      // machine name.
      if (!isset($vars["content"]["field_content_reference"][$i])) {
        break;
      }
      /** @var \Drupal\node\Entity\Node $node */
      $node = $vars["content"]["field_content_reference"][$i]["#node"];

      // Example change to the Node.
      $node->field_parent_paragraph = $paragraph;
      $changed = TRUE;

      if (isset($changed)) {
        // If we've changed the node, give a new cache id.
        // THIS IS IMPORTANT!
        $vars["content"]["field_content_reference"][$i]['#cache']['tags'][] = "paragraph:{$paragraph->id()}";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = "paragraph";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = $paragraph->id();
      }
    }
  }
}

```

Follow that up with something like:

```
/**
 * Implements HOOK_preprocess_node().
 */
function HOOK_preprocess_node(array &$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $vars['node'];
  if (isset($node->field_parent_paragraph)) {
    $paragraph = $node->field_parent_paragraph;
    $vars['content']['#attributes']['class'][] = $paragraph->field_settings_1->value;
  }
}

```
> 2 votes

---
Tags: theming
---


# Question
Title: Rendering a region in region--footer.tpl.php
I have my social media links in my `sidebar_first` region. And these social icons are included in my footer. So in `region--footer.tpl.php`, I have rendered `sidebar_first` region but it is not displaying, I know this is a wrong way to render a side bar region in footer region, does anybody have idea how can I achieve this:

```
<?php if ($content): ?>
<footer id="footer" class="<?php print $classes; ?>">
  <nav class="footer-nav">
    <?php $foter_menu = menu_navigation_links('menu-footer-menu');
      $variables['footer_menu'] = print theme('links__menu_footer_menu', array('links' =>      $foter_menu,'attributes'=>array(''),'heading'=>t('')));
      ?>
  </nav>
  <div class="left-panel">
    <ul class="social-networks">
      <?php print render($page['sidebar_first']); ?>
    </ul>
  </div>
</footer>
<?php endif; ?>

```

then in my `page--front.tpl.php`

```
 <?php print render($page['footer']); ?>

```

# Answer
as you wrote, you can override the region.tpl.php files, following the template name conventions - I would post a link, but drupal.org is down right now. A quick web search should get you to the right url and you can create a region specific tpl file.

you shouldn't try to render one region in another, but you can duplicate the code in both region files, or of course, you could also include the code in two blocks, one for each region
> 0 votes

# Answer
I suspect, though am not sure, that the render sidebar\_first in the footer is not rendering because it has already been rendered. In D7, try putting a call to:

```
"unhide($page['sidebar_first'])"

```

immediately before the footer call to render()
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Configuring Fail2ban for the r4032login module
Recently, I installed fail2ban on my server to help prevent bots from abusing the site.

I have the r4032login module installed and it is writing to the log, but it is using HTTP status 302 for the redirect to the login page.

I'm wondering what would be the easiest way to have fail2ban work alongside the r4032login.

Here is a sample log entry:

```
ddd.ddd.ddd.ddd - - [12/May/2019:14:46:26 -0400] "GET /node/1/edit HTTP/1.1" 302 4305 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"

```

https://www.fail2ban.org/wiki/index.php/Main\_Page

https://www.drupal.org/project/r4032login

# Answer
For Fail2Ban v0.10.2, I edited two files in the `/etc/fail2ban` directory.

I added the following entry to jail.local:

```
[apache-forbidden]
enabled = true
port = http,https
filter = apache-forbidden
logpath = %(apache_access_log)s
maxretry = 3
findtime = 600
bantime  = 600

```

For `filter.d/apache-forbidden.conf` I have the following:

```
[INCLUDES]

before = common.conf

[Definition]

failregex = <HOST> - - .*HTTP/[0-9]+(.[0-9]+)?" 302

```

The 302 at the end is to reflect the redirect code for r4032login module.

**NOTE**: 302 redirects by other modules and Apache might also trigger a ban. Please see the comment below to mitigate this effect.
> 0 votes

---
Tags: 8, security
---


title: Modal dialog doesn't work

text:
# Question
Title: Modal dialog doesn't work
I want to display ctools modal. I tried the following code.

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['my_module/%ctools_js/test-page'] = array(
    'title' => 'Demo CTools Page',
    'page callback' => 'my_module_modal',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_modal($js) {
  $output = '<div class="content">' . t('Test content?') . '</div>';
  dsm($js);
  if ($js) {
  ctools_include('ajax');
    ctools_include('modal');

  ctools_modal_add_js();
    return ctools_modal_render('Define as start matrix', $output);
  }

  return $output;
}

```

The link where I click is

```
<a href="/my_module/nojs/test-page" class="ctools-use-modal">Open modal</a>

```

But it returns me only the content of the page with no modal. When I printed the `$js` variable, it is displaying 0. While the javascript is enabled in the browser. I have checked it with multiple browsers .

What can be the issue?

# Answer
I have found the solution.

You need to add these 3 lines of code to the page where the link `<a href="/my_module/nojs/test-page" class="ctools-use-modal">Open modal</a>` is displaying.

```
ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();

```
> 0 votes

---
Tags: 7, chaos-tool-suite, modal-dialogs
---


# Question
Title: How to get my custom module to recognized a exported view?
I have created a view and then exported it normally to a yml file. Then I put this yml file into my mycustommodule/config/install folder.

So current its named `mycustommodule.view.user_assigned.yml`

However when I uninstall the module and reinstall it to see if it will upload the view, it does not. What am I doing wrong?

Edit: I copied and pasted the yml file itself so there should be no errors there. The only thing I did was remove the UUID string since I read elsewhere it was not needed.

# Answer
> 1 votes
The first part of a config item filename is the module responsible for the config type, not the module installing it.

In your case that's "views", so the file should be named *views.view.user\_assigned.yml*.

# Answer
> 0 votes
This is by concept, uninstalling a module does not remove config listed in `config/install` \- and therefore the config also won't also update through reinstalling. (Actually I thought there even would be some error message like *"can't install because config object already exists"*)

But you can add an `enforced` dependency to your config, which will delete the config object when you uninstall the module (and therefore also update it when you reinstall it).

Add this to your `.yml`

```
dependencies:
  enforced:
    module:
      - mycustommodule

```

---
Tags: views, 8, installation
---


# Question
Title: Automatically redirect user depending on its device screen size?
In a custom module (`amap`), I have two forms with the same final purpose: handle (create, update, delete) a custom content entity (`distribution_inscription`).
The first one (`DistributionInscriptionTableForm`) is for "mass" update, designed as a table form and needs a "large" screen:
The second one (`DistributionInscriptionForUserForm`) is for "small" screen (smartphone):
With the same menu option, I'd like the user automatically redirected to the relevant form depending on the size of the device he currently uses.
How can I do that?

# Answer
> 4 votes
I can think of a couple of ways to do this:

* Render the table version as a list of (list of) items (e.g. ul / li / ul... ), not an html table, and then use CSS media queries to adjust the display between the two formats. That is, traditional responsive design. Optionally, include some JS to "load more" items when there is space to fill.
* Render the page furniture and some JS that will inspect the device dimensions and load the wide/narrow element (as html) from the server in an AJAX callback. Once loaded, the page can be submitted as normal.

Of the two, the first would be my own preference. Be aware that there are a wide range of device sizes, including 5" phones with Full HD and wider screens, so don't rely on absolute pixel numbers - you need to account for dpi. On mobiles, I would definitely lose the sidebar, too.

I would not try to use page redirection - bad user experience - flickering screen, general horribleness :-)

---
Tags: 8
---


title: Drush not fully installed

text:
# Question
Title: Drush not fully installed
I have installed Drush 8.2.3 globally on a Lubuntu 18.04 image. This was done without Composer (I used the default install instructions here)

However, if I run `drush topic` and select any topic number from the list I get

```
phar:///usr/local/bin/drush/examples/sync_via_http.drush.inc: No such file or directory
more: stat of phar:///usr/local/bin/drush/examples/sync_via_http.drush.inc failed: No such file or directory

```

What gives?

# Answer
This is a known issue - Topic command does not work when using Phar. Searching the issue queue is always recommended. Since the current version is Drush 9, I don't expect this to be fixed.
> 0 votes

---
Tags: drush
---


# Question
Title: Not able to enable 'Configuration Translation' module gives error
I am trying to enable MULTILINGUAL -\> Configuration Translation.

It gives below error.

> Error: Call to a member function getPath() on null in Drupal\config\_translation\ConfigNamesMapper-\>getOverviewRoute() (line 247 of /var/www/project/docroot/core/modules/config\_translation/src/ConfigNamesMapper.php) #0 /var/www/project/docroot/core/modules/config\_translation/src/Routing/RouteSubscriber.php(39): Drupal\config\_translation\ConfigNamesMapper-\>getOverviewRoute() #1 /var/www/project/docroot/core/lib/Drupal/Core/Routing/RouteSubscriberBase.php(37): Drupal\config\_translation\Routing\RouteSubscriber-\>alterRoutes(Object(Symfony\Component\Routing\RouteCollection)) #2 \[internal function\]: Drupal\Core\Routing\RouteSubscriberBase-\>onAlterRoutes(Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route\_a...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher)) #3 /var/www/project/docroot/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(111): call\_user\_func(Array, Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route\_a...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher)) #4 /var/www/project/docroot/core/lib/Drupal/Core/Routing/RouteBuilder.php(184): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('routing.route\_a...', Object(Drupal\Core\Routing\RouteBuildEvent)) #5 /var/www/project/docroot/core/lib/Drupal/Core/ProxyClass/Routing/RouteBuilder.php(83): Drupal\Core\Routing\RouteBuilder-\>rebuild() #6 /var/www/project/docroot/core/lib/Drupal/Core/Extension/ModuleInstaller.php(322): Drupal\Core\ProxyClass\Routing\RouteBuilder-\>rebuild() #7 /var/www/project/docroot/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(83): Drupal\Core\Extension\ModuleInstaller-\>install(Array, true) #8 /var/www/project/docroot/core/modules/system/src/Form/ModulesListForm.php(458): Drupal\Core\ProxyClass\Extension\ModuleInstaller-\>install(Array) #9 \[internal function\]: Drupal\system\Form\ModulesListForm-\>submitForm(Array, Object(Drupal\Core\Form\FormState)) #10 /var/www/project/docroot/core/lib/Drupal/Core/Form/FormSubmitter.php(111): call\_user\_func\_array(Array, Array) #11 /var/www/project/docroot/core/lib/Drupal/Core/Form/FormSubmitter.php(51): Drupal\Core\Form\FormSubmitter-\>executeSubmitHandlers(Array, Object(Drupal\Core\Form\FormState)) #12 /var/www/project/docroot/core/lib/Drupal/Core/Form/FormBuilder.php(589): Drupal\Core\Form\FormSubmitter-\>doSubmitForm(Array, Object(Drupal\Core\Form\FormState)) #13 /var/www/project/docroot/core/lib/Drupal/Core/Form/FormBuilder.php(318): Drupal\Core\Form\FormBuilder-\>processForm('system\_modules', Array, Object(Drupal\Core\Form\FormState)) #14 /var/www/project/docroot/core/lib/Drupal/Core/Controller/FormController.php(93): Drupal\Core\Form\FormBuilder-\>buildForm('system\_modules', Object(Drupal\Core\Form\FormState)) #15 \[internal function\]: Drupal\Core\Controller\FormController-\>getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch)) #16 /var/www/project/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call\_user\_func\_array(Array, Array) #17 /var/www/project/docroot/core/lib/Drupal/Core/Render/Renderer.php(582): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #18 /var/www/project/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer-\>executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #19 /var/www/project/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) #20 /var/www/project/vendor/symfony/http-kernel/HttpKernel.php(151): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #21 /var/www/project/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #22 /var/www/project/docroot/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #23 /var/www/project/docroot/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #24 /var/www/project/docroot/core/modules/page\_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #25 /var/www/project/docroot/core/modules/page\_cache/src/StackMiddleware/PageCache.php(78): Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object(Symfony\Component\HttpFoundation\Request), 1, true) #26 /var/www/project/docroot/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #27 /var/www/project/docroot/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #28 /var/www/project/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #29 /var/www/project/docroot/core/lib/Drupal/Core/DrupalKernel.php(669): Stack\StackedHttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #30 /var/www/project/docroot/index.php(19): Drupal\Core\DrupalKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request)) #31 {main}.

I am not sure what exactly cause of this. Anyone faced?

# Answer
> 4 votes
Could be caused by a module which doesn't provide a base path for a config entity, see for example:

https://www.drupal.org/project/dynamic\_layouts/issues/3002255 https://www.drupal.org/project/password\_policy/issues/2703717 https://www.drupal.org/project/paragraphs\_entity\_embed/issues/3014901 https://www.drupal.org/project/search\_api/issues/2919676 https://www.drupal.org/project/salesforce/issues/3040022

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


# Question
Title: How to display a form in modal dialog on page load?
This is on Drupal 8.6, PHP 7.2, Theme is based on Bootstrap.

The scenario is, I want to display a dialog box with a subscription form in the home page. The dialog box will be loaded automatically when page load, not by click any link. I see there are lot of examples there in the net, but all related to by clicking a link, modal will display. But I want to load it without any click.

I partially successful by using BootstrapDialog, but ajax is not working on form submit button. What I did, I attach a js file in the front page, with the code below. It shows the Modal Dialog box, and I tuned a page--newsletter--subscribe.html.twig, its working But submit button not working not ajax is working.

```
    BootstrapDialog.show({
    title: 'Subscribe To Newsletter',
    message: jQuery('<div></div>').load('/newsletter/subscribe'),
    closable: false,
    draggable: true,
    closeByBackdrop: false,
    closeByKeyboard: false,
    buttons: [{
        label: 'Close',
        action: function(dialogRef){
            dialogRef.close();
        }
    }]
});

```

I saw there is an example in code node.preview.js file like this:

```
          var $previewDialog = $('<div>' + Drupal.theme('nodePreviewModal') + '</div>').appendTo('body');
      Drupal.dialog($previewDialog, {
        title: Drupal.t('Leave preview?'),
        buttons: [{
          text: Drupal.t('Cancel'),
          click: function click() {
            $(this).dialog('close');
          }
        }, {
          text: Drupal.t('Leave preview'),
          click: function click() {
            window.top.location.href = event.target.href;
          }
        }]
      }).showModal();

```

But I never able to make it working in my custom module.

If some one can help on this, will be really great!

Update: I just tried to put a link manually in the template and tried to open the dialog, but it gives me some error:

```
<a href="/newsletter/registration" class="use-ajax " data-dialog-type="modal">Show Dialog</a>

```

The error is as follows:

```
dialog.js?v=8.6.4:35 Uncaught TypeError: $element.dialog is not a function
at openDialog (dialog.js?v=8.6.4:35)
at Object.dialog.showModal (dialog.js?v=8.6.4:52)
at Drupal.AjaxCommands.openDialog (dialog.ajax.js?v=8.6.4:96)
at Drupal.Ajax.success (ajax.js?pkvhqx:155)
at Object.success (ajax.js?v=8.6.4:234)
at i (jquery.min.js?v=3.2.1:2)
at Object.fireWith [as resolveWith] (jquery.min.js?v=3.2.1:2)
at A (jquery.min.js?v=3.2.1:4)
at XMLHttpRequest.<anonymous> (jquery.min.js?v=3.2.1:4)

```

It seems some of the library is not loaded. Here is my global attachement:

```
  dependencies:
- core/jquery
- core/jquery.ui
- core/drupal.ajax
- core/drupal
- core/drupalSettings
- core/drupal.dialog
- core/drupal.dialog.ajax
- core/jquery.form
- core/jquery.once
- core/modernizr

```

# Answer
What I did, hide the link in the body and from javascript trigger the click event of the link, will show the dialog.
> 1 votes

---
Tags: ajax, modal-dialogs, bootstrap-theme
---


title: REST login problem

text:
# Question
Title: REST login problem
I'm trying to log in to drupal8 via api rest using postman.

```
POST: https://example.com/user/login?_format=json
Content-type: application/json

{
"name": "admin",
"pass": "password"
}

```

The problem is that this error is returned to me.

> An unexpected error has occurred. Please try again later, thanks.
> Symfony\Component\Serializer\Exception\NotEncodableValueException: Syntax error in Symfony\Component\Serializer\Encoder\JsonDecode-\>decode() (line 78 of C:\www\drupal-composer\vendor\symfony\serializer\Encoder\JsonDecode.php).
>
> Symfony\Component\Serializer\Encoder\JsonEncoder-\>decode('', 'json', Array) (Line: 40)
> Symfony\Component\Serializer\Encoder\ChainDecoder-\>decode('', 'json', Array) (Line: 280)
> Symfony\Component\Serializer\Serializer-\>decode('', 'json') (Line: 167)
> Drupal\user\Controller\UserAuthenticationController-\>login(Object) call\_user\_func\_array(Array, Array) (Line: 123)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 582)
> Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 151)
> Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68)
> Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57)
> Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47)
> Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 106)
> Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 85)
> Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47)
> Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 52)
> Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23)
> Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 693)
> Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

Does anyone have a solution? I am using Drupal 8.7.1.

# Answer
> 4 votes
Solution found! In Postman:

* method: **POST**
* endpoint: **http://{your\_url}/user/login?\_format=json**
* in section Header: **Content-Type: application/json**
* in section body: **{"name":"admin","pass": "admin"}**

Note: **name and password must be entered in the body section (raw)**

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


title: Refreshing entity definition

text:
# Question
Title: Refreshing entity definition
I've got a D8 media type that holds information obtained from an external source. The information comes in name value pairs that I wish to save as individual fields, mostly so I can index them easily with solr. On some files I get new property names that have to be persisted as fields, so I have a presave hook that creates and saves a FieldStorageConfig, and a StorageConfig for my each new field in my media bundle. It all works swimmingly.

THe problem is when i try to save a value to that new field in the presave function an error is thrown indicating that the field doesn't exist. (It does exist, but Drupal doesn't know about it yet). When I resave the media with the same input file everything goes as planned.

Is there a way to force Drupal to refresh the media's field list?

# Answer
> 0 votes
This is as simple as reloading the entity. The entity is loaded with the current fields, if new fields are added to the content type, the entity won't update on its own.

In my presave hook I check to see if new fields have been added at that time. If so I wait til the media update hook is fired to reload.

---
Tags: 8, entities
---


# Question
Title: Filter taxonomy term attached to user field
I have a user that has a taxonomy vocabulary attached their account and a content type with the same taxonomy vocabulary attached to it.

How do I get a page view filter to only display the nodes that have the same taxonomy term that is attached to the user vocabulary?

# Answer
> 2 votes
You can do this with a combination of Relationships and Contextual filters.

1. Create Page Display Views listing your Content nodes
2. Add the Relationship towards the Taxonomy term through your Taxonomy reference fields **Taxonomy term referenced from field\_\[mytaxonomy\]"**. You can Require this Relationship if you don't want any nodes to appear that have that field empty
3. Add another Relationship **User using field\_music**. It will automatically use the first Relationship.
4. Add the Contextual Filter **User ID** and configure it:
Relationship **field\_\[mytaxonomy\]**
`When the filter value is NOT available`
**Provide default value**
**User ID from route context**
`When the filter value IS available or a default is provided`
**Override title**
`Content matching Taxonomy chosen by the user {{ arguments.uid }}` (check your argument token under `Replacement patterns`)
**Specify validation criteria**
**User ID**
5. Optional: Change your **Path** setting to `user/%user/[Vocabularyname]` and **Menu** to `Menu tab` "\[Your tab name\]". This will add a Drupal tab on the user profile pages that shows this Views, listing content that is related to the terms chosen by the user in their profile settings.

If you get duplicates in the results you can turn the Aggregation on and it will help to show each node only once.

# Answer
> 1 votes
One way to do it is a bit of a multi-step process.

First, in the view itself under ADVANCED -\> CONTEXTUAL FILTERS set up a contextual filter for the taxonomy field you want to filter the view based on (make sure that field is also added to the view's fields.

second, you'll need to add a bit of code to a custom module. You'll want to implement `hook_views_pre_view`

```
/**
 * Implements hook_views_pre_view().
 *
 * @param ViewExecutable $view
 * @param string $display_id
 * @param array $args
 * @return void
 */
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $account = \Drupal::currentUser();

  // DO A LOOKUP FOR THE USER'S FIELD
  $VALUE_FROM_USER_FIELD_LOOKUP = 'SOMETHING';

  // IF WE ARE IN THE RIGHT VIEW AND DISPLAY
  if($view->id() == 'MY VIEW ID' && $view->getDisplay()->display['id'] == 'MY DISPLAY ID') {
    // ADD SOME CUSTOM ARGS TO THE CONTEXT FILTER
    $args = [implode("+", $VALUE_FROM_USER_FIELD_LOOKUP)]; //implode on + or some other character? for multi-value contextual filters...
  }

}

```

---
Tags: views
---


# Question
Title: Can't set arguments to a view for displaying all data
I use

```
$view = views_embed_view('export_emargement','page_1',$journee,$region,$produit);

```

it works well, but If I don't want to specify $region the view does'nt works.

Im my view admin if I set argument like this 797/62/24 it works

If I try 797/all/24 it works too!every data are displayed

In my code i try this, but it can't be parsed

```
$args = array($journee.',"all",'.$produit);
or
$args = array($journee.',all,'.$produit);
$view = views_embed_view('export_emargement','page_1',$args);

```

# Answer
`$args` is an array that expects each field's contextual values to be passed in separately.

i think `$args = array($journee, "all", $produit);` ought to work.

you should only concatenate arguments into a string if its a multi-value single field situation and then I believe you join with '+' not commas.

### EDIT

I missed what you were asking, if you have a contextual filter that is optional inside the view you can configure what happens when no value is provided (pick "display all results").

then when calling the view

as far as skipping an argument `'all'` \- the easiest way would be to move the order of the contextual filters so that the one that is allowed to be "empty" is last.

then instead of calling

```
$view = views_embed_view('export_emargement','page_1',$journee,$region,$produit);

```

call

```
$view = views_embed_view('export_emargement', 'page_1', $journee, $produit, $region);

```

or

```
$view = views_embed_view('export_emargement', 'page_1', $journee, $produit);

```

depending on if the user has selected a region
> 0 votes

---
Tags: views, 8
---


# Question
Title: Why can't I update core from 8.6.16 to 8.7.1?
I need to update my Drupal 8 site from 8.6.16 to 8.7.1, but when I run `composer update drupal/core --with-dependencies` it says "Nothing to install or update". I have been banging my head on the wall about this for 45 minutes, and haven't found anything on Google that fixes this.

Does anyone know why it says there is an update, but then says there is nothing to update or install?

# Answer
> 3 votes
There seem to be some version dependency issue with that email-validator.

I solved it by updating the composer.json to the newer version before updating Drupal:

```
composer require drupal/core:~8.7.0 --no-update
composer require webflo/drupal-core-require-dev:~8.7.0 --no-update
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies --dry-run
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies
cd web
[../vendor/bin/]drush updatedb
[../vendor/bin/]drush cr

```

YMMV, here is the Issues where you can get more help if this doesn't work (check the related Issues as well):

Cannot update to Drupal 8.7.0 from 8.6.15 -- egulias/email-validator version conflict

Don't forget to attach your composer.json and composer.lock there so the problem can be properly diagnosed.

---
Tags: 8, updating
---


title: How do I update the sitemap in D7?

text:
# Question
Title: How do I update the sitemap in D7?
I want to exclude some pages from the sitemap.

I go to these pages/nodes, edit them, then go to the XML sitemap tab and set it to 'Exclude'.

I then save and clear cache.

But when I look at my sitemap.xml file nothing is changed - the page URLs are still present.

How do I remove them?

# Answer
The XML Sitemap module doesn't rebuild sitemaps on every node save/load; also, it's not cached like other artifacts in Drupal.

The module tracks XML Sitemap links and they are added/removed upon cron runs. So you'll need to run cron to rebuild your sitemap files.

You can also follow some of the steps in the *Setting up your site map (7.x)* documentation:

> 8. Under "Inclusion" change "Excluded" to become "Included"
> 9. To add pages linked from menus to the sitemap, visit the edit page for each menu whose items should be included (this would usually include the Main menu). Open the XML sitemap fieldset, and similarly change "Excluded" to "Included". Hit Save.
> 10. Once that is all complete, go to Configurations --\> Search and Metadata --\> XML Sitemap
> 11. Click on the Rebuild Links tab in the upper right
> 12. Click on "Rebuild sitemap" even if the message says that you do not need to.
> 13. Now you're taken back to the config page which shows you the link to your xmlsitemap which you can click and confirm that pages have been added
> 1 votes

---
Tags: 7, xml-sitemap
---


# Question
Title: D7 block view to only show child nodes based on taxonomy
Using Drupal 7

I have a hierarchical taxonomy each node in the site is assigned a taxonomy to identify where it sits in the site structure.

On certain pages (landing pages) I would like to show the children of those pages but not the page itself nor importantly any peer pages

so in the following taxonomy

* parent1
    + child1
    + child2
    + child3
* parent2
    + child4
    + child5
    + child6

I have two nodes assigned the "parent1" taxonomy and a node assigned to each of the child taxonomies

If I go to one of the nodes assigned the parent1 term I should see in my block view all the nodes assigned to child1-3

Currently using "taxonomy term with depth" I see all the correct children, but I also see the other node assigned to the parent1 term because taxonomy term with depth, returns all children plus the parent nodes.

Hiding the node I am on is easy with exclude, but I cannot see a way of hiding other nodes with the same term as the page I am on.

How can I select only the child nodes, not the child plus parent nodes?

# Answer
It turns out the problem was not as hard as I thought. The hard part was to know what relationship to set up and what contextual filter to implement.

I solved it by doing the following

* Created a view of content using fields
* Created a contextual filter using "has taxonomy term with depth"
    + Selected default value of taxonomy term ID from URL
    + Set it to depth 1 to pick up children
    + Limited to my vocabulary

That part was obvious. The next part is what caused issues and was not obvious. I could not find an example anywhere on how to do it.

It is easy to exclude the current page by using the nid contextual filter and using the "exclude" option under the "More" section. This is the answer found by searching online. The problem is it does not resolve the "peer" content issue. It would only remove the current node and not other nodes with the same term.

To fix that problem I found that when I added a relationship, a new contextual filter previously not available was added to the list and it had the all important exclude feature.

So I

* Added a relationship using my taxonomy (Content)
* Added a new contextual filter "term ID" previously not available
    + Selected default value of taxonomy term ID from URL
    + Limited it to my vocab (probably not necessary)
    + Set exclude under the More section

This removed all the nodes with the same taxonomy term as the current node, including the current node, leaving only the children nodes
> 1 votes

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


title: Aggregation problem

text:
# Question
Title: Aggregation problem
I have created a view of node content and I need author name, role, and image to show with content. I have also made a relationship with the user in the advance section for the above-mentioned fields. it's working correctly but when I on Aggregation it gives this SQL query error.

> SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'users\_field\_data\_node\_field\_revision\__user\__user\_picture.user\_picture\_' in 'field list': SELECT node\_field\_data.title AS node\_field\_data\_title, users\_field\_data\_node\_field\_revision.name AS users\_field\_data\_node\_field\_revision\_name, users\_field\_data\_node\_field\_revision\__user\__user\_picture.user\_picture\_ AS users\_field\_data\_node\_field\_revision\__user\__user\_picture\_use, nodeviewcount.id AS id, nodeviewcount.nid AS nodeviewcount\_nid, node\_field\_data.created AS node\_field\_data\_created, MIN(node\_field\_data.nid) AS nid, MIN(users\_field\_data\_node\_field\_revision.uid) AS users\_field\_data\_node\_field\_revision\_uid FROM {node\_field\_data} node\_field\_data INNER JOIN {node\_field\_revision} node\_field\_revision ON node\_field\_data.vid = node\_field\_revision.vid LEFT JOIN {users\_field\_data} users\_field\_data\_node\_field\_revision ON node\_field\_revision.uid = users\_field\_data\_node\_field\_revision.uid LEFT JOIN {user\__user\_picture} users\_field\_data\_node\_field\_revision\__user\__user\_picture ON users\_field\_data\_node\_field\_revision.uid = users\_field\_data\_node\_field\_revision\__user\__user\_picture.entity\_id AND (users\_field\_data\_node\_field\_revision\__user\__user\_picture.deleted = :views\_join\_condition\_0 AND users\_field\_data\_node\_field\_revision\__user\__user\_picture.langcode = users\_field\_data\_node\_field\_revision.langcode) LEFT JOIN {nodeviewcount} nodeviewcount ON node\_field\_data.nid = nodeviewcount.nid WHERE (node\_field\_data.status = :db\_condition\_placeholder\_2) AND (node\_field\_data.type IN (:db\_condition\_placeholder\_3)) GROUP BY node\_field\_data\_title, users\_field\_data\_node\_field\_revision\_name, users\_field\_data\_node\_field\_revision\__user\__user\_picture\_use, id, nodeviewcount\_nid, node\_field\_data\_created ORDER BY node\_field\_data\_created DESC LIMIT 11 OFFSET 0; Array ( \[:db\_condition\_placeholder\_2\] =\> 1 \[:db\_condition\_placeholder\_3\] =\> ask\_question \[:views\_join\_condition\_0\] =\> 0 )

I don't know what is the issue and how to fix this problem. Aggregation is must for me in this view because I have to count Node ID through Aggregation.

# Answer
I have the same issue over aggregation but it started working for me once i applied this patch

/// PLEASE CHECK BELOW FOR PATCH

```
diff --git a/modules/field/views_handler_field_field.inc

b/modules/field/views_handler_field_field.inc

index 799c9a5..e713016 100644

--- a/modules/field/views_handler_field_field.inc

+++ b/modules/field/views_handler_field_field.inc

@@ -770,7 +770,7 @@ class views_handler_field_field extends views_handler_field

{

    * Return an array of items for the field.

    */

   function set_items($values, $row_id) {

-    if (empty($values->_field_data[$this->field_alias]) || empty($values-

>_field_data[$this->field_alias]['entity'])) {

+    if (empty($values->_field_data[$this->field_alias]) || empty($values-

>_field_data[$this->field_alias]['entity']) || !isset($values-

>_field_data[$this->field_alias]['entity']->{$this->definition['field_name']})) {
       return array();
     }

```
> 1 votes

---
Tags: views
---


# Question
Title: How do I restrict access to the install.php file
In my Drupal 8 site, the install.php file is accessible.

How can I restrict the access to that file?

# Answer
> 4 votes
In apache vhost:

```
RedirectMatch 403     "/(install|update).php"

```

Or in htaccess change the part on top:

```
# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock)|web\.config)$|cron\.php|install\.php|update\.php|^(CHANGELOG|COPYRIGHT|INSTALL.*|LICENSE|MAINTAINERS|README|UPDATE).txt$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">

```

Please note this htaccess also protects access to cron.php, update.php, web.config and txt files like /core/CHANGELOG.txt

# Answer
> 1 votes
How come you need it gone, is it necessarily a problem? Once the site is installed you just see a message informing you the installation is done.

If you really want it gone then once your site is installed delete the install.php file from the core directory. And then do that every time you update Drupal core

---
Tags: 8
---


title: How to put a link in my route title?

text:
# Question
Title: How to put a link in my route title?
In my custom module `amap`, I have `amap.routing.yml` with (among others) this route:

```
amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title: 'Update Planning'
  requirements:
    _permission: 'edit distribution inscription entities'

```

I'd like to have a link in the title of the route, something like
`Update Planning <a href="/amap/editPlanningOne">Click here</a>`

Drupal 8 API documentation says in Structure of routes

> \_title: The page title for the route. It may differ from the menu link title.
> \_title\_arguments: Additional arguments for the title text passed along to t().
> \_title\_context: Additional context information for the title text passed along to t().
> \_title\_callback: A PHP callable (typically classname::method) returning the page title for the route.

but I don't know how to use it...
How can I do that?

# Answer
In you routing.yml change \_title to \_title\_callback as below:

```
amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title_callback: '\Drupal\amap\Controller\TitleController::title'
  requirements:
    _permission: 'edit distribution inscription entities'

```

Create a "TitleController" controller in you amap module unser "src/Controller"

**TitleController.php**

```
<?php

namespace Drupal\amap\Controller;

use Drupal\Core\Controller\ControllerBase;

class TitleController extends ControllerBase {

  public function title() {
    return t('Update Planning <a href="/amap/editPlanningOne">Click here</a>');
  }

}

```

Now your title will be callable from the controller and you can give whatever that likes you here.
> 1 votes

---
Tags: 8, routes
---