title: Menu on the taxonomy term page

text:
# Question
Title: Menu on the taxonomy term page
maybe the solution to my problem is quite simple but I can not find a way on the taxonomy term page to show a menu block!

I use drupal 8 with bartik theme and have a menu based on taxonomic terms (Module: Taxonomy Menu + Menu Block). This menu is also always displayed everywhere (with the set content types). Just not on the taxonomy term page (the page where all entries are displayed from a taxonomy item in a teaser view).

if I look under Structure\> Block Layout\> Navigation\> Configuration: is there "page" there I tried to enter URL of the taxonomy terms or also / * but both remains without effect.

# Answer
> 0 votes
As mentioned in comments if you want it shown everywhere you should untick the Type options, then they apply anyway. And on the `Seite` delete everything, that should show it everywhere too without restrictions (no need for `/*`).

But I think your particular configuration isn't working because you have included the `/de/` in your path under `Seite`, the language prefix is *not* part of the Drupal path. Remove it from there and it should work.

Instead of:

`/de/tutorial/erste-schritte`

it should say:

`/tutorial/erste-schritte`

You have the Visibility limited to the German language under the `Sprache` tab.

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


title: Core doesn't update with Composer

text:
# Question
Title: Core doesn't update with Composer
We use commands:

```
composer outdated drupal/*
drupal/core 8.6.10 8.6.13 Drupal is an open source content management platform powering millions of websites and applications.

```

It does show 8.6.13.

We run either `composer update drupal/core --with-dependencies` or `composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies` and we get nothing, it does update some dependencies and that is it. Our site is built with composer.

Here's the rest of the log:

```
composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Package "drupal/core:8.6.13" listed for update is not installed. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "twig/twig" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 5 updates, 0 removals
  - Updating symfony/css-selector (v3.4.22 => v3.4.23): Loading from cache
  - Updating symfony/phpunit-bridge (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/dom-crawler (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/browser-kit (v4.2.3 => v4.2.4): Downloading (100%)
  - Updating squizlabs/php_codesniffer (3.4.0 => 3.4.1): Downloading (100%)
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # composer update drupal/core
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # drush status
 Drupal version   : 8.6.10
 Site URI         : default
 DB driver        : mysql
 DB hostname      : localhost
 DB port          : 3306
 DB username      : root
 DB name          : example
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : seven
 Admin theme      : seven
 PHP binary       : /usr/bin/php7.2
 PHP config       : /etc/php/7.2/cli/php.ini
 PHP OS           : Linux
 Drush script     : /usr/local/bin/drush
 Drush version    : 9.4.0
 Drush temp       : /tmp
 Drush configs    : /var/www/example.com/vendor/drush/drush/drush.yml
                    /var/www/example.com/drush/drush.yml
 Install profile  : standard
 Drupal root      : /var/www/example.com/web
 Site path        : sites/default
 Files, Public    : sites/default/files
 Files, Temp      : /tmp

```

Drush is still reporting 8.6.10

First time we did get the WSOD from https://www.drupal.org/project/drupal/issues/3039408 so we ran `composer require twig/twig:1.37.1` to fix it.

# Answer
> 0 votes
So after we ran regular update (current version was 8.6.10), our website crashed. We followed this fix to recover from WSOD https://www.drupal.org/project/drupal/issues/3039408#comment-13018093

After website was restored we tried running all kinds of composer commands to update (like mentioned in question) and it would just spit out "Nothing to install or update".

Solution:

1. remove `"twig/twig": "1.37.1",` from `composer.json`
2. Run again `composer update drupal/core webflo/drupal-core-require-dev --with-dependencies`

`Updating twig/twig (v1.37.1 => v1.38.2): Loading from cache
Updating drupal/core (8.6.10 => 8.6.13): Downloading (100%)`

So, not sure what's going on.

# Answer
> -1 votes
We came across the similar issue while upgrading from 8.6.10 to 8.6.13, try deleting the core and then run

```
composer update drupal/core --with-dependencies

```

It should upgrade it to 8.6.13

---
Tags: 8, drush, updating, composer
---


# Question
Title: When will doctrine ORM be implemented for modules?
I am looking at Drupal for some websites I want to set up. I have been a Symfony developer in the past so would like to use doctrine when I create a custom module. Is it implemented in 9 dev yet? Any idea of when 9 will be at a stable version? Or will it not be implemented until a future version of 9?

# Answer
> 2 votes
Drupal 9 is planned for some time in 2020. No, Doctrine ORM is not in a 9.x-dev branch.

As far as implementing, there are no immediate plans for it. D8 has its own custom DBAL, utilizing PHP PDO, and it's own custom ORM via its Entity API.

Doctrine has been proposed as a replacement but it's not an easy undertaking so don't expect it any time soon. Pre-existing DBAL/ORM components don't get replaced quickly.

If you want to utilize Doctrine ORM or DBAL, there are existing module projects out there that implement it. You're better off utilizing those projects or the Drupal Entity API (if your objects are managed content) than waiting for it to show up in D9

---
Tags: database
---


# Question
Title: How to use articles attached images as background of a div
I'm doing my first site on Drupal 8 and I have a problem. I would like you to help me.

In fact I'm trying to get the articles attached images as a background for a div created in the page templates.

I wrote this code in my theme.file

```
function THEME_preprocess_page(&$variables, $hook) {

// Set articles attached img like background
$node = Drupal::request()->attributes->get('node');
if($node){
    if ($node->bundle() == "article") { // Content type check
        $image = file_create_url($node->field_image->entity->getFileUri()); // Creating file path from uri
        $variables['article'] = true; // Setting value true for current node is articles.
        $variables['background_img'] = $image;
    }
  }
}

```

and I try to get the image back with the following code in the field--node--field-image--article.html.twig template

```
<div class="img-ban" style="background: url({{ my_image }});"></div>

```

but it doesn't work.

Can someone tell me what's wrong with this code? I would really appreciate it. Thank you.

# Answer
## Contrib module

What you are describing can be done easily with a contrib module. You could try background\_image, bg\_image\_formatter, bg\_img\_field perhaps there are others.

## Use image in node.html.twig or variant

If you MUST DO IT WITH CUSTOM CODE and you want `my_image` in `node.html.twig` or `node--article.html.twig` you need to prepare it in `hook_preprocess_node`

```
function THEMENAME_preprocess_node(&$variables) {
    $node = $variables["node"];
    if ($node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
      // can set more variables
    }
}

```

## Use image in page.html.twig

If you want to include it in a div inside your `page.html.twig` you should use `hook_preprocess_page` and note that `$node` has to be extracted from the ROUTE

```
function THEMENAME_preprocess_page(&$variables) {
  // get the current node
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->bundle() == "article" && $node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
      // can set more variables
    }
  }
}

```

## Use image in field.html.twig or variant

I can't see the use case but if you want to use it in `field.html.twig` or a variant such as `field--node--field-image--article.html.twig` you can access it directly

```
{% set my_image = file_url(element['#object'].field_image.0.entity.uri.value) %}

```

or can set `my_image` using a `hook_preprocess_field`

```
function THEMENAME_preprocess_field(&$variables) {
  if($variables["element"]["#field_name"] == "field_image"){
    // get parent node
    $node = $variables['element']['#object'];
    if ($node->bundle() == "article" && $node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
    }
}

```
> 3 votes

---
Tags: theming, media
---


# Question
Title: How do I fix the errors I get after removing the comment field from a content type?
After I removed the comment field from the user interface, and uninstalled the Comments module, I can't open any *Article* node.

In the Drupal log, I find this message.

> InvalidArgumentException: Field comment is unknown. in Drupal\Core\Entity\ContentEntityBase-\>getTranslatedField() (line 580 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).
> Drupal\Core\Entity\ContentEntityBase-\>get("comment") (Line: 17)
> gavias\_sanbro\_preprocess\_node(Array, "node", Array) (Line: 287)
> Drupal\Core\Theme\ThemeManager-\>render("node", Array) (Line: 437)
> Drupal\Core\Render\Renderer-\>doRender(Array, ) (Line: 195)
> Drupal\Core\Render\Renderer-\>render(Array, ) (Line: 226) Drupal\Core\Render\MainContent\HtmlRenderer-\>Drupal\Core\Render\MainContent{closure}() (Line: 582)
> Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 227)
> Drupal\Core\Render\MainContent\HtmlRenderer-\>prepare(Array, Object, Object) (Line: 117)
> Drupal\Core\Render\MainContent\HtmlRenderer-\>renderResponse(Array, Object, Object) (Line: 90)
> Drupal\Core\EventSubscriber\MainContentViewSubscriber-\>onViewRenderArray(Object, "kernel.view", Object)
> call\_user\_func(Array, Object, "kernel.view", Object) (Line: 111)
> Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch("kernel.view", Object) (Line: 156)
> 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: 99)
> Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78)
> Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47)
> Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50)
> Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23)
> Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 657)
> Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

How can I fix this issue?

# Answer
Given your error stacktrace:

Check function `gavias_sanbro_preprocess_node()` (Line: 287 in your `gavias_sanbro.theme` theme file).

This preprocessing function obviously tries to access the `comment` field without checking, whether it exists. As you uninstalled the field, it is causing your exception.

You may comment out, remove, or alter the code accordingly.
> 1 votes

---
Tags: comments
---


title: TableSelect with drag-and-drop weight

text:
# Question
Title: TableSelect with drag-and-drop weight
I have a tableselect and I have been looking all over the internet for a tutorial on how to make a tableselect have sorting/drag-and-drop functionality. I have found tutorials for making normal lists have click and drag, but not a single mention of tableselect.

I would like to know if making a tableselect draggable is possible. I'm not asking for a tutorial. At this time I just want to know if it is possible.

This the form element I am using.

```
$form['mod_setttings']['settings'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No settings available')
);

```

This tableselect is inside a vertical\_tabs element.

# Answer
i think you are looking for tabledrag option.If so please refer drupal\_add\_tabledrag
> 0 votes

# Answer
check these examples :

Drupal: Drag and Drop Tables in Custom Modules

CREATING A FORM WITH DRAGGABLE ELEMENTS
> 0 votes

