# Question
Title: Symfony\Component\HttpFoundation\Response is never cached
My custom controller is returning data but it is never being cached.

My controller function:

```
use Symfony\Component\HttpFoundation\Response;

 $build = [
            '#theme' => 'search_form_suggest',
            '#nodes' => $nodes,
            '#term' => $term,
            '#type' => $type,
            '#cache' => [
                'keys' => [
                    'sg_search_term_suggestions_' . $term . "_". $type
                ],
                'tags' => [
                    'sg_search_term_suggestions_' . $term . "_". $type
                ],
                'contexts' => ['route']
            ],
        ];

$response = new Response($content);
return $response;
//retrun $build; //this does serve from CACHE

```

Looks like it never ends up hitting the cache mechanism. When I `return $build` then it does serve from cache.

# Answer
> 4 votes
Return a cacheable response. For example

```
use Drupal\Core\Cache\CacheableResponse;
use Drupal\user\Entity\User;

  /**
   * A route returning a CacheableResponse object.
   *
   * @return \Drupal\Core\Cache\CacheableResponseInterface
   *   A CacheableResponseInterface object.
   */
  public function cacheableResponse() {
    $user = User::load(1);
    $response = new CacheableResponse($user->label());
    $response->addCacheableDependency($user);
    return $response;
  }

```

From `Drupal\dynamic_page_cache_test\DynamicPageCacheTestController`.

There are multiple ways to add cache data to the response object additional to the one used in the example.

You can use addCacheTags()/addCacheContexts():

```
$response->getCacheableMetadata()->addCacheTags($tags);
$response->getCacheableMetadata()->addCacheContexts(['route']);

```

The route cache context is by the way not necessary in a controller because it depends already on the route.

Or add cacheable metadata contained in a render array

```
use Drupal\Core\Cache\CacheableMetadata;

$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));

```

See also How to handle cache metadata in a cacheable response? and How to get cache metadata from nested render array when returning response?

---
Tags: caching
---


# Question
Title: How to alter an existing breadcrumb link programmatically?
I am trying to alter the 'Home' Breadcrumb link using

`hook_system_breadcrumb_alter()`

The default Breadcrumb class allows you to add New links using the

`addLinks`

method.

However it does not allow one to edit the links. Is there a way to edit an existing link directly?

# Answer
Turns outs you can't edit the existing breadcrumbs. However you can fetch them using the getter function, modify them and then call the Breadcrumb builder class.

```
<?php
/**
 * Implements hook_system_breadcrumb_alter().
 */
function MODULE_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // Add new link
  $breadcrumb->addLink($link);
  // Saving the original links and caching
  $original_links = $breadcrumb->getLinks();
  $cacheability = CacheableMetadata::createFromObject($breadcrumb);
  // Remove the old value of the array.
  array_shift($original_links);
  $home_link = array_pop($original_links);
  array_unshift($original_links, $home_link);
  // Finally generating the new link.
  $breadcrumb = new Breadcrumb();
  $breadcrumb->setLinks($original_links);
  $breadcrumb->addCacheableDependency($cacheability);
}

```
> 2 votes

---
Tags: 8, breadcrumbs
---


title: Total of multiple computed elements

text:
# Question
Title: Total of multiple computed elements
I am trying to create a quote form where I can add two computed twig elements together to give a total of the two. I have created the two computed elements to give a total based on the user inputs but when I then create the third computed element it doesn't add the two together. It just gives me a value of two. Below is the export of the Webform. What am I doing wrong please or am I going about this wrong? Any help to resolve this would be greatly appreciated :)

Drupal version 8.9.13 - Webform Version: 6.0.2

```
uuid: b6d7a837-6396-4fe5-af62-9a15bbf50cb2
langcode: en
status: open
dependencies: {  }
open: null
close: null
weight: 0
uid: 1
template: false
archive: false
id: quote_builder
title: 'Quote builder'
description: ''
category: ''
elements: |
  how_many_sockets_:
    '#type': textfield
    '#title': 'How many sockets?'
  cost_per_socket:
    '#type': hidden
    '#title': 'Cost per socket'
    '#default_value': '45'
    '#prepopulate': true
  total_cost_of_sockets:
    '#type': webform_computed_twig
    '#title': 'Total cost of sockets'
    '#display_on': view
    '#template': '{{( data.how_many_sockets_ * data.cost_per_socket )}}'
    '#store': true
  how_many_light_fittings_including_down_lights_:
    '#type': textfield
    '#title': 'How many light fittings? (including down lights)'
  cost_per_light_fitting:
    '#type': hidden
    '#title': 'cost per light fitting'
    '#default_value': '35'
    '#prepopulate': true
  total_cost_of_light_fittings:
    '#type': webform_computed_twig
    '#title': 'total cost of light fittings'
    '#display_on': view
    '#template': '{{( data.how_many_light_fittings_including_down_lights_ * data.cost_per_light_fitting )}}'
    '#store': true
  total_cost_of_sockets_and_light_fittings:
    '#type': webform_computed_twig
    '#title': 'Total cost of sockets and light fittings'
    '#template': '{{( data.total_cost_of_sockets + data.total_cost_of_light_fittings )}}'
    '#store': true
    '#ajax': true
css: ''
javascript: ''
settings:
  ajax: false
  ajax_scroll_top: form
  ajax_progress_type: ''
  ajax_effect: ''
  ajax_speed: null
  page: true
  page_submit_path: ''
  page_confirm_path: ''
  page_theme_name: ''
  form_title: both
  form_submit_once: false
  form_exception_message: ''
  form_open_message: ''
  form_close_message: ''
  form_previous_submissions: true
  form_confidential: false
  form_confidential_message: ''
  form_disable_remote_addr: false
  form_convert_anonymous: false
  form_prepopulate: false
  form_prepopulate_source_entity: false
  form_prepopulate_source_entity_required: false
  form_prepopulate_source_entity_type: ''
  form_reset: false
  form_disable_autocomplete: false
  form_novalidate: false
  form_disable_inline_errors: false
  form_required: false
  form_unsaved: false
  form_disable_back: false
  form_submit_back: false
  form_autofocus: false
  form_details_toggle: false
  form_access_denied: default
  form_access_denied_title: ''
  form_access_denied_message: ''
  form_access_denied_attributes: {  }
  form_file_limit: ''
  share: false
  share_node: false
  share_theme_name: ''
  share_title: true
  share_page_body_attributes: {  }
  submission_label: ''
  submission_log: false
  submission_views: {  }
  submission_views_replace: {  }
  submission_user_columns: {  }
  submission_user_duplicate: false
  submission_access_denied: default
  submission_access_denied_title: ''
  submission_access_denied_message: ''
  submission_access_denied_attributes: {  }
  submission_exception_message: ''
  submission_locked_message: ''
  submission_excluded_elements: {  }
  submission_exclude_empty: false
  submission_exclude_empty_checkbox: false
  previous_submission_message: ''
  previous_submissions_message: ''
  autofill: false
  autofill_message: ''
  autofill_excluded_elements: {  }
  wizard_progress_bar: true
  wizard_progress_pages: false
  wizard_progress_percentage: false
  wizard_progress_link: false
  wizard_progress_states: false
  wizard_auto_forward: true
  wizard_auto_forward_hide_next_button: false
  wizard_keyboard: true
  wizard_start_label: ''
  wizard_preview_link: false
  wizard_confirmation: true
  wizard_confirmation_label: ''
  wizard_track: ''
  wizard_prev_button_label: ''
  wizard_next_button_label: ''
  wizard_toggle: false
  wizard_toggle_show_label: ''
  wizard_toggle_hide_label: ''
  preview: 0
  preview_label: ''
  preview_title: ''
  preview_message: ''
  preview_attributes: {  }
  preview_excluded_elements: {  }
  preview_exclude_empty: true
  preview_exclude_empty_checkbox: false
  draft: none
  draft_multiple: false
  draft_auto_save: false
  draft_saved_message: ''
  draft_loaded_message: ''
  draft_pending_single_message: ''
  draft_pending_multiple_message: ''
  confirmation_type: page
  confirmation_title: ''
  confirmation_message: ''
  confirmation_url: ''
  confirmation_attributes: {  }
  confirmation_back: true
  confirmation_back_label: ''
  confirmation_back_attributes: {  }
  confirmation_exclude_query: false
  confirmation_exclude_token: false
  confirmation_update: false
  limit_total: null
  limit_total_interval: null
  limit_total_message: ''
  limit_total_unique: false
  limit_user: null
  limit_user_interval: null
  limit_user_message: ''
  limit_user_unique: false
  entity_limit_total: null
  entity_limit_total_interval: null
  entity_limit_user: null
  entity_limit_user_interval: null
  purge: none
  purge_days: null
  results_disabled: false
  results_disabled_ignore: false
  results_customize: false
  token_view: false
  token_update: false
  token_delete: false
  serial_disabled: false
access:
  create:
    roles:
      - anonymous
      - authenticated
    users: {  }
    permissions: {  }
  view_any:
    roles: {  }
    users: {  }
    permissions: {  }
  update_any:
    roles: {  }
    users: {  }
    permissions: {  }
  delete_any:
    roles: {  }
    users: {  }
    permissions: {  }
  purge_any:
    roles: {  }
    users: {  }
    permissions: {  }
  view_own:
    roles: {  }
    users: {  }
    permissions: {  }
  update_own:
    roles: {  }
    users: {  }
    permissions: {  }
  delete_own:
    roles: {  }
    users: {  }
    permissions: {  }
  administer:
    roles: {  }
    users: {  }
    permissions: {  }
  test:
    roles: {  }
    users: {  }
    permissions: {  }
  configuration:
    roles: {  }
    users: {  }
    permissions: {  }
handlers: {  }
variants: {  }

```

# Answer
> 2 votes
Unfortunately, computations cannot draw values from other computed elements. You always have to go back to the original elements.

Here is the working Twig code for the “Total cost of sockets and light fittings“ element:

```
{{
  data.how_many_sockets_ * data.cost_per_socket +
  data.how_many_light_fittings_including_down_lights_ * data.cost_per_light_fitting
}}

```

---
Tags: webforms
---


# Question
Title: Webform Custom element option values validate
Can anyone please suggest how to validate the custom element option values ( select). This validate should work, once we add new element to the form and fill the option value and then click save / save and add element.

# Answer
due to explaining in comment i am thinking you are making a custom Plugin\WebformElement;

aka namespace Drupal\YOURMODULE\Plugin\WebformElement; use Drupal\webform\Plugin\WebformElementBase; ... if this is the case look at this example ( '#element\_validate' =\> \[\[get\_class($this), 'validateOptions'\]\] )

```
 public function form(array $form, FormStateInterface $form_state) {
  $form = parent::form($form, $form_state);
  $form['general']['mycustom'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('mycustom Settings'),
  ];

  $form['general']['mycustom']['some_question_text'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Some Question title '),
    '#required' => TRUE,
    '#default_value' => $this->getDefaultProperty('hello'),
    '#element_validate' => [[get_class($this), 'validateOptions']], //HERE <----
  ];

```

........ later on in the same class ... .......

```
 /**
  * Example validate
  */
 public static function validateOptions(array &$element, FormStateInterface $form_state) {
   $name = $element['#name'];
   // EG ... $options = $element['#options']
   $form_state->setErrorByName($name, t('@m', ['@m' => 'HELLO']));
 }

```
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Exract all node field values to json including reference entities with value
I am writing a module to export drupal's content to another platform, the module provides a UI to manage content types and their fields to be shared on another platform via API.

So far i have managed to get node field values using this sample code

```
$nid = 4951;
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$data = [];
foreach ($node->getFields() as $name => $field) {
  $data[$name]  = $field->getString();
}

```

the `$field->getString();` however do not provides reference entity values and only provide ids.

The out of the above code is like:

```
{"nid":"4951","uuid":"0fae7e9b-d860-43f0-9559-a8bd6bab22b7","vid":"1272611","langcode":"en","type":"article","revision_timestamp":"1612303794","revision_uid":"1166","revision_log":"","status":"1","uid":"866","title":"xyz Chapter April Update","created":"1555961981","changed":"1612303794","promote":"0","sticky":"0","default_langcode":"1","revision_default":"1","revision_translation_affected":"1","moderation_state":"published","scheduled_transition_date":"","scheduled_transition_state":"","metatag":"","path":"\/wisconsin-chapter-april-update, 17276, en","menu_link":"","body":"some this here, rich_text","field_article_author":"Wisconsin Chapter","field_article_chapter":"541","field_article_endnotes":"","field_article_questions_cta":"1","field_article_recommendation":"","field_article_recommended_link":"","field_article_related":"","field_article_related_link":"","field_article_resource_download":"","field_article_subhead":"Here's the latest news from the abc.","field_article_thumbnail":"","field_article_type":"news","field_blog_section":"","field_meta_tags":"","field_tax_article_type":"24, 28, 45","field_tax_audience":"","field_tax_breadcrumbs":"","field_tax_content_format":"50","field_tax_disease":"55, 56, 57, 58","field_tax_ga_type":"","field_tax_research_type":"","field_tax_topic":"90, 91, 92, 93, 94, 108, 109, 111"}

```

Scroll last and see for example `field_tax_topic`

Is there a direct or indirect way of automatically detecting reference entity field and extracting its values, also it should be dynamic solution and that must work with new field types as well.

Any pointer or direction to do it in the right way will help!

# Answer
> 0 votes
If you really really want to do this which you probably wont with JSON API Views and serialisation

https://www.drupal.org/docs/8/api/serialization-api/serialization-api-overview

eg:

```
dump(Drupal::service('serializer')->serializer->serialize($entity, 'json'));

```

But if you really want to ...

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$data = [];
foreach ($node->getFields() as $name => $field) {
   // Get Type.
   $field_type = $node->get($name)->getFieldDefinition()->getType();
   //see https://drupal.stackexchange.com/questions/180373/how-to-get-the-list-of-field-types

   switch($field_type) {
      case 'text_with_summary':
      case 'text':
      case 'text_long:
        $data[$name]  = $field->getString();
        break;
      case 'entity_reference':
      case 'entity_reference':
        $value = [];
        $items = $field->referencedEntities();
        if (!empty($items)) {
            foreach ($items as $item) {
                // here is the crappy part
                $val_1 = $item->get('field_something')->value;
                $value[$item->id()] =  $val_1,
            }
        }
        $data[$name] = $value;
      break;
      // continue for other data types
      // and set a default !
   }
}

```

---
Tags: entities, search, importing-exporting
---


title: Views Json Source data Cached

text:
# Question
Title: Views Json Source data Cached
I'm using the Views Json Source module to load information from a Views Rest Export page on an other website into another website.

But for some reason the view is stuck with old information. I'm pulling in a calendar from the source site. But even though the data from the source site is changing the data in the other site is not.

To solve this I disabled cache for both views but without success When clearing cache on the source site and then the other site the data is changed.

What can I do to make the view look at the rest export on every load of the block?

# Answer
To fix this I uninstalled the module and created my own javascript function. Here I had the same problem. Making me realize the problem was caching in some form. The answer to the question was simply adding a query of the current date to the url.

For more informatie: Views rest export does not update
> 0 votes

---
Tags: 8, views
---


title: Save entity without validation

text:
# Question
Title: Save entity without validation
While adding a new submit button to the form

```
$form['actions']['save_as_draft'] = [
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ['::submitForm', '::save', 'save_as_draft'],
  '#validate' => [],
  '#limit_validation_errors' => []
];
$form['#validate'] = [['validate_errors']];

```

This does not save the entity. I am not sure how to edit the following validate function.

```
function validate_errors(&$form,FormStateInterface $form_state) {
  if ($form_state->getTriggeringElement()['#value'] == t('Save as Draft')) {
    // Skip validation.
  }else {
    // Validate here.
  }
}

```

Meanwhile, I got the error when saving (Entity validation was skipped):

Any inputs on how I can fix this and allow the entity to be saved without validation?

# Answer
I had the same problem. Instead of "#limit\_validation\_error", adding validation handler which simply omits all the error works fine.

```
function my_module_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['save_as_draft'] = [
    '#type' => 'submit',
    '#value' => t('Save as Draft'),
    '#submit' => ['::submitForm', '::save',],
    '#validate' => ['_my_module_clear_errors'],
  ];

  // Add this to avoid 'Entity validation was skipped' error.
  $form_state->setTemporaryValue('entity_validated', TRUE);
}

// Remove all errors.
function _my_module_clear_errors(&$form,FormStateInterface $form_state) {
  $form_state->clearErrors();
}

```

This comment was really helpful

https://www.drupal.org/project/workflow/issues/2859053#comment-12140370
> 1 votes

---
Tags: 8, forms
---


title: Links on site adding index.php in URL

text:
# Question
Title: Links on site adding index.php in URL
I have a Drupal 8 site and am encountering an issue. When I visit the site as an anonymous user and click a link on the menu, it adds /index.php to the url. Then if I navigate to that page and click another link in adds another index.php (i.e. example.com/index.php/index.php/link1/link2) and therefore the page will not load. This does not happen if I am logged into the site, has anyone encountered this before? I tried a fresh htaccess file and beyond that I am stumped. It is on a shared hosting plan. Any help is appreciated.

# Answer
I had the same problem.

I have a view with links to content, where the URLs are *item/\[one content's field value\]*. One day, I watched the view as anonymous user and noticed that these had been changed to *index.php/index.php/item/\[one content's field value\]*. (On the other hand, when I visited as administrator user, it didn't happen.)

I didn't know why it happened, and it was solved by executing `drush cc render`.

However, the problem would still be left.

The environment is Drupal 8.3.9 and PHP 7.0.25.
> 5 votes

# Answer
From here:

> A solution. Install the Redirect Module, the default setting of Enforce clean and canonical URLs will fix the issue. However, there is also a long outstanding bug Route normalizer: Global Redirect in Drupal which apparently is the cause, but hasn't been pushed to Core yet.
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: Implementing hidden content parts (as in old "Hidden Content" module)
There is (long unsupported) "Hidden Content" module, allowing to insert content blocks visible by certain roles only, i.e. like below:

```
[hidden role="Role Name"]
   ...content visible to "Role Name" role only
[/hidden]

```

I browsed through related modules (from "Content Access Control" etc), but see no good match for this module's capabilities. Are there any simple means to achieve the above without either re-implementing the module for Drupal 9 or using inline PHP?

"Paragraphs Access Control" looks somewhat suitable, but it requires creating quite a complex structure only to restrict access to text blocks.

# Answer
> 0 votes
1. You could use Block Class module to set blocks with some useful classes like "only-role\_name", etc. and hide/display it on your theme stylesheet.
2. Maybe even you could set a new block type and, if this type has its own css class (I'm not sure about it), use it to hide/display using, again, your theme stylesheet.
3. You could, too, use a new content type to create the block contents and Views to render this as blocks where you need. Views is able to restrict his view depending on roles or permissions.

---
Tags: nodes
---


title: How to add block template suggestions?

text:
# Question
Title: How to add block template suggestions?
I want to be able to create a block or *place* a block into a region and theme it according to the selected view mode from Panels. I have noticed a discrepancy between Custom Block and Entity Block where one form gives you the view mode to show the block in, and the other does not (Custom Block).

I want the template suggestion to be along the lines of `block--provider/module--block-bundle--view-mode.html.twig` but struggling to find consistency in the variables in `hook_theme_suggestions_block_alter()` in order to add the suggestion. At the same time, I want to enforce the template that is used no matter if the user created the block inline, or referenced an existing block via Entity Block. What keys or identifiers can I look for to make this work?

# Answer
> 1 votes
Normally a content entity has a template, like `node.html.twig` for `node`, so for custom blocks there should be `block-content.html.twig`. To avoid overhead it was decided to remove this template. This means you can't add template suggestions to the entity template, instead you have to add them to the block template. In this case you get the variables from the plugin when adding suggestions and you don't find the view mode or other details in a consistent way like for entities.

Additionally you use two different plugins to place the block:

The second method, this is using custom blocks outside of the core block content plugin is not officially supported, because the pair of both are optimized to work together.

For the second method a custom entity might be a better choice (then of course one which has a template, which is standard for entities built by Drupal Console ).

---

> I have noticed a discrepancy between Custom Block and Entity Block where one form gives you the view mode to show the block in, and the other does not (Custom Block).

Checking the linked code from the Custom Block plugin. It should show the view mode, if there is more than one to choose from:

```
$form['view_mode'] = [
  '#type' => 'select',
  '#options' => $options,
  '#title' => $this->t('View mode'),
  '#description' => $this->t('Output the block in this view mode.'),
  '#default_value' => $this->configuration['view_mode'],
  '#access' => (count($options) > 1),
];