# Answer
Without writing your code, you cannot. To make a table (which isn't a form element) draggable, you first call `theme('table')` and then `drupal_add_tabledrag()`. With a *tableselect* form element, you don't call `theme('table')`, so you cannot call `drupal_add_tabledrag()` either.

What you could do is implementing a new form element and, in the theme function associated to that form element, call `theme('table')` and then `drupal_add_tabledrag()`. `theme_tableselect()` code can be used as guideline.

```
function theme_tableselect($variables) {
  $element = $variables['element'];
  $rows = array();
  $header = $element['#header'];
  if (!empty($element['#options'])) {

    // Generate a table row for each selectable item in #options.
    foreach (element_children($element) as $key) {
      $row = array();
      $row['data'] = array();
      if (isset($element['#options'][$key]['#attributes'])) {
        $row += $element['#options'][$key]['#attributes'];
      }

      // Render the checkbox / radio element.
      $row['data'][] = drupal_render($element[$key]);

      // As theme_table only maps header and row columns by order, create the
      // correct order by iterating over the header fields.
      foreach ($element['#header'] as $fieldname => $title) {
        $row['data'][] = $element['#options'][$key][$fieldname];
      }
      $rows[] = $row;
    }

    // Add an empty header or a "Select all" checkbox to provide room for the
    // checkboxes/radios in the first table column.
    if ($element['#js_select']) {

      // Add a "Select all" checkbox.
      drupal_add_js('misc/tableselect.js');
      array_unshift($header, array(
        'class' => array(
          'select-all',
        ),
      ));
    }
    else {

      // Add an empty header when radio buttons are displayed or a "Select all"
      // checkbox is not desired.
      array_unshift($header, '');
    }
  }
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'empty' => $element['#empty'],
    'attributes' => $element['#attributes'],
  ));
}

```

Keep in mind the conditions reported in `drupal_add_tabledrag()` for the dragging to work, including that the table must have an ID attribute which must be equal to the first argument passed to `drupal_add_tabledrag()`, and each table row needs a weight value (which is used to sort the rows).
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Behat @javascript test can not login user - incorrect username or password message
I am running:

* Drupal 7
* Behat 3.5.0
* Selenium 3.5.0
* Chrome Driver 73.x

Using this test:

```
Feature: User Profile

Background:
  Given users:
    | name | status | roles |
    | incomplete | 1 | authenticated user |
    | complete | 1   | authenticated user |

  Given profiles:
    | drupal_username | field_profile_completed:value | field_first_name | field_last_name | field_birth_month | field_birth_day | field_degree | field_profession | field_specialty | field_organization | field_department |
    | incomplete | 0                                  | |  |  |  |  |  |  |  |  |
    | complete   | 1                                  | John | Doe | 08 | 03 | APRN | 15 | Anesthesiology | MyOrganization | MyDepartment |

@api
@noEncrypt
@defaultRegistration
@javascript
Scenario: As a user with an incomplete profile I should NOT see an icon indicating my profile is not complete.
  Given I am logged in as complete
  Then I should not see an ".js--user-profile-incomplete" element

@api
@noEncrypt
@defaultRegistration
@javascript
Scenario: As a user with an incomplete profile I should see an icon indicating my profile is not complete.
  Given I am on "/user/login"
  And I fill in the following:
    | name | incomplete|
    | pass | password |
  And press "edit-submit"
  Then I should be on "/"
  Then I should see an ".js--user-profile-incomplete" element
  When I wait for ".profile-notify__incomplete"
  Then I should see an ".profile-notify__exclamation" element

```

As you can see, I've tried logging in using Given I am logged in as *and* tried logging in via a meta-step. I can watch it in the browser and I'm getting an "Unrecognized username or password" error.

Login works fine without `@javascript` but I can't test the "When I wait" functionality. If I use a break I can see that the users are created in the database.

Why are my `@javascript` tests not able to login?

# Answer
It was a pain to track down but I traced it to the Security module. It encrypts the password field on form submit - disabling the module allows Behat `@javascript` tests to run fine.
> 0 votes

---
Tags: testing
---


# Question
Title: How to change the labels TRUE and FALSE of a boolean field in views exposed filter
I am using the flag module to toggle a node type 'Task' as Done. I made a view that lists the tasks, and added a views exposed filter for the flag status, which is a boolean field. In this way users can filter the view by selecting True or False for the flag status.

However, I want to change the labels 'True' and 'False' to 'Done' and 'Not Done'

I see no setting in the views exposed filter field that allows to change this setting. Is there another way to do this?

# Answer
> 6 votes
There is a number of ways how to do it, check out this thread for a lot of suggested options: Change the '- Any -' text in an exposed taxonomy filter.

You can change the themed output for that form and filter, you need a bit of custom code for that.

You could use Better Exposed Filters module, it lets you override each option text:

> Use this field to rewrite the filter options displayed. Use the format of current\_text|replacement\_text, one replacement per line. For example:
>
> Current|Replacement
> On|Yes
> Off|No

Without any additional modules or code changes you can use the Flagged Exposed filter **Grouped filters** option instead of the `Single filter` you're using now.

The Grouped filters allow you to enter a Label for each grouping. Only in your case you simply select "True" for the first grouping and "False" for the second grouping, which means you haven't grouped anything, you're just repeating the same options from the Single filter:

---
Tags: views, 8, flags
---


# Question
Title: Unique form per user with custom form class
Not sure if this is a related/duplicate of Generate unique form ID based on context

I am hoping I can render a unique form per user with the Form API using a custom form class.

What I've seen with `\Drupal::formBuilder()->getForm()`, you must provide your `Form::class` and this does not allow for something like:

```
public function getFormId() {

  $userID = \Drupal::currentUser()->id();
  $userFormID = 'form_settings' . $userID;
  return $userFormID;

}

```

and returns an invalid form with `\Drupal::formBuilder()->getForm()`.

Ultimately trying to render a unique form via `hook_preprocess_page()` for the user to interact with.

---

An idea of what I have so far is a simple form with two submit items.

**MYMODULE\src\Form\Form.php**:

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

  $config = \Drupal::config('MYMODULE.MYMODULE_settings');

  $form['description'] = [
    '#type' => 'item',
    '#markup' => $messageMarkup,
  ];

  $form['time'] = [
    '#type' => 'hidden',
    '#default_value' => time(),
  ];

  $form['form_delay'] = [
    '#type' => 'submit',
    '#value' => $this->t('Remind Me'),
    '#submit' => ['::submitFormDelay'],
  ];

  $form['form_ignore'] = [
    '#type' => 'submit',
    '#value' => $this->t('Ignore'),
    '#submit' => ['::submitFormIgnore'],
  ];

  return $form;

}

public function submitFormDelay(array &$form, FormStateInterface $form_state) {

  $values = $form_state->getValues();

  $this->configFactory->getEditable('MYMODULE.MYMODULE_settings')
    ->set('time', $values['time'])
    ->save();

  parent::submitForm($form, $form_state);

}

public function submitFormIgnore(array &$form, FormStateInterface $form_state) {

  $this->configFactory->getEditable('MYMODULE.MYMODULE_settings')
    ->set('time', NULL)
    ->save();

  parent::submitForm($form, $form_state);

}

```

Then grabbing the time value to see if I should show the form

**MYMODULE.module**:

```
function MYMODULE_preprocess_page(&$variables) {

  $config = \Drupal::config('MYMODULE.MYMODULE_settings');

  // Comes from another form controller in the module.
  $reminderDelay = $otherFormConfig->get('reminder_delay');

  $timeAtInteraction = $config->get('time') ?: NULL;

  $timeForm = \Drupal::formBuilder()
    ->getForm(\Drupal\my_module\Form\Form::class);

  if ($timeAtInteraction != NULL) {

    if ($timeAtInteraction < (time() - $reminderDelay)) {
      // Provide our form to page.html.twig.
      $variables['timeForm'] = $timeForm;
    }

  }

}

```

The form works, but of course, a single user sets it for everyone. I'd like the form/values to be unique per user.

Is it possible using the Form API?

(Working on cache contexts as suggested below, but not included above.)

# Answer
> 2 votes
Your updated post shows the issue. The issue here isn't the form, it's the underlying storage method. You are using configuration, which is for site configuration, ie configure how the site as a whole works. But you want to save values per user, not for the whole site.

What you are looking for is having a form used by all users, saving the submitted values for the user, rather than for the site.

I would suggest using the user.data service. This service lets you save data for users. You can user UserData::set() to set values, and UserData::get() to get values. Get the values in the form definition to get the default value, and set the values in the submit handlers to update them with the current values.

As a side note, if you were creating a form for configuration (which you're not), you would want to extend ConfigFormBase, which it doesn't appear you were doing, based on your code.

---
Tags: 8, forms
---


# Question
Title: Render taxonomy type custom fields individually
I'm kind of a twig newbie so I'm hoping that someone can point me in the right direction.

I've added a custom field **field\_url** to a taxonomy type called **field\_type\_poi**. How would you render that taxonomy type's individual field in **node.html.twig**?
I know that I can use **{{ content.field\_type\_poi }}** to render the entire contents of the taxonomy type, but I'm looking for a way to render one field specifically.

# Answer
> 1 votes
`{{ content.field_type_poi }}` doesn't necessarily render the entire content of the taxonomy term. You can select the field in the tab *Manage Display* where you've added the field `field_url` to the vocabulary.

If you need multiple field selections, here only this field, but in all other places the default selection, then add a custom view mode in *Custom Display Settings* at the bottom of the page.

Finally go to the content type and configure the field `field_type_poi` in the tab *Manage Display* to be rendered in the view mode you've configured above.

---

**Edit:**

If you want to use different fields from the taxonomy in different locations you would need to clone the field, see Show field twice in node page, or install the module Twig Tweak and render single fields in Twig:

```
{% set tid = node.field_type_poi.target_id %}
{% if tid %}
  {{ drupal_field('field_url', 'taxonomy_term', tid) }}
{% endif %}