```

# Answer
> 1 votes
I like to reuse basic block for a lot, so I added a List(text) field called "field\_role" With this, I can reuse the basic block type in lots of places, each with unique templates. The following provides template suggestions:

```
function mymodule_theme_suggestions_block_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['elements']['content']['#block_content'])) {
    /** @var \Drupal\block_content\Entity\BlockContent $content */
    $content = $variables['elements']['content']['#block_content'];
    $view_mode = $variables['elements']['content']['#view_mode'];
    if (isset($content->get('field_role')->getValue()[0]['value'])) {
      $role = $content->get('field_role')->getValue()[0]['value'];
      $suggestions[] = "block__block_content__{$role}";
      $suggestions[] = "block__block_content__{$role}__{$view_mode}";
      if ($label = $variables['elements']['#configuration']['label']) {
        $label = preg_replace("/[^a-zA-Z0-9\s]+/", "", trim(strtolower($label)));
        $label = str_replace(" ", "_", $label);
        $suggestions[] = "block__block_content__{$role}__{$label}";
        $suggestions[] = "block__block_content__{$role}__{$label}__{$view_mode}";
      }
    }
  }
}

```

---
Tags: 8, theming, panels
---


# Question
Title: How to send system mails in html format (with Swift Mailer)?
At **Account settings** page (`/admin/config/people/accounts`) I can edit system mails Drupal is sending (Welcome, Account activated, Account blocked and so on).

I also installed and configured **Swift Mailer** module. At **Message settings** page (`admin/config/swiftmailer/messages`) I selected HTML for message format.

Then I edit some message template and enter html content there like:

```
<!DOCTYPE html>
<html>
  <head>
    <title>Your account at [site:name] has been activated.</title>
  </head>
  <body>
[user:display-name],

Your account at [site:name] has been activated.

You may now log in by clicking this link or copying and pasting it into your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at [site:login-url] in the future using:

username: [user:account-name]
password: Your password

--  [site:name] team
  </body>
</html>

```

However in mail I receive I still got `Content-Type: text/plain;` and I see it as plain text.

At that Swift Mail **Message settings** page it says:

*"You can set the default message format which should be applied to e-mail messages."*

But I don't see that option anywhere? How to change this default message format (to "text/html")?

**An update:**

I found out that if I uncheck "Respect provided e-mail format." on SwiftMails Message settings page I do get text/html content type in mail header. However all the tags I enter in mail template are stripped out and new rows are automatically converted to paragraphs? I expected that there will be "HTML email" text format at Text formats page (`/admin/config/content/formats`) where I can set filters, but there aren't any.

# Answer
Swiftmailer works in combination with the (contrib) **mailsystem** module.

Check the settings here: `/admin/config/system/mailsystem`

Make sure Swift Mailer is set as global formatter (on top).

> You also should select the theme you wish to render your HTML emails.

Or, under module specific configuration, you can add the user module to explicitly use Swift Mailer (as formatter). Just leave the key field empty to use all emails from the specific module. Then other emails are not affected ..

**UPDATE:** Swiftmailer can will let you choose form any text format you have defined, you can create a new one yourself. But, this will not let you output any meaningful HTML (see https://www.drupal.org/project/swiftmailer/issues/3122389) as the textformat needs "Show HTML as plain text" filter activated. Work with twig templates (see Why does swiftmailer doesn't use my HTML template?) you can probably make one per email like `swiftmailer--password_reset.html.twig` (see https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/\_user\_mail\_notify/8.2.x for all mail keys). Still if you want to have custom HTML "in-between", you need to hook\_mail and add the information to be used in your template (using #theme render array entries).
> 0 votes

# Answer
My edit to the accepted answer got reverted, so I'll contribute it as a separate answer, for two reasons: 1) several grammatical and formatting errors in the accepted answer make it hard to read and understand and 2) the comments to the accepted answer (and the "Update" section) explain why the proposed solutions do not work. This answer adds an additional working solution, credited to the author of said approach, at the very bottom of the post.

The Swift Mailer Drupal module works in combination with the (contrib) **Mail System** module.

# 1. Setup Mail System

1. Check the settings here: `/admin/config/system/mailsystem`
2. Make sure Swift Mailer is set as the **Default Mail System \> Formatter**.
3. Select the **theme** you wish to render your HTML emails — typically your front-end theme — where you have the ability implement a custom `swiftmailer.html.twig` template with any wrapper HTML (eg email header and footer text that appears on all templates) and sub-templates.
4. Alternatively, under Module specific configuration, add the user module to explicitly use Swift Mailer as the Formatter for the User module. Hint: Leave the key field empty to affect all emails from the specific module. This way, other system or contrib module emails are not affected.

# 2. Configure Swift Mailer to use HTML for Core User Templates

1. Swift Mailer lets you choose the HTML format to use from a list of Text Formats you have defined in Drupal on the *Message settings* page: `/admin/config/swiftmailer/messages`.

So you could theoretically create a new Text Format yourself, such as "HTML Email", but **this setting does not let you output any meaningful HTML** because the text format needs the "Display any HTML as plain text" filter activated (see Issue #3122389: Bugs with format conversion).

In short, **this option in the UI is a red herring** and is only intended for upgrading Plain Text to a basic HTML format, by converting line breaks to `<br>`s and URLs like `https://example.com` to clickable links like `<a href="https://example.com">https://example.com</a>`.
2. Alternatively, you can create a custom Twig template per module, like `swiftmailer--user.html.twig`, or per email key, like `swiftmailer--user--password-reset.html.twig` and replace {{ body }} with your HTML message, however you will not have access to the same Drupal Tokens that are available to the user account email templates in Drupal's admin UI. For a list of all user mail keys, see the `$op` parameter of `_user_mail_notify()`.
3. Therefore, the currently known best approach is to enter your custom HTML into the Drupal administrative UI, then use `hook_mail_alter` to add `text/html` to the Headers and convert the text to a valid Markup object.

```
use Drupal\Component\Render\FormattableMarkup;
/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
  switch ($message['key']) {

    // User module templates from admin/config/people/accounts
    case 'cancel_confirm':
    case 'password_reset':
    case 'register_admin_created':
    case 'register_no_approval_required':
    case 'register_pending_approval':
    case 'register_pending_approval_admin':
    case 'status_activated':
    case 'status_blocked':
    case 'status_canceled':

    // Contact module templates from admin/structure/contact/manage/sitewide
    case 'page_mail':
    case 'page_copy':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      foreach ($message['body'] as $key => $body) {
        $message['body'][$key] = new FormattableMarkup($body, []);
      }
      break;

  }
}

```

Hat tip to blog post from flocondetoile.fr for the code snippet.
> 3 votes

---
Tags: 8, emails
---


# Question
Title: Programmatically enable the entity view display
I would like to programmatically enable the Layout Builder module. I followed the instructions given on Layout Builder — building Drupal 8 layouts, but they don't seem to work. They might be outdated for Drupal 9.1. Specifically, I'm having a hard time getting the following piece of code to work.

```
$entityViewDisplay = \Drupal::entityTypeManager->getStorage('entity_view_display')
  ->load('ENTITY_TYPE.ENTITY_BUNDLE.VIEW_MODE');

```

Can anyone help me understand it? I just keep getting a `NULL` result.

# Answer
I figured it out. You can enable Layout Builder by running the following code in a custom module:

```
$entity_type = 'node';
$content_type = 'article';
$view_type = 'default';

\Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::load("{$entity_type}.{$content_type}.{$view_type}")
  ->enableLayoutBuilder()
  ->setOverridable()
  ->save();

```

Hopefully this helps someone else. Having to do it via the UI is painful if you have a lot of content types. I'm actually surprised this isn't a Drush command yet. Oh well.

Source: https://www.drupal.org/project/drupal/issues/3158916
> 4 votes

---
Tags: 9, layout-builder
---


# Question
Title: Views, add field value as class to list element
I have a content field called Featured which is an list integer checkbox.

When using Views to display a list of this content, I would like to add a css class to the item wrapper when that value is 1 like so:

```
<li class="views-row views-row-1 views-row-odd views-row-first featured">

```

I suspect editing the views row template would be one option, although I do not know how to achieve this, and since this is the only change I need to make, is there an easier way?

# Answer
> 4 votes
The question is a bit old, but i was looking for the same.

My answer is for drupal 7 / views 3.5, not sure if it works on previous versions.

You can use some field replacement patterns when specifying the classname for the row (in the view edit : Format / Settings / Row Class )

To do so, on the same settings page you may have to check the box 'force using fields'

You then have to make sure the field you want to use is added to the fields section of the view edit

To know what pattern you can use, click on the field in the fields section and go to 'rewrite results' / 'rewrite the output of this field', there is a 'replacement patterns' block that will show you the available patterns.

hope that help, I'm still stuck though by the fact that the string you will get is not class friendly and may contain spaces.

# Answer
> 1 votes
The answers here so far don't answer the question as we're specifically looking to include the value of a field within the views row within the markup of the views row wrapper element. The suggestions so far cover adding a class to the entire view's wrapper or giving a class to a field within the row, which isn't quite right.

Making a views template is a matter of clicking "Theme: Information" (Views 3) and you'll be presented with a list of candidate file template names. Create a new file in your theme with a name more specific than the currently used template (highlighted in bold) then click "rescan template files" or clear the cache.

Sample template files that you can C&P from are in the Views module (of course), look in your "sites/all/modules/views/theme" folder.

Actually creating the Views row template is not particularly hard, so finding "an easier way" might be tough :P

That said, depending on your use case you might just want to exclude all the fields from display, then create a "global: custom text" field and use a token replacement for your "featured" field in a wrapper div/span inside this custom text and drop your desired content within that to create a "row within a row" kind of effect.

# Answer
> 1 votes
As *developpeur 2000* suggested, one way to add a class to these rows is to edit the view and go into Format / Settings / Row Class.

In that input box, enter the token for the field you're interested in displaying, along with any prefixes you'd like to add (in my case, it was "featured-\[field\_featured\]").

If the field you're displaying is a boolean and you want a 0 or 1 as your class, make sure that you have "Key" selected as the formatter under Fields / {Your Field} / Formatter. Otherwise nothing will show up unless you've set an "On value" and an "Off value" in the field's settings.

If you want the boolean to display as "true" or "false," for example, you'll need to set an "On value" and "Off value" for the boolean under Structure / Content Types / {Your Content Type} / Manage Fields / {Your Field}. Then you'll want to use "Default" instead of "Key" as your Formatter in views.

For your specific example, let's assume the content type you're pulling in is called **News Articles** and the field you're interested in adding as a class is called **Featured**. Here's a step-by-step that I hope should work for you:

1. Go into Structure / Content Types / **News Articles** / Manage Fields / **Featured** and set the "On value" to **featured**. Leave the "Off value" blank. Save settings.
2. Edit your view and click on Format / Settings. Under row class, enter **\[field\_featured\]**. Apply.
3. Still in your view edit area, click on Fields / **Featured**. Make sure the formatter is set to **Default**. (I also use "Exclude from display" since I don't want this appearing anywhere else in my markup.)
4. Inspect your list to make sure you've got the "featured" class on items you want featured, then save.

This method avoids editing the views row template, which is nice because it's theme independent this way. You can load up a different theme and you'll still be adding the "featured" class to the same place.

# Answer
> 0 votes
If I understand well your question, I think that your view have a class to achieve this. You can use your current `featured` class to style the first element. for example:

```
li.featured:first-child
{
color:red;
}

```

regarding add a class according the value of your first LI item, I do not know how to make this from a Drupal way, I just can offer a jquery way:

if your view already have a `featured` class you can try this, just putting this code in the head of your page.tpl.php

```
<script src="http://code.jquery.com/jquery-1.6.4.min.js">
//this is not necessary if your Drupal already have Jquery
</script>
<script>

$(document).ready(function() {
valueLi = $('li.featured:eq(0)').text(); //get the value
valueLiClass = valueLi.replace(/\s+/gi,'');//remove spaces between words
$('li.featured:eq(0)').addClass(valueLiClass);//add the class
 });

</script>

```

I hope information be useful.

# Answer
> 0 votes
Adding details to the good answer from to "developpeur 2000", if the field type you rely on is "Text List", be sure the output format is "Key". This will produce safe class names as

```
views-row-{{ field-Featured }}

```

"Exclude from output" in field setting is probable necessary also.

---
Tags: views
---


# Question
Title: jQuery dependency on a custom theme is not adding jQuery?
I know that this question has been asked previously many times but any of the solutions are not working in my case so please, I request if anyone can help me with this situation please provide me assistance. I have added dependency of the core jQuery(along with other core libraries) in my **theme.libraries.yml** but only core jQuery is not loading in my drupal frontend and the console is showing the error of jQuery is not defined. Also other drupal core libraries as working fine only jQuery is not loading.

My code of various files is as follows

***theme.libraries.yml***

```
global-styling:
  version: 1.x
  css:
    theme:
      css/bootstrap.css: {}
      css/custom.css: {}
      css/owl.carousel.min.css: {}
      css/owl.theme.default.min.css: {}
      css/responsive.css: {}
      css/style.css: {}
      fonts/fonts.css: {}
  js:
    js/bootstrap.js: {}
    js/owl.carousel.min.js: {}
    js/popper.js: {}
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

```

**theme.info.yml**

```
name: wcsb
type: theme
description: 'Another outstanding WebCube Theme'
package: Core
version: '0.1.2'
core: '8.x'
base theme: classy

libraries:
  - wcsb/global-styling

regions:
  header_bar_1: 'Header Bar 1'
  header_bar_2: 'Header Bar 2'
  header_bar_3: 'Header Bar 3'
  header_bar_4: 'Header Bar 4'
  mobile_header_1: 'Mobile Header 1'
  mobile_header_2: 'Mobile Header 2'
  slider_images: 'Slider Images'
  breadcrumb: Breadcrumb
  featured_top: 'Featured top'
  above_content: 'Above Content'
  content: Content
  below_content: 'Below Content'
  sidebar_first: 'Sidebar first'
  sidebar_second: 'Sidebar second'
  featured_bottom_first: 'Featured bottom first'
  featured_bottom_second: 'Featured bottom second'
  featured_bottom_third: 'Featured bottom third'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_fourth: 'Footer fourth'
  footer_fifth: 'Footer fifth'

```

**list of scripts loading**

```
<body class="path-frontpage page-node-type-page" data-new-gr-c-s-check-loaded="14.1002.0" data-gr-ext-installed=""
cz-shortcut-listen="true">

<script type="application/json" data-drupal-selector="drupal-settings-json">
    {
        "path": {
            "baseUrl": "\/",
            "scriptPath": null,
            "pathPrefix": "",
            "currentPath": "node\/1",
            "currentPathIsAdmin": false,
            "isFront": true,
            "currentLanguage": "en"
        },
        "pluralDelimiter": "\u0003",
        "suppressDeprecationErrors": true,
        "ajaxTrustedUrl": {
            "form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM": true
        },
        "user": {
            "uid": 0,
            "permissionsHash": "508c848d9cf616f3b3735479b8cad945e128b7dbb0a534206170c7d3643afe05"
        }
    }
</script>
<script src="/core/assets/vendor/jquery-once/jquery.once.min.js?v=2.2.3"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.9.13"></script>
<script src="/core/misc/drupal.js?v=8.9.13"></script>
<script src="/core/misc/drupal.init.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/bootstrap.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/owl.carousel.min.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/popper.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/scripts.js?v=8.9.13"></script>
<script src="/modules/contrib/commerce/modules/cart/js/commerce_cart.js?v=8.9.13"></script>

```

**console errors**

# Answer
> 1 votes
**Solved** The problem was in my .theme file where it was unsetting the core jQuery library. The problem code:

```
function theme_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets)
{
    unset($javascript['core/assets/vendor/jquery/jquery.min.js']);
}

```

Thanks to **@AlfredArmstrong** for providing the suggestion of reviewing the php files

---
Tags: 8, theming, javascript
---


# Question
Title: How can I add paragraphs to a translated node?
I have a problem with the Paragraphs module and translation. I'm using Drupal 8.7.7 and Paragraphs 8.x-1.9.

When I add a translation to a node with a paragraphs field (unlimited), I can only translate existing fields in this paragraph, but I cannot add new values on the translation node.

I followed the instructions given in the docs on https://www.drupal.org/docs/8/modules/paragraphs/multilingual-paragraphs-configuration and in fact, if I didn't I wouldn't have been able to even see the fields in the translation edit form.

I have no idea, how to set this up correctly.

I installed the Paragraphs Asymmetric Translation Widgets module which somehow says, it deals with it, but it does not. I used the Widget 'Paragraphs Classic Asymmetric' in the form display, but to no avail.

I'm really desperate now.

# Answer
There is no solution out of the box yet.

There are two features that are not realised at the same time.

* The *Paragraphs EXPERIMENTAL* widget by the Paragraphs module provides for a drag & drop mode mode
* The *Paragraphs Classic Asymmetric* widget from Paragraphs Features module provides the functionality of asymmetric translation

There is no *Paragraphs EXPERIMENTAL Asymmetric* widget

I decided to drop the Drag & Drop feature in favor of the asymmetric translation feature.
> -1 votes

# Answer
If I remember this right this is by design (or maybe more a technical necessity). And you can only circumvent this by having multi-value fields inside a paragraph type. Like a node reference field for example. This then can have a different number of items per language and even in a different order.

You could also add a new untranslatable "Visibility" field to each paragraph type, like Paragraphs Collection is offering it, see 2846682#comment-11887724 for example. Then you add different paragraphs in the original language but set them to be displayed only in selected languages.

And regarding Paragraphs Asymmetric Translation Widgets you may file a bug report in its issue queue.
> 0 votes

# Answer
I had a similar problem and I solved it by making the paragraph field on the node **translatable**.

This can be done by going to manage fields of the content type and editing the paragraph field and then tick the checkbox **"Users may translate this field**"

More information on this particular point can be found on the Paragraphs Asymmetric Translation Widgets module page.
> 0 votes

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


# Question
Title: Cannot use object of type stdClass as array error in node save
I built a custom form and one of them is of type geocode with lat/lon fields. When I try to save the node I receive the following error:

> Cannot use object of type stdClass as array in /var/www/vhosts/example.com/httpdocs/modules/field/field.attach.inc on line 208\n'.

The error disappears when I put comments in this field. My question is how can I solve this since it is very important field (I try to create nodes with geocode locations)

Here is how I declare my field:

```
$form['field_locationmap'] = array(
    '#title' => 'geofield',
    '#type' => 'geofield_latlon',
  );

```

It seems that the error occurs when I m trying to pass the values to the object:

```
$location->field_locationmap->und->{0}->geom->lon=$form_state['values']['field_locationmap']['lon'];
$location->field_locationmap->und->{0}->geom->lat=$form_state['values']['field_locationmap']['lat'];

```

# Answer
Assuming this is Drupal 7 field\_locationmap is an array so your assignment should look something like this:

```
$location->field_locationmap['und'][0]['geom']['lat']

```

Also make sure that\['geom'\]\['lat'\] is the correct structure for that value (i.e it is an array with two keys) P.S. Consider using $location-\>language instead of 'und' in case you support multiple languages.
> 0 votes

# Answer
I guess you are using Entity metadata wrapper solution to set values of an entity (in this case node) , if so you have to use `set` method like this :

`$location->field_locationmap->set([$form_state['values']['field_locationmap']['lon'], $form_state['values']['field_locationmap']['lat']]);`

if not using entity metadata wrapper you might using some code like below:

```
$location = new stdClass();
$location->field_locationmap->und->{0}->geom->lon=$form_state['values']['field_locationmap']['lon'];
$location->field_locationmap->und->{0}->geom->lat=$form_state['values']['field_locationmap']['lat'];
$location->save();

```

if so as drupal expects fields value to be an array, it throws exception when facing object, so you need to modify your code like this:

```
$location = new stdClass();
$location->field_locationmap['und'][0]['geom'] = [
  'lon' => $form_state['values']['field_locationmap']['lon'],
  'lat' => $form_state['values']['field_locationmap']['lat']
];
$location->save();

```
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Pathauto pattern for a content type depending on a reference field?
This question is already asked here, but the answer selected does not work for Drupal8.

**Description**: There is a content-type, which has field, referencing taxonomy term. The term is in "Content class" dictionary. This term is used in views to filter the right content for the view. When a link in the view is clicked, it opens the node. This is OK. So, it is needed pathauto to generate /Content class term/Content\_title\_name when this node is opened.

**What did not work**: `[node:field_content_class:value]/[node:title]`. This is not accepted, produces error: `Path pattern is using the following invalid tokens: [node:field_content_class:value]`

The accepted (by Drupal) pattern: `[node:field_content_class]/[node:title]` generates alias, containing only the \[node:title\] part. The first component is empty.

This is made to not create separate content-types for nodes with the same fields.

EDIT: The accepted answer works on a fresh copy of Drupal with language translation enabled. I continue to investigate the case with my production site.

# Answer
> 5 votes
A taxonomy field is referencing entities, it has no `value` property. See how to print value of a taxonomy field to headline with node.html.twig?

Converting this to a token pattern:

```
[node:field_content_class:entity:name]/[node:title]

```

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


# Question
Title: Why no alias record could be found when I'm trying to sql-sync the database?
I'm trying to synchronize a production database to two development installations at once, instead of having the production database dumped twice.

In `aliases.drush.inc` file I'm defining a site-list alias as following:

```
$aliases['dev'] = array(
  'site-list' => array('@dev1', '@dev2'),
);

$aliases['prod'] = array(
  'uri' => 'default/prod',
  'root' => '/docroot/prod',
  'db-url' => 'mysqli://root:pass@localhost/prod',
);
$aliases['dev1'] = array(
  'uri' => 'default/dev1',
  'root' => '/docroot/dev1',
  'db-url' => 'mysqli://root:pass@localhost/dev1',
);
$aliases['dev2'] = array(
  'uri' => 'default/dev2',
  'root' => '/docroot/dev2',
  'db-url' => 'mysqli://root:pass@localhost/dev2',
);

```

Running a Drush command against any of these aliases works fine.

Running `drush @dev status` works fine too, and displays the status for both `@dev1` and `@dev2`.

However, trying to execute `drush sql-sync @prod @dev` gives me the following error:

> Error: no alias record could be found for @dev

Do you have any clues?

# Answer
Seems that this feature is buggy in Drush and will be removed. Check this out: drupal.org/node/1316378
> 2 votes

# Answer
Drush 8+ expects a site alias file. For me it turned out that the drush/sites/self.site.yml didn't exist after I've run into a similar error. The alias file didn't got copied properly into a container.

You need to ensure that the alias file exists.

> ```
> $ drush sql-sync @test @self -y
> Error: no alias record could be found for source [error]
> @test
>
> ```

Here's a nice article about Drush Site Aliases for Drupal 8 and Drupal 9 and how this actually is supposed to work in detail: https://drupalize.me/tutorial/drush-site-aliases?p=2458
> 1 votes

# Answer
copy the DB array from your settings to your aliases file.
> 0 votes

---
Tags: drush
---


# Question
Title: How come images with image styles are blurry?
We have noticed that images that are displayed using Image Styles are blurry. Below are the settings we have enabled.

The original images look fine and scale accordingly when using those on the pages, but not the Images with Image Styles. How can this be resolved?

1. GD2 Image Manipulation Toolkit settings: JPEG set to 100%
2. ImageMagick module but the results are the same.
3. We also tried to use JPEG and PNG

View mode (field setting):

1. formatter = image
2. Image style: Banner Image

Banner Image Image Style settings:

1. Scale 1600px (W) by 900px (H)
2. Allow Upscaling = false

CSS and HTML used:

```
<div class="banner__image" style="background-image: url('/sites/default/files/styles/banner/filename-banner.jpg')";>

.banner__image {
  width: 100%;
  height: 100%;
  background-position: center;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

```

# Answer
> 0 votes
I've delt with this issues on many sites. The cached version from the image style always renders poorly. I'd recommend removing it and using CSS to adjust the sizing.

In some cases, removing existing upload size limits on the image field has helped resolve this.

# Answer
> 1 votes
Yes. Better to increase the image styles in Drupal UI (/admin/config/media/image-styles) For Example: (340×340) means just increase the 2x size in your image styles config like (640x640)

---
Tags: 8, media
---


# Question
Title: Ajax enabled form stopped working - Ajax callback never called
I have the weird problem that an Ajax enabled form that just worked stopped working - and I have not a clue what is causing this and when it stopped to work. The form itself has no changes for months now and I did not find any code updates which may interfere with this form.

The form is defined in its own form class which extends FormBase. The Ajax functionality is added with the following code in buildForm() method:

```
$form['form_container']['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => [
    'callback' => '::ajaxResponse'
  ],
  '#attributes' => [
    'class' => ['js-show-throbber']
  ],
  '#weight' => -45,
];

```

In the form class the method is defined:

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

```

When I set a breakpoint within this method for XDebug the script never stops, the process within this methods are not running.

There is no info in browser's console, it is not working in any browser and in watchdog of Drupal are no entries. For me it seems that somehow the bridge between browser / JavaScript world and the form PHP class is broken. I use the exact same PHP code for many other forms without any problem.

My question: can anybody give me a hint how exactly the bridge between browser and form class is created when the form gets rendered? How can I find out if there is a problem in the PHP form class or somewhere in JavaScript?

# Answer
Ok, this was just a stupid mistake in a another javascript. There the jQuery method .off() was used to remove event listeners which had the effect to remove the Ajax event listener.
> 1 votes

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


title: Display a certain page in a view

text:
# Question
Title: Display a certain page in a view
Here is what I'm trying to do is display a certain page in a view instead of all of the basic pages.

How would I go about doing that?

# Answer
> 1 votes
If you want to change what is shown on the site front page you can do that under Configure \> System \> Site information.

Enter `node/[number]` into the **Default front page** field (replace the \[number\] with the node ID of the content you want to appear on the front page).

---

If you want to change Content Views to show only a particular node add the Filter `Content: Nid` with the **Operator** set to `Is equal to` and enter your node ID number in the **Value** field.

This will show only the one node information on that Views.

---
Tags: 7, views
---


# Question
Title: How to add and associate Paragraphs to Media Library Images Programmatically
Good day everyone,

Our client wants to have this feature where he can upload/reuse multiple images for an article content type. This can be achieved using a Media Library, where I find it tricky is each images will have additional fields(Alt, Copyright, Description fields), I've tried adding the additional fields to the Image Media Type but once the node is saved, their value will be associated to the image's metadata. The proper functionality should be is when the node is saved, the Alt and Description of the images should be associated to the node's metadata because Images can be reusable to another node, and the values of Alt and Description varies to each node.

So I talked with someone who really knows a lot about Drupal. He suggested that I keep the Media Library, and create a Paragraph Type. I called it 'Image Library Paragraphs', this paragraph has Image, Alt, Copyright, and Description fields. This way the Paragraph can hold the id of the image, alt, description and the node's ID. In theory, what we're trying to do here is everytime the user uploads/select an image. We must find a way to associate that image and add corresponding paragraph for each of those images. So if the user uploads/selects 3 images. It will also automatically create 3 paragraphs for those images. We also would need to reconstruct the layout of the form to somehow "blend" the image and its corresponding paragraphs. And since the position of the images can be changed, we also need to somehow reposition its paragraph accordingly to the image.

It's tricky and a lot of work, honestly it's even beyond my Drupal skills. But any help to the right direction will truly be appreciated. I haven't even tried creating a really complex custom module. But would really want to learn how this can be done. Thank you in advance.

In theory this is what it's gonna look like

# Answer
1. Create a paragraph "Node Image".
2. Within the Paragraph type, add your media reference field and various text fields for your image metadata. Set them all to required, this is key for later.
3. Go back to your Node type and add a new Paragraphs field called "Node Images", set to unlimited cardinality. Restrict the field to only allow the "Node Image" Paragraph type.
4. On the Node's Form Display, set to the new field to "Paragraphs Experimental".
5. Configure the settings (the gear icon) to suit your needs. AKA override the single/plural to be "Node Image" and "Node Images", set to closed, use button, default value...etc. Fiddle with it.
6. Create a Test Node with 2 of these paragraphs. Ensure theme debugging and cache is off. Otherwise you will have to flush each time.

> At this point you have all the ability to add the data needed to Drupal. The rest can be handled via traditional theming methods, or Display Suite. Within display suite there are even various routes to accomplish this. I will explain what I feel is the simplest method. This method relies on the fact that all your fields are required, unless you are OK with possibly printing things like empty tags. Remember from earlier when I said it was key?

1. Go to Display Suite \> Fields in the admin UI and create a new "Token field" name it "SEO Image" or something fun.
2. Within that field, configure it to show up for Paragraphs of type "Node Image".
3. In the field content, build an `<img src="[token]" alt="[other_token]" ...>` tag and fill in the data with values properly. You might want to brush up on tokens and reference fields with the `:entity:` keyword. You will need that to get the URL for the image. For the SEO fields, you can just find them in the token browser **NOTE:** You will need to ensure that a text format is setup that allows both HTML and tokens :)
4. Go to your Paragraph type, and visit the Manage Display tab. On that page, at the bottom, enable the display to be "Display Suite : Reset". Save the page to reload the form.
5. Remove all of the other fields from being enabled, and instead drag the new Token field we created to enabled. Save the form.
6. Go look at your Test node. You should see your images rendered through that token field on the front end.

If any of this doesn't work, tweak your settings. There is a bit of a learning curve here. Webwash has done some great tutorials on all of the concepts covered if you want to do some research.

The Paragraphs experimental widget is really powerfull, for your backend UI needs of reordering and side by side you can do the following:

1. Create a new display mode (or view mode as you might also know it) for your paragraph called "Node Image Admin".
2. Go you your paragraph type, and under Manage Display, you can enable that view mode. Once you have this setup, you can now alter the HTML markup to build your side by side admin UI. This would vary depending on your admin theme. You could also try using Display Suite and the Field Group module to do it all in the UI, so many options really once you digest everything.
3. The final step is going back to your "Manage Form Display" for your node type. Edit the settings (gear icon) for the Paragraphs field and set the closed display to the new view mode.

As stated, paragraphs experimental widget has drag and drop, mass drag and drop, and all kinds of features to discover. I have yet to find anyone who wants to pay for more that what you get out of it when they have been given a tutorial of how to use it. It is really on the developer to tweak it to work best for each use case.
> 0 votes

---
Tags: forms, media, paragraphs, 9
---


# Question
Title: Tell taxonomy links to use route in custom module
I have a module where I created a route `/page/tag/{term}` that uses a controller for modifications to how the term page is handled.

The problem is that when any page displays these term links, they don't use the custom route, but the default `/taxonomy/term/{id}`.

How can I tell the taxonomy term links to use my custom route?

Adding the path as the term alias skips over the custom route entirely.

OR, how would I get rid of the custom route and create a pathauto pattern using the same path, but tell those pages to use my custom controller?

I have tried both methods without success...

---

Here is what I've tried with modifying the existing route:

modulename.services.yml

```
services:
  modulename.route_subscriber:
    class: Drupal\modulename\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber, priority: 100 }