```

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


# Question
Title: Problem using Font Awesome for a Custom text in a view
I have a custom entity (contract) created in a custom module (amap) by a bunch of BaseFieldDefinition.

This is the corresponding form.

>

One of the fields is a file defined this way.

```
$fields['file1'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Source file'))
  ->setDescription(t('Source file (may be modified)'))
  ->setSettings([
    'target_type' => 'file',
    'file_extensions' => 'doc docx odt pages',
    'file_directory' => 'contrats',
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setReadOnly(TRUE);

```

I have a view about a custom entity that displays some fields in table mode.

>

The actions are defined using *Custom text*. For example, the first one is the following one.

>

I use Font Awesome Icons in these Custom texts, and I have a problem with this: If the field 'file1' doesn't exist (as in the second row), it displays exclamation-triangle icon with no link, which is OK; if 'file1' exists (as in the first row), it displays the download icon with a link to the file (which is OK) and the exclamation-triangle icon with no link (which shouldn't be there).

What is wrong?

By the way, if I replace Font Awesome icons by a simple character, it works as expected.

```
{% if file1__target_id %}
  A
{% else %}
  B
{% endif %}

```

>

This is the HTML markup of the part of the page related to the view output (header and two rows).

```
<div id="block-mayo-content" class="block block-system block-system-main-block">
    <div class="content">
        <div class="views-element-container contextual-region">
            <div class="contextual-region view view-amap-contracts view-id-amap_contracts view-display-id-page_1 js-view-dom-id-404c9a70ff66dba6ebf5ff803693aafc74ec9d93a006df3b4e5af9de3b1c1b30">
                <div data-contextual-id="entity.view.edit_form:view=amap_contracts:location=page&name=amap_contracts&display_id=page_1&langcode=fr" data-contextual-token="P56DWcQ_TYjoKxCel2ETjrZhR1bCqk6wRud80xjPtno">
                </div>
                <div class="view-header">
                    <a href="/amap/contract/add?destination=amap/contracts" title="Ajouter un contrat"><i class="fas fa-plus-square"></i></a>
                </div>
                <div class="view-content">
                    <table class="views-table views-view-table cols-7 sticky-enabled">
                        <thead>
                            <tr>
                                <th class="views-align-left views-field views-field-type views-align-left" id="view-type-table-column" scope="col">Type</th>
                                <th class="views-align-left views-field views-field-name views-align-left" id="view-name-table-column" scope="col">Nom</th>
                                <th class="views-align-center views-field views-field-startdate views-align-center" id="view-startdate-table-column" scope="col">Date début</th>
                                <th class="views-align-center views-field views-field-enddate views-align-center" id="view-enddate-table-column" scope="col">Date fin</th>
                                <th class="views-align-left views-field views-field-referentid views-align-left" id="view-referentid-table-column" scope="col">Référent</th>
                                <th class="views-align-center views-field views-field-isvisible views-align-center" id="view-isvisible-table-column" scope="col">Visible</th>
                                <th class="views-align-left views-field views-field-nothing views-align-left" id="view-nothing-table-column" scope="col">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="odd">
                                <td headers="view-type-table-column" class="views-field views-field-type views-align-left"><a href="/amap/contract_type/1" hreflang="und">Fruits rouges</a> </td>
                                <td headers="view-name-table-column" class="views-field views-field-name views-align-left"><a href="/sites/default/files/contrats/Contrat-1-20190101.pdf" target="_blank">Contrat Fruits rouges 2019</a> </td>
                                <td headers="view-startdate-table-column" class="views-field views-field-startdate views-align-center">01/01/2019 </td>
                                <td headers="view-enddate-table-column" class="views-field views-field-enddate views-align-center">31/12/2019 </td>
                                <td headers="view-referentid-table-column" class="views-field views-field-referentid views-align-left"><a href="/association/person/11" hreflang="und">Falzon Eric</a> </td>
                                <td headers="view-isvisible-table-column" class="views-field views-field-isvisible views-align-center">Oui </td>
                                <td headers="view-nothing-table-column" class="views-field views-field-nothing views-align-left views-field-nothing-2 views-field-nothing-5 views-field-nothing-3 views-field-nothing-4 views-field-nothing-1"><a href="/amap/contract/1/edit?destination=amap/contracts"><i class="fas fa-edit" title="Éditer le contrat"></i></a> <a href="/amap/contract/1/delete?destination=amap/contracts"><i class="fas fa-trash" title="Supprimer le contrat"></i></a> <a href="/amap/contract/1/subscribe?destination=amap/contracts"><i class="fas fa-list-alt" title="Entrer les souscriptions"></i></a> <a href="/amap/contract/1/Fruits%20rouges/export?destination=amap/contracts"><i class="fas fa-file-csv" title="Exporter le contrat"></i></a> <a href="/sites/default/files/contrats/Contrat-1-20190101.docx" target="_blank"><a href=" /sites/default/files/contrats/Contrat-1-20190101.docx "><i class="fas fa-download" title="Télécharger l'original"></a> </a> </td>
                            </tr>
                            <tr class="even">
                                <td headers="view-type-table-column" class="views-field views-field-type views-align-left"><a href="/amap/contract_type/1" hreflang="und">Fruits rouges</a> </td>
                                <td headers="view-name-table-column" class="views-field views-field-name views-align-left">Contrat Fruits rouges 2020 </td>
                                <td headers="view-startdate-table-column" class="views-field views-field-startdate views-align-center">01/01/2020 </td>
                                <td headers="view-enddate-table-column" class="views-field views-field-enddate views-align-center">31/12/2020 </td>
                                <td headers="view-referentid-table-column" class="views-field views-field-referentid views-align-left"><a href="/association/person/11" hreflang="und">Falzon Eric</a> </td>
                                <td headers="view-isvisible-table-column" class="views-field views-field-isvisible views-align-center">Oui </td>
                                <td headers="view-nothing-table-column" class="views-field views-field-nothing views-align-left views-field-nothing-2 views-field-nothing-5 views-field-nothing-3 views-field-nothing-4 views-field-nothing-1"><a href="/amap/contract/2/edit?destination=amap/contracts"><i class="fas fa-edit" title="Éditer le contrat"></i></a> <a href="/amap/contract/2/delete?destination=amap/contracts"><i class="fas fa-trash" title="Supprimer le contrat"></i></a> <a href="/amap/contract/2/subscribe?destination=amap/contracts"><i class="fas fa-list-alt" title="Entrer les souscriptions"></i></a> <a href="/amap/contract/2/Fruits%20rouges/export?destination=amap/contracts"><i class="fas fa-file-csv" title="Exporter le contrat"></i></a> <i class="fas fa-exclamation-triangle " title="Pas d'original à télécharger"> </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

```

This is how I use the view UI to define the problematic icon.

>

# Answer
> -1 votes
You have nested link tags `<a...><a...></a></a>` \- this is invalid HTML. Most browsers try to fix this by breaking it into two links `<a...></a> <a...></a>`, which most likely causes two icons in your case.

---
Tags: views, 8
---


# Question
Title: Update node revision time in hook_entity_presave
In my site Drupal 8, I have custom entities (say components) and bundles. I load these entities in a node using the *Inline entity* module.
On the front-end, the contextual links provide two edit links: an edit link to edit the node with all inline entities and a link for a specific entity. When users use the second link, they get the edit page for that entity and its field values. Using the second link, the node last update value won't change.

I tried updating the node value in `hook_entity_presave()`, but it creates infinite redirection. How do I avoid it?

# Answer
`hook_entity_presave()` cannot save any entity, or saving an entity will cause `hook_entity_presave()` to be invoked again. If your `hook_entity_presave()` implementation isn't able to understand it is invoked for the second time, and saves again an entity, it will cause an infinite loop.
Even if you implement `hook_ENTITY_TYPE_presave()` and save a different entity, you will cause `hook_entity_presave()` to be invoked more than once, and that could cause issues.

In your case, if *components* is the entity type being edited, you should implement `hook_components_presave()`, get the node for which you need to alter the *Last changed* value, and save that node. As I said, I cannot guaranty there will not be issues, but at least your `hook_components_presave()` implementation won't be called twice, as it is invoked for the *components* entities, and it saves a node. The issues would come, for example, from a module that assumes that `hook_entity_presave()` is invoked only when a user edits or creates a node, and saves it.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Some of the pending updates cannot be applied because their dependencies were not met
I have a Drupal 7 site that is giving me the above error. I cannot for the life of me, figure out what dependency needs to be met. And I can't not remember what I did, or if I did anything, to cause it.

Is there any way to get more info than that?

# Answer
> 2 votes
For those who end up here with the same issue on a Drupal 8 web site, I found that using drush's updb command will give information that the UI does not:

```
 drush updb
 [warning] The following module is missing from the file system: media_bulk_upload bootstrap.inc:276
 [warning] The following module is missing from the file system: media_upload bootstrap.inc:276

```

# Answer
> 1 votes
This may help: http://drupal.org/node/915216

Others that are more module specific may be:

1. http://drupal.org/node/1190294
2. http://drupal.org/node/1111524

---
Tags: updating
---


title: How to add icons to a menu?

text:
# Question
Title: How to add icons to a menu?
I use Drupal 8.

I would simply want to add icons to one of the menus with a `<span>`.

Have you runways?

# Answer
This is how I'm doing it for dropdown operations(Font Awesome icons).

```
/**
 * Implements hook_preprocess_links().
 */
function HOOK_preprocess_links(array &$variables) {
  if (stripos($variables['theme_hook_original'], 'links__dropbutton__operations') === 0) {
    $variables['attributes']['class'][] = 'menu';
    $links = &$variables['links'];
    foreach ($links AS $key => &$link) {
      switch (Html::getClass($key)) {
        case 'view';
        case 'canonical':
          $icon = 'eye';
          break;

        case 'edit':
          $icon = 'pencil';
          break;

        case 'delete':
          $icon = 'trash';
          break;

        case 'clone':
          $icon = 'clone';
          break;

        case 'add':
        case 'create':
        $icon = 'plus';
          break;

        case 'manage-fields':
          $icon = 'list';
          break;

        case 'manage-form-display':
          $icon = 'server';
          break;

        case 'manage-display':
          $icon = 'th';
          break;

        case 'devel':
          $icon = 'code';
          break;

        case 'pay':
          $icon = 'money';
          break;

        case 'enable':
          $icon = 'toggle-off';
          break;

        case 'disable':
          $icon = 'toggle-on';
          break;

        default:
          $icon = 'question';
          break;
      }

      $link['link']['#title'] = [
        '#type' => 'inline_template',
        '#template' => '<i class="fa fa-{{ icon }}" title="{{ title }}"></i><span class="visually-hidden">{{ title }}</span>',
        '#context' => [
          'title' => $link['link']['#title'],
          'icon' => $icon
        ]
      ];
    }
  }
}

```
> 3 votes

# Answer
There is a new easy alternative to display icons in Menu Items in Drupal 8:

The Menu Manipulator module now provides an option for you to create a list of available icons that editors can select when editing menu links.

The icon's ID is then passed to Twig so you can theme/render/display it however you want (e.g. an icon font such as FontAwesome, a custom Twig file, as a background image in CSS ...etc).

Example `yourtheme/templates/menus/menu--main.html.twig`:

```
[...]
    {% for item in items %}
      <li{{ item.attributes.addClass('menu-item', 'column') }}>
        {% if item.icon %}
             {# Assuming you use so type of icon font #}
             <span class="fa fa-{{item.icon}}"></span>

             {# Assuming your icons are callable as Twig file. #}
             {% include '@yourtheme/icons/icon.html.twig' with { icon: item.icon } %}
        {% endif %}
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
[...]

```
> 1 votes

# Answer
You can check how the Menu Item Extras add the body field or you can use the body field abd insert image with the CKEditor.
> 0 votes

---
Tags: theming, 8
---


title: Bidirectional entity relationships?

text:
# Question
Title: Bidirectional entity relationships?
I am doing a migration right now and have a need to maintain how entities are related in a way that the core entity reference field does not seem to support.

Lets say I have two content types, Foo and Bar. I am migrating Foo first, and Bar gets stubbed.

I need to relate Foo to Bar, but the relationship is not one way. Bar is also related to Foo, but there is no way (when editing Bar) to see this relationship. If Foo or Bar are deleted, it needs to unlink that.

Does Drupal 8 do that yet? How would you effectively do this? Do you need to create a custom entity to hold links?

I looked at the Dynamic Entity Reference module and it does not seem to do this. I also looked at the Corresponding Entity Reference module and it looks dead with a lot of logged bugs (last release 2017).

# Answer
I would use 2 entity reference field, one in each content type referencing the other. With some custom logic, you could add the desired behavior, eg remove reference Foo -\> Bar when the user removes Bar -\> Foo.

Regarding the migation, you can run the first migration twice with the `--update` flag the 2nd time:

* Step 1. Migrate Foo. The migration\_lookup plugin will not find any values for the entity reference so it will be empty.
* Step 2. Migrate Bar. Foo already exists, you should have no problem with the entity reference.
* Step 3. Migrate Foo again, with the `--update` flag. Bar already exists, so the entity reference field will filled.
> 2 votes

# Answer
> Does Drupal 8 do that yet?

Not that I know of.

> How would you effectively do this?

I would use hook\_ENTITY\_TYPE\_presave and sprinkle some custom code, like the following simple example:

```
function MODULE_node_presave(Drupal\node\NodeInterface $node) {
    if ($node->bundle() == 'article') {
      $node2 = Node::load($node->field_reference->value); // load referenced node.
      $node2->field_reference->value = $node->id(); // reference back original node.
      $node2->save(); // save referenced node.
    }
  }
}

```
* If they are different content types the above is fine.
* If they are the same content type, then watch out for infinite loop! Add a condition to check if the reference already exists, or save directly to DB to prevent another presave hook from firing.

I believe when you delete node, Drupal automatically deletes references, but double check on that by looking at the DB.

You will also want to cover the scenario when a reference gets removed via node update, to do that use:

```
function MODULE_node_presave(Drupal\node\NodeInterface $node) {
    if ($node->bundle() == 'article') {
      if (!empty($node->original) &&
         $node->original->field_reference->value != $node->field_reference->value) { // check if it changed
            $node2 = Node::load($node->original->field_reference->value); // load removed referenced node.
            $node2->field_reference->value = ''; // remove reference back to original node.
            $node2->save(); // save removed referenced node.
      }
   }
}

```

Obviously all the above is the most basic scenario, if you allow for multiple values, you'll have to work with loops and arrays and perhaps with even with the Batch API if there are lots of nodes that reference the same node.

---

That said, the above is only necessary in special use cases, where the owner wants to be able to link or unlink from either end. Most of the time one way is enough, as you can easily get the referencing node info via views relationship, twig, or DB query.
> 0 votes

---
Tags: 8, entities
---


title: How do I minify inline CSS using Twig?

text:
# Question
Title: How do I minify inline CSS using Twig?
Inside my html.html.twig template I've added a stylesheet inside the style elements using this.

```
{% include directory ~ '/css/base/style.css' %}

```

Is there a way that I can strip it for all whitespaces? Can I apply the CssOptimizer class to it in any way? Can I also strip the stylesheet for comments?

# Answer
> 2 votes
This is not the right way to integrate a .css file inside a twig file in drupal8. You should use the standard procedure as I mentioned below.

```
 {{ attach_library('bartik/messages') }}
```

SO now for minifying the .css you can use the 3rd party site- https://cssminifier.com/

So the after minifying the .css file, crate the library

```
messages:
  css:
    theme:
      css/components/my-minify.css: {}

```

Then attach the library in the twig by using the below sysntax

```
{{ attach_library('your-theme-name/messages') }}

```

Hope this will help you. If any doubt please don't hesitate to mention.

# Answer
> 1 votes
Take a look at the Advanced CSS/JS Aggregation module.

---
Tags: theming, 8
---


title: Concatenate variable to node value

text:
# Question
Title: Concatenate variable to node value
```
{%
  set fields_array = [
    'field_address',
    'field_phone',
  ]
%}
{% for field in fields_array %}
  {{ node.field }}
{% endfor %}

```

How to concate dynamic value to node object?

# Answer
> 1 votes
To get a field with the field name stored in the variable `field` you can use the method `get()` on the node:

```
{{ node.get(field).value }}

```

---
Tags: 8, theming
---


title: Update price via AJAX

text:
# Question
Title: Update price via AJAX
I created a content type (main prod) that is referencing a product content type (sub prod). The sub prod is also referencing another product content type called (option sets) which will be the option sets of that product, with the use of Commerce Product Bundle I was able to combine all the different prices of the sub prod and the option sets and with the use of Commerce Product Attributes I am able to change the option sets to a list text field.

I applied a patch that I saw to calculate the total price of all the chosen option sets and the sub prod on the cart and checkout page. My problem is on the product page itself I want the price of the sub prod to be calculated depending on the option sets chosen via real time of with using ajax.

Can anybody help?

This is the list of commerce modules I have currently installed on my site.

# Answer
The answer is that "Commerce Product Bundles" (https://www.drupal.org/project/commerce\_product\_bundle) is never recommended since it circumvents large portions of Drupal Commerce. You should consider using line item fields or https://www.drupal.org/project/commerce\_bundle if bundling is important to you.

Note: Custom line item fields also suffer from not having ajax updates. The community effort to make this a reality can be found here: https://www.drupal.org/node/1541886 and a video that describes an interesting use case for line item fields is here: https://www.youtube.com/watch?v=j9KsyvQZaAY
> 0 votes

# Answer
If you are using Drupal 7 - what you are looking for might be module custom\_price, or Rules module(maybe with conditional\_rules extension). If you are using Drupal 8 - your options are either Rules module or writing a whole custom module that will be intercepting showed and calculated price based on specific rules that you would create.
> 0 votes

---
Tags: commerce, ajax
---


# Question
Title: How do I enable dynamic favicons in a custom theme?
So, I'm working on a site that I didn't build and I'm trying to figure out how to get the favicons working. The site has favicons enabled in the theme settings folder as well as through the themes settings UI, however no favicons are showing up. From what I read, this should just be a question of putting the favicon in the theme root folder. The issue is that I have a bunch of favicons that are meant to be served dynamically (e.g. different devices/sizes, etc) from a subfolder of my theme e.g. `themes/custom/mytheme/assets/images/favicon`. I haven't dug too far into this yet, but I assume that there's a script somewhere that deals with this. So, how or what do I do to enable my favicons?

# Answer
Unless your theme allows for functionality to add further icons you'll need to add head link tags yourself with something like this using template\_preprocess\_html:

```
function YOURTHEME_preprocess_html(&$variables) {
  $icon = [
        '#tag' => 'link',
        '#attributes' => [
            'href' => '<url to your icon-52x52.png>',
            'rel' => 'shortcut icon',
            'sizes' => '52x52'
        ],
    ];
    $variables['#attached']['html_head'][] = [
        $icon,
        'icon52x52
    ];
}

```

Or if you want to avoid adding code the metatag module as a sub module of "Metatag: favicons" to allow you to add them from the CMS https://www.drupal.org/project/metatag
> 2 votes

# Answer
As an alternative to your custom implementation you can use responsive\_favicons that helps with creating and displaying all the favicons for all platforms correctly without knowing all the details of what goes where or proper names.

Part of the instructions will tell you to to upload a favicon.png (greater than 260px width is recommended) and with a form to fill will generate all icons for you.
> 0 votes

---
Tags: 8
---


title: Event subscription for EntityTypeEvents

text:
# Question
Title: Event subscription for EntityTypeEvents
So I'm trying to get an event subscriber working for EntityTypeEvents and I can't figure out why it's not firing.

This is a general outline of the code:

```
namespace Drupal\subscriber_class_module;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Entity\EntityTypeEvents;
use Drupal\Core\Entity\EntityTypeEvent;

class SubscriberClassModuleSubscribesToEntityTypeEvents implements EventSubscriberInterface {

    public function onCreate(EntityTypeEvent $event)  {
          //Do things on creation
    }
    public function onUpdate(EntityTypeEvent $event)  {
          //Do things on update
    }
    public function onDelete(EntityTypeEvent $event)  {
          //Do things on delete
    }
    static function getSubscribedEvents() {
         $events = [];

         $events[EntityTypeEvents::CREATE][] = array('onCreate', 100);
         $events[EntityTypeEvents::UPDATE][] = array('onUpdate', 100);
         $events[EntityTypeEvents::DELETE][] = array('onDelete', 100);
         return $events;
    }
}

```

Added class declaration and namespacing. I should note that the same class that I am using has no probablem firing on kernel events, I'm just wondering if there is something special about entity events.

# Answer
> 3 votes
i already have the same issue, you have to implement this class to EntityTypeListenerInterface and use the trait EntityTypeEventSubscriberTrait

```
class SubscriberClassModuleSubscribesToEntityTypeEvents implements EntityTypeListenerInterface, EventSubscriberInterface{

use EntityTypeEventSubscriberTrait;

public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
}

public function onCreate(EntityTypeEvent $event)  {
      //Do things on creation
}
public function onUpdate(EntityTypeEvent $event)  {
      //Do things on update
}
public function onDelete(EntityTypeEvent $event)  {
      //Do things on delete
}

/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
    return static::getEntityTypeEvents();
}

```

}

and you get to load entity manager in your module.service.yml declaration arguments: \['@entity.manager'\]

---
Tags: 8, entities, event-subscribers
---


title: I cannot translate the action label

text:
# Question
Title: I cannot translate the action label
I'm using Umami profile and choose Spanish is default language. Almost of the interface has been translated into Spanish. But some places did not translate like user page.

I'm going to **admin/config/regional/translate** to check. But This text already translated, but UI still show English text.

I try debug to find the reason. I was break point at line 340 of line drupal/core/modules/views/src/Plugin/views/field/BulkForm.php and found that $action-\>label() return English string.

Because at line 116 `$this->actionStorage->loadMultiple()` return all actions. In this some actions return English string, some actions return Spanish string (example install module pathauto, this action return Spanish). All actions when install profile will using English text and module install after will be translate.

I don't know why. And How to can translate label of actions?

# Answer
To translate action labels install the core module **Actions** and go to `/admin/config/regional/config-translation/action`.

Actions are config entities, which you can translate in an exported config as well, if you don't want to install the UI option.
> 5 votes

# Answer
You can translate them easily in `hook_form_alter()`.

```
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id ='views_exposed_form' && isset($form['header']['node_bulk_form']['action']['#options'])) {
    foreach ($form['header']['node_bulk_form']['action']['#options'] as $key => $option) {
      $form['header']['node_bulk_form']['action']['#options'][$key] = t($option);
    }
  }
}

```
> 1 votes

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


# Question
Title: CKEditor toolbar missing when conditional field becomes visible
I use the D8 Conditional Fields module to make a CKEditor field (author bio) invisible until there is something in another field (author). When I type something in the author field, the author bio field becomes visible, but it doesn't include a CKEditor toolbar. It appears that CKEditor initialization is not done on fields that aren't initially visible. Any way to overcome this?

# Answer
Not finding a built-in way to avoid the problem of missing CKEditor toolbars on conditionally displayed fields, instead of using the Conditional Fields module, I use the Asset Injector module's JS Injector to inject this JavaScript into the node add/edit page (note that the authors field is an entity reference):

```
var el = document.getElementById("edit-field-authors-0-target-id");

if (el) {
  showHideBio();
  el.addEventListener("change", showHideBio);
}

function showHideBio()
{
  var el = document.getElementById("edit-field-bio-wrapper");

  if (this.value) {
    el.style.display = "block";
  }
  else {
    el.style.display = "none";
  }
}

```

Seems to work just fine, but open to suggestions for improvement. Thanks to @Taggart Jensen for the idea.
> 1 votes

---
Tags: 8, wysiwyg, toolbar
---


title: module to test if e-mail is working

text:
# Question
Title: module to test if e-mail is working
In D7 I'm trying to determine the best way to periodically check if e-mail is working. I'm looking for a way to create a workflow that, say, on cron would check the day of the month, if it's the day that has been configured in the module as the test day, send an e-mail. Check the return value on the e-mail function. If the e-mail failed, write the error to the logs and/or send it to another service, like Slack, to alert the team.

Is there a module that comes close to doing this, or can something be cobbled together with actions and rules, etc? Thanks!

# Answer
What I did instead: Since all I really want to know is when e-mail fails, I went the watchdog rules route instead. Combining watchdog rules with the Slack API allowed me to create a rule that sends a slack message whenever one of our sites has an smtp error.
> 0 votes

---
Tags: 7, rules, emails, cron, actions
---


# Question
Title: How do I use Drush 8 site aliases in Drush 9?
In Drush 8, my site aliases are loaded correctly from `~/.drush/mysite.aliases.drushrc.php`.

E.g.

```
$aliases['dev'] = array(
  'root' => '/var/www/html/mysite.dev/docroot',
  'uri' => 'mysite.prod.acquia-sites.com',
  'remote-host' => 'mysite.ssh.acquia-sites.com',
  'remote-user' => 'mysite.dev',
  'path-aliases' => array(
    '%drush-script' => 'drush' . $drush_major_version,
  ),
);

```

However these aliases aren't loaded in Drush 9.

```
$ drush site-alias
{  }

```

How I should define site aliases in Drush 9? Is there any migration process?

# Answer
Aliases are now provided in YAML files. According to the example aliases file for Drush 9:

> To convert legacy alias (`*.aliases.drushrc.php`) to yml, run the site:alias-convert command.

So running the command:

```
drush site:alias-convert

```

should do the trick.
> 16 votes

# Answer
Clive's answer is a start, but as TheRealWebGuy notes, there is another step you must take.

I was upgrading from drush 8 to drush 9, and my aliases still did not work after running `drush site:alias-convert`. An additional step that I needed to take for my new alias files to work was to run `drush init`. I ran it in my user home directory; I don't know if that matters.

Hopefully this saves future users some additional clicking and searching.
> 2 votes

---
Tags: drush
---


title: reCaptcha does not display

text:
# Question
Title: reCaptcha does not display
I've installed Captcha and reCaptcha in Drupal 8 because I want to use it on the site contact form. I believe I have all the configuration options set correctly but they are limited. For example, there is no place to tell it what form I want it to appear on.

All modules and core are up to date.

I am logging out to test the form. I know that by default administrators are not presented the reCaptcha.

I'm working with image based reCaptcha v2.

I've looked for a field widget to add to the form but there is nothing. Nor is there anything in the form display settings.

In the old days there was a form list to select from (see screenshots on this question: How do I go about telling Captcha that my form exists? ) but that no longer appears.

The instructions even reference the missing list:

While reCaptha has a stable release for 8, Captcha has only a beta from Feb 2017. So I'm wondering if anyone has this working in 8 at all.

Any suggestions? Further troubleshooting steps I can take?

# Answer
Go to CAPTCHA Points and enable reCaptcha for your form.
> 1 votes

---
Tags: 8, captcha
---


# Question
Title: Customize the output of the Drupal 8 Aggregator module
I am using the Core Aggregator module to aggregate content from RSS feeds, and then using a View to output the content.

The Aggregator module has two view modes, `default` and `summary`. The view modes themselves are editable, but the feed items themselves are grouped into the "items" field, that has no options.

In `default` mode, the title, blog, description etc. for each item are rendered, but in `summary` mode only the title and blog name are rendered.

How can I influence the fields that are rendered in `summary` view mode?

# Answer
> 0 votes
I believe what you are looking for is the 'Manage Display Option" viewable from

admin/config/services/aggregator/display

In other words from the aggregator admin ui.

Not sure how much control this gives you in reality. Also I am having issues with Aggregator appearing to strip out image tags from my feeds for some reason, so I am also considering using the feeds module instead that seems to have better support than the core module.

UPDATE

Ended up using the migrate module which enables custom mapping of fields from a field to a content type of your choosing with custom fields etc.

---
Tags: 8, feeds
---


# Question
Title: How do I tell Drush where the root directory is?
I have successfully installed Drupal 8 with Composer and I also installed Drush with Composer. When I use Drush, it says that the Drupal root is not found. I am passing the root, but it still says that.

How do I tell Drush where the root directory is?

I am using Drush from vendor/drush/drush/drush. I couldn't get vendor/bin/drush to work.

# Answer
> 2 votes
When I run:

```
$ composer create-project drupal-composer/drupal-project:8.x-dev drupal-project-test-site --no-interaction
$ cd drupal-project-test-site
$ vendor/bin/drush status

```

Then I see:

```
 Drupal version : 8.6.13
 Site URI       : http://default
 PHP binary     : /usr/local/Cellar/php/7.3.0/bin/php
 PHP config     : /usr/local/etc/php/7.3/php.ini
 PHP OS         : Darwin
 Drush script   : .../drupal-project-test/drupal-project-test-site/vendo
                  r/drush/drush/drush
 Drush version  : 9.6.0
 Drush temp     : /tmp
 Drush configs  : .../.drush/drush.yml
                  .../drupal-project-test/drupal-project-test-site/vendo
                  r/drush/drush/drush.yml
                  .../drupal-project-test/drupal-project-test-site/drush
                  /drush.yml
 Drupal root    : .../drupal-project-test/drupal-project-test-site/web
 Site path      : sites/default

```

Drush should be able to find the Drupal root for the site that it's contained inside without the use of `--root` or an alias. I'm not sure why `vendor/bin/drush` would not work. Perhaps try again with a new test project, and see whether you get the same results? Perhaps your install did not complete.

---
Tags: drush
---


# Question
Title: How to use custom code to change the node form layout and group fields while maintaining values?
I am trying to alter the node form layout in a form alter hook.

I altered the node form and added a field set in which I grouped couple of existing fields into a fieldset. Then hid the existing fields so that they don't show up twice:in the fieldset and standalone.

However, after changing the structure, the field content are not being saved on submission. I thought this is due to drupal internal validation. So I thought I would use a validation hook to map the new fields structure to their existing (hidden fields). But I am facing couple of issues:

1. can't retrieve the values in the validation function using `$formstate->getValue()`.
2. Changing the structure causing the fields to not be processed correctly.

```
    // Group 2 fields: 1 date field and another text field in custom group
    $form['custom_group'] = [
      '#tree' => TRUE,
      '#type' => 'details',
      '#title' => t('Custom Group'),
      '#weight' => 19,
      '#collapsible' => TRUE,
      'existing_field_1' => $form['existing_field_1'], // is a date field
      'existing_field_2' => $form['existing_field_2'],
    ];
    // Hide the original fields.
    $form['existing_field_1']['#access'] = FALSE;
    $form['existing_field_2']['#access'] = FALSE;

    // Add our validation to try to force the values to be saved:
    $form['#validate'][] = 'my_module_form_node_form_validate';
    // make my validation first but probably unnecessary:
    $form['#validate'] = array_reverse($form['#validate']);

```

And in the validation function:

```
function my_module_form_node_form_validate($form, $form_state) {
  // grab the field values:
  $my_values = $form_state->getValue('custom_group')
}

```

But I cannot access them this way.

After digging into the issue I was able to access the values:

```
    function my_module_form_node_form_validate($form, $form_state) {
      $values = $form_state->getUserInput();
      $form_state->setValue('existing_field_1', $values['custom_group']['existing_field_1'];
    }

```

However issue #2 remains. For example, `->getUserInput();` is returning the raw value of the `existing_field_1` which has type date. And the value is just a raw string instead of the normal DateTime object. So it's failing validation. To clarify `->getUserInput()` returns raw string as expected `01-01-2019` and not valid datetime. So I end up with datetime validation error.

I could do the processing myself but that would be an overkill. So, in short, is it possible to use an alter hook two group fields (date/text/esle) into a field set and let drupal process the values?

# Answer
> 2 votes
$form\_state is an object, not an array. You should be able to get the values like `$my_value = $form_state->getValue('custom_group')`. Or get all values like `$values = $form_state->getValues()`.

See: Introduction to Form API

---
Tags: 8, nodes, forms
---


# Question
Title: How do I set a cookie using $response->headers->setCookie() in a form submission handler?
I read on Deprecate user\_cookie\_save() and user\_cookie\_delete(). that `user_cookie_save()` will be deprecated in Drupal 9 and that we should now use the Symfony's method, as in the following code.

```
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar'));
return $response->send();

```

If I use that code in a submission handler of a custom form, `$response-send()` just returns an empty page, rather than my site. What am I missing here?

# Answer
You can't send a response from custom code in Drupal. You have to return it from a controller.

You can also set a response or add the cookie to an existing response in an event subscriber. In your case set the response in form submit, then Drupal does this for you in a core event subscriber:

```
$form_state->setResponse($response);

```

To avoid the empty page you probably want to fill the response with content or add the cookie to a redirect response to display a different page.

---

**Don't `$response->send()`**

To explain why not to send a response. When you find a code example for the Symfony component HttpFoundation sending a response, it isn't valid for custom code in Drupal. See the warning in this doc:

> This article explains how to use the HttpFoundation features as an independent component in any PHP application. In Symfony applications everything is already configured and ready to use. Read the Controller article to learn about how to use these features when creating controllers.

In addition the Drupal kernel is wrapped in stack middlewares using Stack/Builder. So sending a response can even be a security risk if you have for example installed a middleware providing security checks.
> 5 votes

---
Tags: 8, cookies
---


title: Route Parameter Validation Problem

text:
# Question
Title: Route Parameter Validation Problem
I have limited experience with D8 and custom routes.

Current mobile video system for client takes a scheme-less url for the video like so

https://example.com/mobile-video/some-video-desktop.azureedge.net

The routing has worked fine until we had a vendor change for video hosting and the new URLs include slashes and query strings **which may or may not** be the issue.

mobilevideo.routing.yml looks like

```
mobilevideo.content:
  path: '/mobile-video/{vguid}'
  defaults:
    _controller: 'Drupal\mobilevideo\Controller\MobileVideoController::content'
    _title: 'Mobile Video'
  requirements:
    _permission: 'access content'
    vguid: '^[-a-zA-Z0-9.\/?=]+'

```

Prior to today the validation was just '^\[-a-zA-Z0-9.\]+'

So testing the new URLs I am getting 404s. But if the parameter passed to the mobilevideo.routing.yml fails validation a 404 is the correct response so I assume the issue is validation. https://www.drupal.org/docs/8/api/routing-system/parameters-values-validation-in-routes

So I changed the validation from `vguid: '^[-a-zA-Z0-9.]+'` to `vguid: '^[-a-zA-Z0-9.\/?=]+'` that had no effect and I also tried `'.+'` and also the original without ? and = with no change.

I should note that the original URLs with no slashes worked continously through all of this and that each change was followed by clearing all caches.

Also tried removing validation entirely and that also failed so I am wondering if my path cannot include slashes in the parameter for reasons beyond validation?

What should my next step be in debugging this?

A full example URL will look like

https://example.com/mobile-video/someidhere.cloudfront.net/sessions/forty-characters-or-more-of-vguid-here.mp4?invocationId=thirty-more-chars-here

**UPDATE** Based on info re optional parameters and the comments on this post I added four more parameters and default values of '' for each updating mobilevideo.routing.yml to

```
mobilevideo.content:
  path: '/mobile-video/{vguid}/{vguidtwo}/{vguidhtree}/{vguidfour}/{vguidfive}'
  defaults:
    _controller: 'Drupal\mobilevideo\Controller\MobileVideoController::content'
    _title: 'Mobile Video'
    vguid: ''
    vguidtwo: ''
    vguidthree: ''
    vguidfour: ''
    vguidfive: ''
  requirements:
    _permission: 'access content'
    vguid: '^[-a-zA-Z0-9.]+'
    vguidtwo: '^[-a-zA-Z0-9.]+'
    vguidthree: '^[-a-zA-Z0-9.]+'
    vguidfour: '^[-a-zA-Z0-9.]+'
    vguidfive: '^[-a-zA-Z0-9.]+'

```

Then updated the controller to use `public function content($vguid, $vguidtwo, $vguidthree, $vguidfour, $vguidfive) {` and assemble the URL based on that array.

Attempting to flush the cache gets `The website encountered an unexpected error. Please try again later.`. What did I miss?

# Answer
My solution was to modify the javascript directing traffic to the mobile video page so that it replaced the slashes with triple underscores.

`urlNoProtocol = src.replace(/\//i, "___");`

The validation in mobilevideo.routing.yml was updated to `vguid: '^[-a-zA-Z0-9._?=]+'`

Then in MobileVideoController.php the content() function was updated to reverse the replacement.

`$url = preg_replace('/___/','/', $vguid);`
> 0 votes

---
Tags: 8, routes
---


# Question
Title: Show Targeted Content Based on Content Field and User Roles
I'm looking for a way to show specific targeted content based on a **content type's field** and **user role**.

For example, if user1 has a "Content Group 1" role, then the view should show content pieces with "field\_content\_grouping" == "Content Group 1". User2 having a "Content Group 2" role should only be able to see "Content Group 2" and so on. Both roles & field values are exactly the same.

I'm looking for the best way to properly execute this. I've seen people do similar things with pre-render for views or views query alter hooks. My general line of thinking is:

1. Before rendering views get User roles: Loop and check roles against a specific field "field\_content\_grouping" - if there is a match, continue else unset node from view.
2. Return full results (sans content pieces without a matching field & role).

What's the best way to accomplish something like this? Or am I completely on the wrong track all together? Any and all assistance is greatly appreciated, thanks!

# Answer
You can make your *content field* a *taxonomy term* and you can accomplish this with a simple view without any custom coding.

If we assume

* vocabulary *Departments*
* user has field *Departments*
* some users with *department* selected
* token and views\_argument\_token installed

Add a content view

* Add any relevant filters (content types, etc)
* Add user relationship
* Add contextual filter *Has taxonomy term id*
    + *Provide default value \> token* and fill in the current user's selected term id which in this case is `[current-user:field_department:target_id]`
    + use **Browse available tokens** to find the relevant token

Here is a screenshot of a working view
> 0 votes

---
Tags: views, users
---


# Question
Title: Programmatically delete a webform submission by sid without first loading it
Drupal 8 project has a 2 webforms:

* Webform "ABC"
* Webform "123"

**Explanation of the process:**

When Webform "ABC" is submitted, a new "node" is created and the "Sid" used to create this node is recorded inside a "text" field (field\_submission\_sid) on this created node.

Now, when Webform "123" is loaded, the value of (field\_submission\_sid) is populated inside a 'text' element (submission\_to\_delete)... and when the Webform "123" is submitted, a **custom handler** will delete the submission of **sid value = (submission\_to\_delete)**

The custom handler is working but I believe there is a better solution... so please I need your help ?

**Custom handler:**

```
<?php

namespace Drupal\custom_module\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Delete a 'webform Submission' using its "SID" retrieved from a populated webform submission value.
 *
 * @WebformHandler(
 *   id = "Delete a webform Submission using its sid",
 *   label = @Translation("Delete a webform Submission using its sid"),
 *   category = @Translation("Entity Delete"),
 *   description = @Translation("Delete a webform Submission using its sid retrieved from a populated webform submission valu"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class DeleteSidWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Load 'submission' object from webform-submission populated data.
    //get (SID) from (submission_to_delete) text element available on the webform
    $sid = $values["submission_to_delete"];
    $webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);

    //Delete the Submission
    $webform_submission->delete();
 }
}

```

**If you notice, I am loading the submission first then i am deleting it...**

is there a better solution where I can delete the submission directly without first have to load it ? maybe something like `$webform_submission = \Drupal\webform\Entity\WebformSubmission::delete(submission_to_delete);`

**UPDATE:**

I noticed if the 'webform submission' is not available (Ex: An admin deleted by mistake) so the value of `$sid` will be `NULL` and the below error is generated:

```
Error: Call to a member function delete() on null in Drupal\custom_module\Plugin\WebformHandler\DeleteSidWebformHandler->submitForm()

```

How to add an **if statement** to check if **$sid value is empty** then do nothing otherwise **execute code**.

Thank you,

# Answer
You always need to load before delete, there is no "better" solution.

> I am affraid from affecting the performance of the website since the above handler will be executed a lot

Loading one entity at a time is no performance issue whatsoever.

```
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);
// Check if submission is returned.
if (!empty($webform_submission)) {
  //Delete the Submission
  $webform_submission->delete();
}

```
> 3 votes

---
Tags: 8, webforms
---


# Question
Title: How do I fetch a vote given on a node and programmatically apply this vote to the author of the node?
I am using the voting api, fivestar and rules modules to try to fetch the vote a user gave to a node (article) and apply that same vote/value to a fivestar field of the author of that node. How can I accomplish this?

```
{ "rules_cast_a_vote_when_the_author_casts_a_vote_on_their_article" : {
"LABEL" : "Cast a vote when the author casts a vote on their article",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "cast", "fivestar", "vote" ],
"REQUIRES" : [ "rules", "rules_conditional", "voting_rules" ],
"ON" : { "voting_rules_insert_node" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "article" : "article" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_my_fivestar_rating" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_the_editor" } }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : { "type" : "user", "id" : [ "node:field-the-editor:uid" ] },
      "PROVIDE" : { "entity_fetched" : { "editor_uid_fetched" : "Fetched editor uid" } }
    }
  },
  { "CONDITIONAL" : [
      {
        "IF" : { "entity_has_field" : {
            "entity" : [ "editor-uid-fetched" ],
            "field" : "field_my_fivestar_rating"
          }
        },
        "DO" : [
          { "drupal_message" : { "message" : "When conditional is TRUE: [editor-uid-fetched:name]\u0027s ID has been fetched and is: [editor-uid-fetched:uid]" } },
          { "data_set" : {
              "data" : [ "editor-uid-fetched:field-my-fivestar-rating" ],
              "value" : [ "node:field-my-fivestar-rating" ]
            }
          }
        ]
      }
    ]
  },
  { "drupal_message" : { "message" : "vote:value [vote:value]\u003Cbr\u003E\r\nnode author fetched ID: [node-author-fetched:uid]\u003Cbr\u003E\r\nnode author fetched name: [node-author-fetched:name]\u003Cbr\u003E\r\neditor rating now: [editor-uid-fetched:field_cr_rating]\u003Cbr\u003E\r\neditor rating value now: [editor-uid-fetched:field_cr_rating:value]\u003Cbr\u003E\r\neditor rating now (hyphens): [editor-uid-fetched:field-cr-rating]\u003Cbr\u003E\r\neditor rating value now (hyphens): [editor-uid-fetched:field-cr-rating:value]\u003Cbr\u003E\r\n\r\n" } }
]

```

} }

# Answer
> 0 votes
I undesrtand that your question is about a 'code' solution, this one is not but it works, you'll need rules conditional module, and voting rules module , it adds an action: 'a node has been rated', then fecth node-author-by-id, make shure both have the same field (user-bundle and contentype), set user-author-rating-field-value with your node-rating-field-value, or import rule, please edit your field-rating machine name and dependencies as needed. i hope it helps.

```
    { "rules_set_node_five_star_rate_to_node_author" : {
    "LABEL" : "set node five-star rate to node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "RATING_MODULE_MACHINE_NAME" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_YOUR_FIVE_STAR_FIELD" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "node:author:uid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched_author_by_id" : "author_by_id" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_has_field" : {
                "entity" : [ "entity-fetched-author-by-id" ],
                "field" : "field_YOUR_FIVE_STAR_FIELD"
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "entity-fetched-author-by-id:field_YOUR_FIVE_STAR_FIELD" ],
                  "value" : [ "node:field_YOUR_FIVE_STAR_FIELD" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

```

---
Tags: 7, rules, rating
---


# Question
Title: The way to join the entity to itself and use joined fields in UI
I have a list of locations and want to make a view of routes between them. In classical sql the query will be:

```
SELECT src.name, dst.name FROM locations src LEFT JOIN locations вые ON src.name!=dst.name

```

I made hook\_views\_pre\_execute:

```
function bd_create_views_pre_execute(\Drupal\views\ViewExecutable $view) {
  if ($view->id() == 'ways' && $view->current_display == 'list') {
    $input = $view->exposed_raw_input;
    $query = $view->build_info['query'];
    $query->leftJoin('taxonomy_term_field_data', 'joj', 'taxonomy_term_field_data.tid != joj.tid');
    $query->addField('joj', 'name', 'label1');
    $view->build_info['query'] = $query;
    $view->build_info['count_query'] = $query;
  }
}

```

What is the way to bring **label1** to views admin interface?

Or is there another way to join using only admin interface?

# Answer
> 0 votes
You'll need to change your starting approach; `hook_views_pre_execute()` is for modifying a View prior to execution, not for providing new table data to integrate into Views. You won't be able to plugin into the UI from this hook.

If you're wanting to plugin into D8 Views system so that it can be seen by the Views admin UI, you'll need to implement various plugins that the D8 Views modules will use to look up your table data, fields (columns) & relationships (joins) that Views can use to build queries on your data table.

Start by following tutorial examples like *Building Views Query Plugins for Drupal 8* or by looking at a well-known module with Views integration (e.g. `node`, `user`) to understand & implement the various plugins that provide Views integration.

---
Tags: views, 8
---


# Question
Title: Custom Save and Unpublished button for node
While clicking `Save as draft` button, it will save the node but while it have to redirect to the created node it gives error `The website encountered an unexpected error. Please try again later.` and `$entity->setPublished(FALSE);` is also not working.

```
function MYMODULE_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit_unpublish'] = array(
    '#type' => 'submit',
    '#weight' => '-10',
    '#value' => t('Save as draft'),
    '#submit' => array_merge($form['actions']['submit']['#submit'],
    ['MYMODULE_draft_submit_callback']),
  );
}

function MYMODULE_draft_submit_callback(array &$form, FormStateInterface &$form_state) {
    $entity = $form_state->getFormObject()->getEntity();
    $entity->set('moderation_state', 'submitted');
    $entity->setPublished(FALSE);
    $entity->save();
}

```

# Answer
You can't use

```
 $entity->set('moderation_state', 'submitted');

```

if you don't have *Content Moderation* core module enabled

Also make sure you declare the usage of *FormStateInterface* somewhere in your *.module* file

```
use Drupal\Core\Form\FormStateInterface;

```

Also look in your error logs found in *admin/reports/dblog* for other possible errors
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to style a custom theme setting form
I have a set of custom theme settings defined in my theme.

They are fully integrated into my theme and appear on the theme's setting page but they are not styled. I use the seven admin theme.

I would like to style the forms on the admin pages; similarly to how other core modules like color, logo etc are styled.

How does one go about this?

Ideally, I would group my settings, place them in a div and give the entire group a title and help.

# Answer
Basically it's just these two steps:

1. Define a library from `MYMODULE.libraries.yml`.
2. Attach the library to your form.

---

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

> ### Attaching a library to a form
>
> As forms are just render arrays, attaching a library works just the same:
>
> ```
> /**
>  * Implements hook_form_alter().
>  */
> function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
>   /* @var Drupal\Core\Entity\FieldableEntityInterface $entity */
>   $formObject = $form_state->getFormObject();
>   if ($formObject instanceof \Drupal\Core\Entity\EntityFormInterface) {
>     $entity = $formObject->getEntity();
>     if (
>       $entity->getEntityTypeId() === 'node'
>       && in_array($entity->bundle(), ['organisation', 'location', 'event', 'article'])
>     ) {
>       $form['#attached']['library'][] = 'yourmodule/yourlibrary';
>     }
>   }
> }
>
> ```

---

To add additional wrapper divs around some single or multiple form elements you can nest them into containers or fieldsets. For example:

> ### class Container
>
> Provides a render element that wraps child elements in a container.
>
> Surrounds child elements with a and adds attributes such as classes or an HTML ID.
>
> Usage example:
>
> ```
> $form['needs_accommodation'] = array(
>   '#type' => 'checkbox',
>   '#title' => $this
>     ->t('Need Special Accommodations?'),
> );
> $form['accommodation'] = array(
>   '#type' => 'container',
>   '#attributes' => array(
>     'class' => 'accommodation',
>   ),
>   '#states' => array(
>     'invisible' => array(
>       'input[name="needs_accommodation"]' => array(
>         'checked' => FALSE,
>       ),
>     ),
>   ),
> );
> $form['accommodation']['diet'] = array(
>   '#type' => 'textfield',
>   '#title' => $this
>     ->t('Dietary Restrictions'),
> );
>
> ```

The D7 Form API Reference still is the most useful resource for that. Though you might want to check for changes on the D8 equivalent: Form and render elements.
> 2 votes

---
Tags: 8, theming, forms
---


# Question
Title: How do I debug incorrect favicon showing on the front page in a custom theme?
I'm working on a Drupal 8 site with a custom theme that I didn't code. The site is using the metatag: favicons module to control the favicons. The favicon seem to work correct on all except the home page, which has the default Drupal "Drop" icon. You can see the site here \[Site no fav\]\[1\]. I am not sure how to begin debugging this since the behavior is not causing an error and the favicons work on the rest of the pages. I assume this has to be some sort of misconfiguration, somewhere, but I'm not sure if I should be looking in template files, something in the admin UI, or where exactly. Any help/guidance appreciated.

Update: The issue is not a local cache issue, as it was brought to our attention by an external user and happens in Firefox and Chrome.

Update2: Closer inspection of the page source shows that the links for the favicons are indeed not loaded onto the homepage. Specifying a favicon in the Metatag UI for the front page loads one of the favicons. However, the favicons do not have global settings and are still loaded into every other page. The fix of course, is to specify all the icons I want, but this is tedious and doesn't answer why it works on the non-homepage pages.

# Answer
In the metatag module the front page has it's own settings. I'm guessing you edited the "Global" settings. But you'll also see a "FRONT PAGE" under the /admin/config/search/metatag admin screen and the front page will be using those settings and not the global ones because the front page has its own set of settings
> 1 votes

---
Tags: 8, debugging
---


# Question
Title: How do I output the link to the content?
In a view, I've got a field set up to output the link to the content.

I'm not sure how to reference it in my views-view-fields.html.twig file. I'm referencing all of the other fields values properly as they all work, but that main anchor link just isn't coming out. What is the proper syntax?

```
 <a href="{{ fields.link_to_content.value }} "><!--start smallbox link-->
 <div style="background-color:grey" class="smallestboxes"><!--start small box 2::::image 1st then text-->
 <div class="container"><!--start container-->
 <div class="content"><!--start content div-->
 <div class="content-overlay" id="clienthover"></div>
 {{ fields.uri.content }}
 <div class="content-details fadeIn-bottom" id="worktext"><!--start fade in-->
 <h1>{{fields.field_work_page_tagline.content}}</h1>
 <p>{{fields.title.content}}</p>
 </div><!--end fade in-->
 </div><!--end content div-->
 </div><!--end container-->
 </div><!--end smallest box 2--></a>

```

# Answer
> 1 votes
`{{ fields.view_node.content }}` displays the value of *Content: Link to Content* view field.
It works for me when I use that line in the *views-view-fields.html.twig* template file.

---
Tags: views, theming
---


# Question
Title: How to add "#main-content" to the link of pager element?
I would like to add `#main-content` to the link of pager element. So, I would get an url like this: http://domain.com/my-views-list?page=2#main-content

Any idea, are there any preprocesses or something like that?

# Answer
You can use template\_preprocess\_pager to alter the pager links. You should be able to do something like the following for whatever links within the pager you want to change:

```
function MYTHEME_preprocess_pager(&$variables) {
  if (some check to make sure its the pager you want){
    $cur = $variables['items']['next']['href'];
    $variables['items']['next']['href'] =  $cur . '#main-content';
  }
}

```
> 2 votes

---
Tags: views, 8
---


# Question
Title: How to remove the click event on an Ajaxified form's submit buttons?
I've created several forms with Drupal 8 directly in admin or with Form API. I've added some client side validation with this jQuery plugin : jQuery Validation Plugin.

Everything works very well. Now my client asked me to open one of these form in a popin. So I've installed this 2 modules : Contact Block (The Contact Block module provides contact forms in a block.) https://www.drupal.org/project/contact\_block

I can open form in a popin and it works well but after validation, the page is reloaded and it is not UX friendly since we are in a popin. So I've installed this module : Contact ajax (implements ajax submission for core Contact form in Drupal 8.) https://www.drupal.org/project/contact\_ajax

It works well but the submission is done before I can execute client side validation.

The problem seems to be the priority of execution.

I've tried to apply `preventDefault` on the submit button but it doesn't work.

```
$( "#form #submit-button" ).click(function( event ) {
  event.preventDefault();
  //validation code
});

```

I've found this topic but I donc know how to implement the code : How to prevent an Ajax form from submitting

I've also found this topic : https://www.drupal.org/project/clientside\_validation

Can you help me to understand how I can block the click event on an Ajaxified form's submit buttons ?

**EDIT**

I've tried this module : Clientside Validation and apply this patch 2952233-5.patch

It works, the Ajax submit button is disabled. The solution is based on that answer.

For now it has a bug : the form is validated but I don't see the confirmation message at the end.

Then, I've copied the code from this patch in my project and it works.

# Answer
> 1 votes
```
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    $( "#form #submit-button" ).click(function( event ) {
      event.preventDefault();
    });
  }
};

```

Can you try like this. This will trigger for every AJAX call.

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


# Question
Title: How to load jQuery UI after bootstrap js files?
I'm a newbie to drupal 7, And I'm facing a conflict between `jquery.ui.button.js` and `bootstrap/button.js` because jquery ui is loaded before bootstrap. How can I change the order and load jquery ui last?

Knowing that bootstrap files are loaded by the theme, and jQuery UI is loaded by the module (jquery\_update)

# Answer
There are a couple of ways in Drupal 7 to control load/execution order. The simplest is to change the module weight in the system table to get the right order. Unfortunately, this will not work in this case since there is a module and theme involved. Themes always get executed after modules (so UI changes are ensured to happen and not be overwritten).

This means you will probably have to write some code in order to modify the load order. In your \[theme.module\] file, you will need to implement the Drupal hook: hook\_js\_alter. E.g. add a `function my_theme_js_alter(&$javascript)` to the theme module file.

You will probably need to install devel and use dpm to dump the javascript array. You can then use this information to rearrange the load order as you need it. Probably just unset the jquery\_ui entry and add it to the array at the bottom.
> 0 votes

---
Tags: javascript, bootstrap-theme
---


title: Custom edit Panel/Tab for content type

text:
# Question
Title: Custom edit Panel/Tab for content type
In Drupal 8 I have a custom content type, and I want to add a group of fields to it that are related to tracking. Since these fields don't have to do with the content displayed, I wanted to separate these options in the UI by having them on a different tab or panel.

This is an example of what I have in mind.

What is the best way to accomplish this? Is there some hook to achieve this?

I have done a lot of searching, but I can't find anything relevant.

# Answer
> 1 votes
Field Group is a module that provides this functionality. https://www.drupal.org/project/field\_group

---
Tags: nodes
---


title: Output image src via JSON

text:
# Question
Title: Output image src via JSON
I have worked out how to use dynamic routing and `JsonResponse()` in a custom controller to output pure JSON, with no HTML at all. I would like to do the same with an image — for the page to output an image header and the image itself to the browser, with no HTML, as though the address were simply a file path to an image.

Is this possible?

# Answer
> 1 votes
Something like the following could help you.

Just Set `$filepath` and `$filename` with your desired values.

```
$filepath = "/path/to/my/image/chart.png";
$filename = "chart.png";

$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($filepath));

return $response;

```

# Answer
> 0 votes
I suspect the reason my original approach failed was a typo, or something similarly trivial, and being such a Drupal noob I assumed an entirely different kind of error. @Yusuf's answer is neater by far than what I ended up with, but doesn't work for me for reasons I explain in a comment. Here is what I had to do — less elegant, but also more universal: $im is passed to the controller in the URL:

```
    $impath.='http://<IMAGE DOMAIN HERE>/media/'.$im;
    $ext = pathinfo( $im, PATHINFO_EXTENSION );

    switch( strtolower($ext) ){
        case 'jpeg':
        case 'jpg':
            $im = imagecreatefromjpeg( $impath );
            if ( $im ){
                header('Content-Type: image/jpeg');
                imagejpeg( $im );
                imagedestroy( $im );
            } else {
                echo '<p>'.basename(__FILE__).'#'.__LINE__.'<br />$impath = '.$impath.'<br />$ext = '.$ext.'</p>';
            }
            break;
        case 'png':
            $im = imagecreatefrompng( $impath );
            if ( $im ){
                header('Content-Type: image/png');
                imagepng( $im );
                imagedestroy( $im );
            } else {
                echo '<p>'.basename(__FILE__).'#'.__LINE__.'<br />$impath = '.$impath.'<br />$ext = '.$ext.'</p>';
            }
            break;
        case 'gif':
            $im = imagecreatefromgif( $impath );
            if ( $im ){
                header('Content-Type: image/gif');
                imagegif( $im );
                imagedestroy( $im );
            } else {
                echo '<p>'.basename(__FILE__).'#'.__LINE__.'<br />$impath = '.$impath.'<br />$ext = '.$ext.'</p>';
            }
            break;
        default:
            echo '<p>'.basename(__FILE__).'#'.__LINE__.'<br />$impath = '.$impath.'<br />$ext = '.$ext.'</p>';
            break;
    }

    exit;

```

I'm not sure what to do about accepting an answer — I suspect I shouldn't accept @Yusuf's since it didn't actually solve my problem and consequently I haven't seen it work.

---
Tags: 8, media
---


# Question
Title: Is it possible to show password reset email success in user password page?
I am completely exhausted trying to find out a solution for this simple problem.

I am intending to put a "Forgot Password" in my Drupal site and wants a confirmation when the form emails the password to the user.

For instance, I go to this link http://www.some.com/user/password for the "Forgot Password" link.

when I enter the username or password, it just doesn't show anything and just redirects to the homepage. I intend to change that and want to show the confirmation that an email has been successfully sent.

Any idea how I can do this?

## What I tried

I tried creating a page--user--password.tpl.php but it doesn't allow me to make any changes. I am not sure where the values are coming in the form.

# Answer
By default, drupal\_set\_message() is set and displayed on form submission when a new password is emailed. It's possible LoginToboggan is interfering with this but I haven't encountered that in my use of it.

Alternatively, if you cannot resolve the issue, you can use hook\_form\_alter() to create your own submission handler on the password reset form, and use drupal\_set\_message() to re-show the message (or any custom message you provide) on the form.

```
function MYMODULE_password_reset_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'my_custom_handler';
}

function my_custom_handler($form, &$form_state) {
  drupal_set_message('An email has been sent with instructions to reset your password.');

}

```
> 1 votes

# Answer
There's definetly a module or something acting with the login behavior.

On a brand new Drupal 7 install, if you use the reset link on /user/passsword, it redirects to /user and show the following system message : Further instructions have been sent to your e-mail address.

You'll need to desactivate modules which could interfere and check for other things like Rules or whatever.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Template suggestions periodically not being recognized
I have some simple template suggestions setup in my `THEME_preprocess_node()` function. Example:

```
function my_theme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'MY_TYPE' && $vars['view_mode'] == 'MY_VIEW_MODE') {
    $vars['theme_hook_suggestions'][] = 'my__template';
  }
}

```

Then I have the template file (named `my--template.tpl.php`) setup in my theme. I cleared the cache, and this is recognized right away and works fine.

Then, after about an hour, if I refresh the page that uses the template, it suddenly is not recognized anymore. I clear cache again and it comes back.

Has anyone experienced this before?

Just FYI, I am using `hook_theme()` in a custom module to specify the theme for this page based on the URL alias.

# Answer
> 0 votes
Turns out I had the wrong hook specified. I copied this from another theme and forgot to update the hook prefix. So I had:

```
other_theme_preprocess_node

```

instead of:

```
my_theme_preprocess_node

```

Changing that seems to have resolved the issue.

---
Tags: 7, theming, theme-negotiation
---