```

modulename/src/Routing/RouteSubscriber.php

```
namespace Drupal\modulename\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
    * {@inheritdoc}
    */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            // i've tried both of these
            $route->addDefaults(['_controller' => '\Drupal\modulename\Controller\ListController::list_by_tag' ']);
            $route->addDefaults(['_title' => 'test']);
        }
    }

}

```

---

Edit: after seeing this, I thought about keeping my custom route and using the alterRoutes to change the links...

`$route->setPath('/page/tag');`

That worked, but it adds on ?taxonomy\_term=123

How can I get the term name into the url? `/page/tag/term`

---

Update:

Still can't figure out how to get the term name from the route (without loading the taxonomy entity - I'd imagine that is too much load)

Also, I will need to make sure I'm in a specific vocabulary before changing the route.

Any ideas?

# Answer
> 1 votes
In my case, I'm also using a `RouteSubscriber` to change the default controller responsible for handling taxonomy term entities. I also wanted to use a custom template only for a specific taxonomy (called `my_taxonomy` in the example below).

Here is the code for the `RouteSubscriber`:

```
<?php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RoutingEvents;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            $route->setDefaults([
                '_controller' => '\Drupal\my_module\Controller\DefaultController::listAll',
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -200];
        return $events;
    }

}

```

And here is the code for the controller. Note that a custom render array can be returned only for terms of the specific taxonomy `my_taxonomy`. All other terms fall back to the default controller used by the `views` module in the original route:

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\Routing\ViewPageController;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends ControllerBase {

    public function listAll(Request $request) {
        $render = [];

        $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
        $term = Term::load($tid);
        $bundle = $term->bundle();
        if ($bundle == 'my_taxonomy') {
            // render array for your custom template
        } else {
            // falls back to the default ViewPageController to handle all other taxonomies
            $viewPageController = new ViewPageController();
            $render = $viewPageController->handle('taxonomy_term', 'page_1', \Drupal::routeMatch());
        }

        // Return render array
        return $render;
    }

}

```

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


title: Use theme template with specific Views

text:
# Question
Title: Use theme template with specific Views
I have a D8 subtheme of Bootstrap and on the homepage I have 2 Views (2 carousel views).

I turned on twig debugging so I could see which template file(s) is (are) being used, and where it starts and ends. When I used this before it included a listing of sample alternate filenames for that specific content (e.g. *paragraph--about-us-page--full.html.twig*), which was a big help.

For each of the views on the homepage, they are shown using **views-view.html.twig** and **views-view-field.html.twig** whether from the module template, bootstrap template or my copy of the files into my theme.

Is there a way to set up a template file for each of the views individually?

View Machine Names:

* homepage\_slider
* homepage\_loans

They only reside on the front page. I have tried renaming files to see if I can see it being used in the Twig debugging and frequently clear the cache.

It could be a Page, View, Block, etc. template, but then how do I reference the parts of the View to control the display of the fields.

Thank you.

# Answer
I think what you're looking for is in this section: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/twig-template-naming-conventions#s-views

Specifically,

> views-view-field.html.twig based patterns are postfixed with the view's field id (as in replacement patterns) to display a single field in a view:
>
> * views-view-field--\[viewid\]--\[view-display-id\]--\[fieldid\].html.twig
> * views-view-field--\[viewid\]--page--\[fieldid\].html.twig
> * views-view-field--block--\[fieldid\].html.twig
> * views-view-field--\[fieldid\].html.twig
> * views-view-field.html.twig
> 1 votes

# Answer
The reason you don't see these suggestions is due the the following bug, #2923634: Use hook\_theme\_suggestions in views
> 1 votes

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


# Question
Title: Remove Administration Theme from user/%/edit
I want the administration theme for all the default pages, except one: /user/%/edit

How do I get the default theme to display for this page instead of the administration theme?

# Answer
For Drupal 7 you can use Administration theme or hook\_admin\_paths\_alter() in your custom module.

```
/**
 * Implements hook_admin_paths_alter().
 */
function my_module_admin_paths_alter(&$paths) {
  $paths['user/*/edit'] = FALSE;
}

```

For Drupal 8, see https://www.drupal.org/node/2224207.
> 13 votes

# Answer
I believe ThemeKey allows you to control that: https://drupal.org/project/themekey

If that doesn't work, you can force a specific theme for a page using: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_custom\_theme/7
> 1 votes

# Answer
For anyone looking for a D8 solution:

Filename: YOUR\_MODULE.routing.yml

```
YOUR_MODULE.user_edit:
  path: '/user/{user}/edit'
  defaults:
    _entity_form: 'user.default'
    _title_callback: 'Drupal\user\Controller\UserController::userTitle'
  requirements:
    _entity_access: user.update
    user: \d+
  options:
    _admin_route: FALSE

```
> 0 votes

---
Tags: theming, users
---


# Question
Title: Newly created field not being added to entity
I have created a form that adds a subset of field types to an entity (does not support bundles). (the reason for the custom form is that end users find the Drupal standard 'Manage fields' workflow too difficult) The class extends FormBase. When the 'submitForm' function is executed, the field is saved but not added to the entity.

This is the code to save a date field (with text values filled in for explanation purposes):

```
$field_storage_values = [
  'field_name' => 'field_test_date',
  'entity_type' => 'my_entity_id',
  'type' => 'datetime',
  'translatable' => TRUE,
];

$field_values = [
  'field_name' => 'field_test_date',
  'entity_type' => 'my_entity_id',
  'bundle' => 'my_entity_id',
  'label' => 'Test Date',
  'translatable' => FALSE,
];

$this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values)->save();
$field = $this->entityTypeManager->getStorage('field_config')->create($field_values);
$field->save();

```

When the form is submitted, the field is created correctly but not added to the entity.

When I export the field configuration to YML, the following appears under dependencies:

```
dependencies:
  config:
    - field.storage.my_entity_id.field_test_date

```

Creating an identical Node field results in the following field configuration YML dependencies:

```
dependencies:
  config:
    - field.storage.node.field_test_date
    - node.type.basic_page

```

I suspect the field created with my custom form should also add the second configuration dependency like:

```
my_entity_id.type.my_entity_id

```

I tried adding the following before the field is saved but the 'addDependency' function is protected.

```
$field->addDependency('config', 'my_entity_id.type.my_entity_id');

```

# Answer
> 1 votes
You can't add this dependency, it's bundle configuration which you don't have and don't need in a bundleless entity. For testing better add a user instead of a node field or check the already pre-installed field.field.user.user.user\_picture.yml

To create the field config you only need to specifiy the field storage and the bundle (for a bundleless entity this is the entity id). The other values are then extracted from the storage config:

```
$storage = $this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values);
$storage->save();

$field = $this->entityTypeManager->getStorage('field_config')->create([
  'field_storage' => $storage,
  'bundle' => 'my_entity_id',
]);
$field->save();

```

BTW part of the field UI is also the configuration of display modes. You need to add the new field as component at least to the default view and form mode, so that the new field is visible. See How to change the entity view display configuration programmatically?

---
Tags: 8, entities
---


title: Override form element twig template

text:
# Question
Title: Override form element twig template
I want to override the twig template for specific fields on a form which I created via the Contact module in Drupal 8.

However, I can't find any documentation, and the suggestions in the HTML comments also doesn't show me anything useful.

Basically I want to override, a custom field (field\_phone) and a standard field (Sender name) on a specific contact form the following values:

* form-element.html.twig
* form-element-label.html.twig
* input.html.twig

Is that possible? And what are the file name suggestions?

# Answer
> 8 votes
The Drupal Themable Forms module adds some helpful theme suggestions for form elements that are missing from core.

The added theme suggestions for form elements are:

```
  form-element--[form-id]--[element-type].html.twig
  form-element--form-id--[form-id].html.twig
  form-element--type--[element-type].html.twig
  form-element.html.twig

```

# Answer
> 8 votes
No need to install an extra module, you could just add the suggestions by yourself:

file: *MYMODULE.module*

```
function MYMODULE_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if ( $variables['element']['#id'] === 'FORMID') {
    $suggestions[] = $hook . '__custom';
  }
}

```

this will make Drupal look for a twig file named '**form-element--custom.html.twig**'

$hook is 'form\_element' in this case, as we are explicitly hooking into it, the function name is '*MYMODULE\_theme\_suggestions\_HOOK\_alter*', but you could just choose **any arbitrary name** for the template file, i just tried to stick to the Drupal naming conventions.

To find out the FORMID for your specific form just add the following line as the first line of the function and then inspect the element in the browser, there you will see an html comment with the name of the form.

```
  print '<-- FORMID:'.$variables['element']['#id'].'-->';

```

# Answer
> 0 votes
A more generic approach:

```
function MYTHEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  $suggestions[] = $hook . '__' . $variables['element']['#id'];
  $suggestions[] = $hook . '__' . $variables['element']['#type'];
}

```

---
Tags: theming, 8
---


# Question
Title: Error: Class 'DOMDocument' not found in Drupal\Component\Utility\Html::load() (line 286 of core/lib/Drupal/Component/Utility/Html.php)
After a Debian update my Drupal 8 installation can not show single nodes and spits the following error.

> Error: Class 'DOMDocument' not found in Drupal\Component\Utility\Html::load() (line 286 of core/lib/Drupal/Component/Utility/Html.php).

I have no clue what to do and have installed all required php extensions, following some other issues with the same error.

I already removed all suspicious contrib modules and I am lost now with a broken project.

Any suggestions would be very helpful.
**ENV:** `Drupal 8.5` | `PHP 7.2.9`

# Answer
> 2 votes
That sound like it can't find php Dom extension, to get that try `sudo apt-get install php-xml`, it should solve your problem

# Answer
> 2 votes
Even after installing PHP-dom and PHP-XML, I was getting the same error. So I did a restart of PHP-fpm and Ngnix. It started working after that

---
Tags: 8
---


# Question
Title: How to prevent admin role from changing "Updated date" of content
The updated date of the content is displayed on each node with this code in template file.

```
<?php print strftime( "%Y-%m-%d", $node->changed) ?>

```

Now when I save the content with admin role the date displayed is the date I updated (of course). But I only want to display the date updated by the author of the content. So how can I prevent admin role from changing "updated date" and only keep the date updated by the content author? Or is there a way to display only the updated date by the author of content?

# Answer
> 2 votes
Like Clive mentioned there is no good/easy way to prevent the node change timestamp from being updated, but as a possible alternative you could use node creation time instead:

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      global $user;
      if ($node->type == 'mynodetype' && !in_array('administrator', $user->roles)) {
        $node->created = time();
      }
      break;
  }
}

```

This implementation of hook\_nodeapi() would set the 'mynodetype' node creation time to the current time when a non-administrator saves it. You'll have to keep in mind that users can manually set the creation time when editing nodes and this will override it for non-administrators. It will also mean that in those cases the actual node creation time will be lost even if the user isn't modifying it.

# Answer
> 3 votes
You can't really, it's hard coded into the `node_save()` function with this bit of code:

```
$time = time();
if (empty($node->created)) {
  $node->created = $time;
}

// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

```

Short of implementing your own node form which bypasses `node_save()` there's not really much you can do (except hacking the core node.module file which is never advised).

# Answer
> 2 votes
```
<?php if (($logged_in)&&($user->uid != "1")): ?>
<?php print $submitted; ?>
<?php endif; ?>

```

# Answer
> 1 votes
In order to prevent changes to nodes by administrators from updating the `changed` date, you can make a module with the following code. The way this works is when an administrator saves a node, the new changed date is replaced with the old changed date.

```
<?php

/**
 * Implements hook_node_presave().
 * @param $node
 */
function YOURMODULE_node_presave($node) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    $node->changed = $node->original->changed;
  }
}

```

The above code will prevent the date from updating on all node types. If you only want this to apply to specific node types, try something like the code below. You might want to extract the $types array into a module configuration form.

```
<?php

/**
 * Implements hook_node_presave().
 * @param $node
 *
 * Add node types to $types array to freeze their changed date.
 */
function YOURMODULE_node_presave($node) {
  $types = array(
    'your_node_type',
    'node_type_2'
  );
  if (in_array($node->type, $types)) {
    $node->changed = $node->original->changed;
  }
}

```

# Answer
> 1 votes
In Drupal 9 (and a while before), the changed field of the node entity is of type ChangedItem (see `BaseFieldDefinition::create('changed')` in Node.php).

In Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem, you'll find the following:

```
public function preSave() {
    parent::preSave();
    ...
      if (!$entity->isNew() && $original && $original->hasTranslation($langcode)) {
        $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
          $this->value = REQUEST_TIME;
        }
      }
    }

```

So, if you change the changedTime in hook presave of your content type to +1 second, the change timestamp will stay "about" the same...

This is what I do in my hook preSave:

```
if (Drupal::currentUser()->id() == 1) {
      $this->setChangedTime($this->original->getChangedTime()+1); // +1 sek. fakes ChangedItem to not fire update
    }

```

Then it won't appear in like "changed recently" lists at my pages.

---
Tags: 6, theming, nodes
---


# Question
Title: Complex conditional logic for Webform field in YAML format
I have a complex scenario in Webforms, where field #states depends on multiple OR / AND conditional logic.

For Example:

field\_d has a visibility condition where field\_a must be filled and either of field\_b or field\_c must be filled. I am not sure how to proceed with that kind of Yaml logic. I have tried something like below but it seems not to work.

field\_d has below conditional logic under field advance tab -

```
visible:

  ':input[name="field_a"]':
      filled: true

  and

  (
  ':input[name="field_b"]':
      filled: true

  or

  ':input[name="field_c"]':
      filled: true
  )

```

Thanks.

# Answer
Nested states can be tricky. Make it two conditions:

```
visible:
  - ':input[name="field_a"]':
      filled: true
    ':input[name="field_b"]':
      filled: true
  - or
  - ':input[name="field_a"]':
      filled: true
    ':input[name="field_c"]':
      filled: true

```
> 2 votes

---
Tags: webforms
---


# Question
Title: How to use a RedirectResponse with a # (hash)?
I have this code:

```
$event->setResponse(new RedirectResponse(base_path().'mypage#actions_clicker'));

```

It redirects to /mypage, but it doesn not include the #actions\_clicker part. How do I make Drupal not loose the hash / # part?

# Answer
> 1 votes
Try url encoding the `#` fragment. so it becomes `%23`, e.g:

```
$event->setResponse(new RedirectResponse(base_path().'mypage%23actions_clicker'));

```

**Update:**

Check the browser header to see that the fragment is passed. In my local testing it was ok:

**Sample code to append fragment to redirect response.**

```
return new RedirectResponse($redirect_url . '#test', 301);

```

More info: https://stackoverflow.com/a/2305927/583715

# Answer
> 0 votes
Old question, but if it helps someone :

```
$event->setResponse(new RedirectResponse(Url::fromUri('mypage', ['fragment' => 'actions_clicker'));

```

Or with a route :

```
RedirectResponse(Url::fromRoute('entity.node.canonical', ['node' => $node->id()], ['fragment' => 'my-anchor'])->toString());

```

Note: `Url` is from namespace `\Drupal\Core\Url`

---
Tags: 8, redirection
---


# Question
Title: How can I create a view of the first entityreferenced child item from a multifield for a list of parent nodes via views UI?
I have a node type A containing a multifield of entityreferences to another node type B and using only the views admin interface I want to create a list of the first type B child entityreference on every node of type A.

I think its possible just can't quite figure out how to do it.

Thanks

# Answer
We usually name the referencing nodes Children, and referenced nodes Parents (Children reference Parents), so I'll assume it applies here that you want to show the first Parent in a multivalue ER field.

You need to create a list of type A nodes in a Block Display, add the ER field and select to show only the one, first value under Multivalue settings for the field.

This will give you a list of A-type nodes that shows only the first B reference.

Now we need to filter out only the A node that we're currently viewing. This can be done through the `ID` Contextual filter (under `Advanced` View settings), configure it:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS in the URL or a default is provided`
**Specify validation criteria**
Validator: **Content**
Content type **A**
Set the option for the case when the argument doesn't validate, and all the other options, to something that makes sense to you.

When you add the Contextual filter, depending on what option you chose for when the argument doesn't validate, you may see no results any more. To bypass the Contextual filter enter `all` into the Preview field (unless you change that default).

You can test the Contextual filter with Views Preview. Enter the node ID of the A node into the Preview field. You should see only the one result in Views, the result relating to the A node with the ID you entered.

If you're seeing expected results save the Views and place the Block into a theme region, but don't forget to set the Context option on Block configuration too.
> 0 votes

---
Tags: views, entities
---


title: Block the node which I am currently in

text:
# Question
Title: Block the node which I am currently in
I am discovering one problem on my page - as a content I have some recipe. Under it, I've created a block which is displaying "Simular recipes". And now, this block is displaying some simular recipes AND the one which is in the content page above. So, I would like to ask if someone can help me how to do filtering to make this block not showing me the recipe which is in the page. Basically, need to block the node which I am currently in. Thanks in advance.

# Answer
> 3 votes
I'm assuming the Block you're using is a Views Block.

You can filter out the current node with the `ID` Contextual filter (under `Advanced` Views settings) from the "Content" Category with these settings:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS in the URL or a default is provided`
**Specify validation criteria**
Validator: **Content**
Content type **recipe**
Set the option for the case when the argument doesn't validate to something that makes sense to you.
`More`
**Exclude**

The last section of settings (`More`) is where you have the Exclude option that makes the selection of the Contextual filter and reverses it, so it finds the ID of the current node, and excludes it from the list.

Test it by entering a node ID into the Preview field in Views, the node with the entered ID should be removed from the Views results.

You also need to select the Contextual option in the Block configuration or it won't work when you place the Block on pages, Views Preview can't test the Contextual works in actual placement.

---
Tags: views, nodes, blocks
---


# Question
Title: How can I watermark images with a taxonomy term from the node they belong to?
I'm working on a site for a business who would like to watermark all their product photos with the brand name of the product (which is a taxonomy term reference field on the product content type).

Looking into this, I found a variety of modules that will watermark images in various ways, but most expect to just put a single image or text overlay on all images of a given style, which is not what I need here.

The one exception I found was Textimage, which works with the Image Effects module and, at least in theory, supports node tokens. But when I tried out those two modules, I was unable to get any token for the taxonomy field in question to work. I tried \[node:field\_brand\] and \[node:field\_brand:entity:name\] without success — it just put the text of the token instead of replacing it with the brand. Other tokens, like \[node:title\], did work, but not the one I wanted (even though it was in the list of available tokens).

I posted to the issues queue for Textimage, but it doesn't seem like anyone's monitoring it regularly, and I'm on a deadline.

Does anyone know either how I can get the node replacement to work in Textimage, or alternatively any other way of doing this? I'm not at all wedded to Textimage and Image Effects — they're just the only modules thus far that claim to be able to do what I need to do.

# Answer
> 0 votes
Problem solved — Rainer Feike's comment prompted me to examine the field setup and I realized I had made an error in the way I set it up that was causing the token not to resolve (there were two taxonomy fields on the original product content type, referencing two different vocabularies, and I had matched the wrong field name with the vocabulary in setting up the test content type I was trying out the new image style on).

Once I corrected that it worked. My apologies for posting about what turned out to be a self-created problem.

---
Tags: tokens
---


# Question
Title: IF statement to check if loaded entity is of type
In my module (fork of ECK Clone) I'm trying to set a default value when an entity of type "Course" is cloned.

### Currently I do:

```
function eck_clone_clone_entity($entity, $account = FALSE) {

  $original_entity = clone $entity;

  $entity->id = NULL;

  if ($account && isset($entity->uid)) {
    $entity->uid = $account->uid;
  }

  if (isset($entity->created)) {
    $entity->created = NULL;
  }

  if (isset($entity->changed)) {
    $entity->changed = NULL;
  }

  if (isset($entity->title)) {
    $entity->title = t('Clone of !title', array('!title' => $entity->title));
  }

  $entity->status = 1;
  $entity->some_boolean = 1;
  $entity->content_status = 1164;

  $context = array('original_entity' => $original_entity);

  drupal_alter('clone_eck', $entity, $context);

  entity_save($entity->type, $entity);

  return $entity;
}

```

*PS: some\_boolean value gets set, but not the status. I wonder why.*

What I need is to check if the $entity is of the type "Course". I thought it would be as simple as wrapping it in an if statement like so:

```
if($type == 'course') {
    $entity->some_boolean = 0;
    $entity->content_status = 665;
    $entity->course_number = 3;
    $entity->tag_line = "some other tag line here";
  }

```

But that doesn't work. Any idea? PS: some\_boolean value gets set, but not the status.

# Answer
Like @Kevin pointed out, $type was never set. That was helpful.
I believe this works:

```
if($entity->type == 'course') {
  $entity->some_boolean = 0;
  $entity->content_status = 665;
  $entity->course_number = 3;
  $entity->tag_line = "some other tag line here";
}

```

If you can improve this, please let me know. Much appreciated.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I modify the Quick Edit Module to have a better UX for end-users?
For a current project I'm working on we're trying to leverage the "In Place Editor" functionality provided by the Quick Edit module.

Our main goals are to:

1. Have a module that allows us to perform Create Update and Delete options in-line on only fields that needs the functionality.
2. Make it so that there is a single visible button which says "Edit" on some content that is always used to enter the "In Place Editing" mode.

Instead, the Quick Edit module provides us with:

1. Quickedit on any and all fields that are editable by the user.
    * This works really well for site and content adminstrators, but, our target audience is the end-user of the site.
2. A contextual link (a pencil icon by default) which you must first click. This link then shows a menu for options "Quick Edit", "Edit", "Delete" (and any others that have been placed by modules hooking into the Contextual module).

Clicking "Quick Edit" then simply enables the ability to edit in line. At which point, you still have to click on a field within the context in order to get the field to appear as an editable form input (and it's not immediately obvious that's an available option).

What is the best way to go about achieving a slightly more stream-lined, end-user oriented, in place editing system in drupal 8?

tl;dr

Drupal gives me this:

I'd like this instead:

# Answer
> 1 votes
You can check https://www.drupal.org/project/simpler\_quickedit to do exactly what you need

---
Tags: 8, navigation, entities
---


# Question
Title: Conditional Show/Hide Child Terms on Edit Page
I have a content type with a term reference. The terms have child terms. On the admin editing side, I want to show only top level terms until selected, then show only the child terms for that parent.

This to prevent having a ginormously long field.

```
Parent 1
  Child 1
  Child 2
Parent 2
  Child 3
  Child 4
Parent 3
...

```

When a user edits a piece of content, I want to only show the parent terms initially. Then show/hide the child terms when the parent is checked.

```
Parent 1
Parent 2 (checked)
  Child 3
  Child 4
Parent 3
Parent 4
...

```

I've used conditional fields, state API, and select (other) modules. But this is showing and hiding children on the same field. So it's a bit different.

Anyone have any advice for this scenario?

# Answer
> 1 votes
Off the top of my head, I would say that you can do this more cleanly with two `'#type' => 'select'` elements.

The first one would just contain the parent terms.

The second one would be set to

```
'#states' => [
  'disabled' => [
    ':input[name="parent_term"]' => ['value' => ''],
  ],
],

```

Then you could use Drupal Form API `#states` to conditionally set the value of the second select element to the appropriate child terms, depending on which parent term is selected.

The most obvious alternative approach would be some hacky JavaScript.

# Answer
> 1 votes
Well, I went the following route. If someone knows a better/cleaner way, let me know. Otherwise this works pretty well.

My field referencing the taxonomy: `field_categories` .

## Preprocess Form

First I'm adding an extra class via hook\_preprocess\_form\_element. I don't love that I have to load each term, but it's only for admin pages.

```
/**
 * Implements hook_preprocess_form_element().
 */
function admin_helper_preprocess_form_element(&$variables) {
  if ($variables["element"]["#type"] == 'checkbox') {
    $tid = $variables["element"]["#attributes"]["value"];

    // Check if term has parents.
    $parents = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);

    // If parents exist, add classes.
    if (!empty($parents)) {
      $key = array_key_first($parents);
      $variables['attributes']['class'][] = 'child-term--' . $parents[$key]->id();
    }
  }
}

```

## Javascript

Then my not-too-hacky javascript. I could probably combine some of this and clean up a bit. But again, this is just for one content type on the admin side.

```
(() => {
  const parents = document.querySelectorAll('[id^="edit-field-categories"] input');

  [].forEach.call(parents, el => {
    const id = el.value;
    const children = document.querySelectorAll(`.child-term--${id}`);

    if (el.checked) {
      [].forEach.call(children, el => {
        el.style.display = 'block';
      })
    } else {
      [].forEach.call(children, el => {
        el.style.display = 'none';
      })
    }
  });

  [].forEach.call(parents, el => {
    el.addEventListener('click', (e) => {
      const id = e.currentTarget.value;
      const children = document.querySelectorAll(`.child-term--${id}`);

      if (el.checked) {
        [].forEach.call(children, el => {
          el.style.display = 'block';
        })
      } else {
        [].forEach.call(children, el => {
          el.style.display = 'none';
        })
      }
    });
  });
})();

```

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


# Question
Title: I can't filter the child view based on a value from the parent view
I have read many of the questions asked on this site, but none of them suited my problem. What is the need to make a Users view that shows below its created contents.

I have a website with 3 roles. Each role has the permission to create a content type. Users of the "Truckers" role can create nodes whose type is *Trucks*. The *Username* value is automatically added to a field, in order to identify which truck driver that truck belongs to. That field is an entity reference.

I need to create a view that shows users of the *Truckers* role and the trucks which belong to them. I created 2 views. One of them, based on the *Trucks* content type, lists the trucks, and among other fields, shows the *Username* of the truck driver who created it; the other one, based on *Users*, lists the users who have the *Truckers* role.

Using *Views field view*, I added the *Trucks* view as a field inside the *Truckers* view. However, I didn't find any combination of contextual filters, relationships, etc. that gives the desired result.

In the second image, you can see that the *Trucks* view is shown below each user of the *Truckers* role, but it shows all trucks, not just those created by the trucker.

>

>

I am not a programmer. How could I achieve the result I need? Is there a contextual filter, relationship, that I need to set? They have many options and I do not understand all of them correctly and in depth.

I am using Drupal 8.9.13 and Views field view 8.x-1.0-beta3.

# Answer
> 1 votes
You should be able to accomplish this with one view. I don't think views field view is necessary.

Add a view that shows Users

In the Filter Criteria section filter it by role (trucker).

Under Advanced use the Relationships dropdown to add the relationship Content Authored.

In the Fields section add a field to show whatever field of the trucks content type you want to show for each trucker (e.g. truck name). You could also use title. This field setting will use the "node" relationship which is available as a result of adding Content Authored in the relationships dropdown in the advanced section.

If you do use title instead of something like truck name, or any field that appears in multiple content types, in the Filter Criteria section be sure to add a "content type" filter in order to restrict results to the trucks content type.

Format the results as you like (e.g. table, etc.).

---
Tags: 8, views
---


# Question
Title: How to create a new parent section on the Configuration page?
When one navigates to **Manage » Configuration**, the page is divided into sections which (in the "Seven" theme at least) shows up in individual boxes. These sections have headings like "People", "Content authoring", "Development", etc.

I am able to create a settings form and place this inside any of the existing sections on the configuration page by associating it with the `parent` key in `hello_world.links.menu.yml`.

Example:

```
hello_world.greeting_form:
  title: 'Salutation settings'
  description: 'Configure the salutation message.'
  route_name: hello_world.greeting_form
  parent: system.admin_config_development

```

This places a link to the settings form for the "Hello World" module in the "Development" section. This is not where I want to place it.

Instead, I want to create a new section named "Examples", place this new section along with the others on the "Configuration" page, and make this new section the parent of my link to the settings form.

Below is an image of what I want it to look like. There should be a new section, named "Examples" as the section heading, and in that section, there should be a link to the settings form with the text "Salutation settings":

# Answer
The yaml-files that do this for the core is located in `core/modules/system/`. I eventually solved it by copying and adapting the relevant bits from `system.routing.yml`and `system.links.menu.yml`.

First, in `hello_world.routing.yml`, set up the routings we shall need:

```
hello_world.admin_config_examples:
  path: '/admin/config/examples'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Examples'
  requirements:
    _permission: 'access administration pages'

hello_world.greeting_form:
  path: '/admin/config/examples/salutation-configuration'
  defaults:
    _form: Drupal\hello_world\Form\SalutationConfigurationForm
    _title: 'Salutation configuration'
  requirements:
    _permission: 'administer site configuration'

```

Then, in `hello_world.links.menu.yml`, set up menu items. First the item that is going to be link to the section, and then the the menu item that links to the settings form:

```
hello_world.admin_config_examples:
  title: 'Examples'
  route_name: hello_world.admin_config_examples
  parent: system.admin_config
  weight: 0
hello_world.greeting_form:
  title: 'Salutation settings'
  description: 'Configure the salutation message.'
  route_name: hello_world.greeting_form
  parent: hello_world.admin_config_examples

```
> 2 votes

# Answer
Here is a way to do it.

#example\_codes.links.menu.yml

```
example_codes.base:
  title: 'Example Codes Module'
  parent: system.admin
  description: 'A Module with various Examples.'
  route_name: example_codes.base
  weight: 0

```

You need to define `system.admin` as parent.

And in your routing.yml should contain this base route.

#example\_codes.routing.yml

```
example_codes.base:
  path: '/admin/examples-codes'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Example Codes Module'
  requirements:
    _permission: 'administer example codes configurations'

```
> 1 votes

---
Tags: forms, 9
---