# Question
Title: How to automatically flag entities once (without PHP error)?
I created a custom module to automatically flag new entities and update entities. It works :-)

**Here is the problem :**

If I update a neud it is flagged. Perfect that's what I want to do, but if I update the node again, I get a PHP error. This is normal because the custom module tries to flag an already flagged node.

I have the same problem for all entities.

How to fix this ? I am completely stuck with this problem.

Here are the error messages in the logs :

```
Type    php
Date    Dimanche, 20 septembre, 2020 - 17:43
Utilisateur Mathieu
Emplacement https://dev.exemple.com/fr/node/360/edit
Référent    https://dev.exemple.com/
Message Drupal\Core\Entity\EntityStorageException : The user has already flagged the entity with the flag. dans Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (ligne 846 de /var/www/www-exemple-com/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Severity    Erreur

```

and

```
Type    nœud
Date    Dimanche, 20 septembre, 2020 - 17:43
Utilisateur Mathieu
Emplacement https://dev.example.com/fr/node/360/edit
Référent    https://dev.example.com/
Message LogicException : The user has already flagged the entity with the flag. dans Drupal\flag\FlagService->flag() (ligne 253 de /var/www/www-example-com/web/modules/contrib/flag/src/FlagService.php).
Severity    Erreur

```

Here is the code for my custom module :

```
<?php

/**
 * @file
 * Holds hook implementation for the Admin Task Notify module.
 */

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_user_insert() and hook_user_update().
 */
function admin_task_notify_user_insert(User $account) {
  $flag_id = 'moderate_user';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_admin = \Drupal\user\Entity\User::load(1);
  $flag_service->flag($flag, $account, $user_admin);
}

function admin_task_notify_user_update(User $account) {
  $flag_id = 'moderate_user';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_admin = \Drupal\user\Entity\User::load(1);
  $flag_service->flag($flag, $account, $user_admin);
}

/**
 * Implements hook_store_insert() and hook_store_update().
 */
function admin_task_notify_commerce_store_insert(Store $commerce_store) {
  if ($commerce_store->bundle() == 'ephemere' || $commerce_store->bundle() == 'personnel' || $commerce_store->bundle() == 'professionnel') {
    $flag_id = 'moderate_store';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $commerce_store, $user_admin);
  }
}

function admin_task_notify_commerce_store_update(Store $commerce_store) {
  if ($commerce_store->bundle() == 'ephemere' || $commerce_store->bundle() == 'personnel' || $commerce_store->bundle() == 'professionnel') {
    $flag_id = 'moderate_store';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $commerce_store, $user_admin);
  }
}

/**
 * Implements hook_product_insert() and hook_product_update().
 */
function admin_task_notify_commerce_product_insert(Product $commerce_product) {
  if ($commerce_product->bundle() == 'produit' || $commerce_product->bundle() == 'service') {
    $flag_id = 'moderate_product';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $commerce_product, $user_admin);
  }
}

function admin_task_notify_commerce_product_update(Product $commerce_product) {
  if ($commerce_product->bundle() == 'produit' || $commerce_product->bundle() == 'service') {
    $flag_id = 'moderate_product';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $commerce_product, $user_admin);
  }
}

/**
 * Implements hook_group_insert() and hook_group_update().
 */
function admin_task_notify_group_insert(Group $group) {
  if ($group->bundle() == 'personnel' || $group->bundle() == 'professionnel') {
    $flag_id = 'moderate_group';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $group, $user_admin);
  }
}

function admin_task_notify_group_update(Group $group) {
  if ($group->bundle() == 'personnel' || $group->bundle() == 'professionnel') {
    $flag_id = 'moderate_group';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $group, $user_admin);
  }
}

/**
 * Implements hook_node_insert() and hook_node_update().
 */
function admin_task_notify_node_update(Node $node) {
  if ($node->bundle() == 'annonce' || $node->bundle() == 'article' || $node->bundle() == 'demande' || $node->bundle() == 'discussion' || $node->bundle() == 'evenement' || $node->bundle() == 'itineraire' || $node->bundle() == 'recipe') {
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $user_admin);
  }
}

/**
 * Implements hook_comment_insert() and hook_comment_update().
 */
function admin_task_notify_comment_insert(Comment $comment) {
  if ($comment->bundle() == 'annonce' || $comment->bundle() == 'article' || $comment->bundle() == 'demande' || $comment->bundle() == 'discussion' || $comment->bundle() == 'evenement' || $comment->bundle() == 'itineraire' || $comment->bundle() == 'recipe' || $comment->bundle() == 'produit' || $comment->bundle() == 'service') {
    $flag_id = 'moderate_comment';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $comment, $user_admin);
  }
}

function admin_task_notify_comment_update(Comment $comment) {
  if ($comment->bundle() == 'annonce' || $comment->bundle() == 'article' || $comment->bundle() == 'demande' || $comment->bundle() == 'discussion' || $comment->bundle() == 'evenement' || $comment->bundle() == 'itineraire' || $comment->bundle() == 'recipe' || $comment->bundle() == 'produit' || $comment->bundle() == 'service') {
    $flag_id = 'moderate_comment';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $user_admin = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $comment, $user_admin);
  }
}

```

# Answer
```
$flag_status = $flag_service->getFlagging($flag, $comment, $user_admin); // get flag status
if (!$flag_status) { // if not TRUE, is FALSE, not flagged
  $flag_service->flag($flag, $comment, $user_admin);
}

```
> 2 votes

---
Tags: 8, entities, flags
---


# Question
Title: How do I flag new user accounts or updated accounts?
I created a custom module to automatically flag new user accounts and updated accounts. When I create a new user or update an existing account, it is not automatically flagged and there is no error message in the log.

How do I flag new user accounts or updated accounts?

This is the code I am using in the custom module.

```
use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_user_update().
 */
function admin_task_notify_user_update(User $account) {
  $flag_id = 'moderate_user';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_admin = \Drupal\user\Entity\User::load(1);
  $flag_service->flag($flag, $account, $user_admin);
}

```

# Answer
> 1 votes
```
/**
 * Implements hook_form_alter()
 */
function admin_task_notify_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_form') { // check is user form
    $form['actions']['submit']['#submit'][] = 'admin_task_notify_flag_user'; // adds custom handler
  }
}

function admin_task_notify_flag_user(&$form, \Drupal\Core\Form\FormStateInterface $form_state) { // the custom handler
  $flag_id = 'moderate_user';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_admin = \Drupal\user\Entity\User::load(1);
  $user_to_flag_uid = $form_state->getValue('uid');
  $user_to_flag = \Drupal\user\Entity\User::load($user_to_flag_uid);
  $flag_status = $flag_service->getFlagging($flag, $user_to_flag, $user_admin); // get flag status
  $is_admin = $user_to_flag->hasRole('administrator');
  if (!$flag_status && !$is_admin) { // if flag not TRUE, is FALSE, not flagged and user is not admin
    $flag_service->flag($flag, $user_to_flag, $user_admin);
  }
}

```

---
Tags: 8, users, flags
---


# Question
Title: "Order items" view displaying removed items (variations)?
I'm dynamically removing items from cart with this function:

```
  static function _remove_product_variation_from_cart($variationId) {
    $orders = \Drupal::service('commerce_cart.cart_provider')->getCarts();
    if (empty($orders)) {
      return 0;
    }
    $items = reset($orders)->getItems();

    foreach ($items as $item) {
      $quantity = $item->getQuantity();
      $itemVariationId = $item->getPurchasedEntity()->id();
      if ($variationId == $itemVariationId){
        foreach ($orders as $order) {
          $order->removeItem($item)->save();
        }
        return $quantity;
      }
    }
    return 0;
  }

```

And during checkout process it's all fine - removed items are not displayed. But page:

```
/user/user_id/orders/order_id

```

is listing also removed items (that's view "Order items"). Sum (order total) is correct however. On other hand i.e. view "Checkout Order Summary" is returning order items correctly (without removed ones).

Am I removing cart item wrong way or something? Why is this happening?

# Answer
```
foreach ($items as $item) {
  $quantity = $item->getQuantity();
  $itemVariationId = $item->getPurchasedEntity()->id();
  if ($variationId == $itemVariationId){
    foreach ($orders as $order) {
      $cart_manager = \Drupal::service('commerce_cart.cart_manager');
      $cart_manager->removeOrderItem($order, $item);
    }
    return $quantity;
  }
}
// return 0; <-- not necessary, functions don't have to always return.

```
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How to allow users to 'add' values to a multi-value field but not edit any previously add values?
I have a field called 'Remarks' on an ECK entity (not a node) and Role A is allowed to leave remarks but I don't want them to edit previous remarks, I just want to give them the option to add one. Note: they are not the author or owner of the entity. Right now, I use an Edit Page Variant for this entity that they have access to and where this form for 'field\_remarks' appears. The problem is that the previously added remarks are still showing up and therefore now they can still edit someone else's remarks.

## potential solution 1

I would probably be possible to hide the fields that already contain values with jQuery but that is not really the Drupal way, I believe.

## potential solution 2

Could it possibly be done with a Rules component that adds the value (text) to this field programmatically? And if so, how and where to show a text field that would accomplish that?

# Answer
> 1 votes
You can programmatically disable them in module like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'eck__entity__form_edit_ENTITY_NAME_BUNDLE_NAME') {
     $lang = $form['field_name']['#language'];
     foreach ($form['field_name'][$lang] as $key => $value) {
       if (is_numeric($key) && !empty($value['value']['#default_value'])) {
         $form['field_name'][$lang][$key]['value']['#disabled'] = TRUE;
       }
     }
   }
}

```

## Result

# Answer
> 0 votes
## Answer Using jQuery:

Like so we can check which fields have contain a something (a value).

```
$( "table#field-remarks-values > tbody > tr textarea" )
.not( "textarea:empty" )
.parentsUntil("tbody")
.addClass("hidden");

```

Maybe a better way is to remove them entirely:

```
$( "table#field-remarks-values > tbody > tr textarea" )
.not( "textarea:empty" )
.parentsUntil("tbody")
.remove();

```

This may be more difficult to bring them up again if at all.

It's a solution that works for now but not the best solution in my opinion.

---
Tags: 7, rules
---


# Question
Title: Custom block build function to display wysiwyg body text
I am learning to build custom blocks through a module. I am trying to get the build() function to work. I have the code and it works. However, if I edit the configuration of the block as a user it does not print the text in the text formatter.

```
'#markup' =>
    '<div>' . $this->t('Body: @body', ['@body' => $this->configuration['body']]) . '</div>',

```

In the rendered block on the page it prints... Body: But not the text in the wysiwyg.

Any ideas how to get that to work. The tutorials and links I am finding are not relavant.

# Answer
Assuming you store the block configuration via a `text_format` form element as in https://drupal.stackexchange.com/a/278811/47547

*src/Plugin/Block/ExampleBlock.php*

```
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides an example block.
 *
 * @Block(
 *   id = "mymodule_example",
 *   admin_label = @Translation("Example"),
 *   category = @Translation("mymodule")
 * )
 */
class ExampleBlock extends BlockBase {

  public function blockForm($form, FormStateInterface $form_state) {
    $body = !empty($this->configuration['body']) ? $this->configuration['body'] : [];
    $form['body'] = [
      '#type' => 'text_format',
      '#title' => 'Body',
      '#format' => isset($body['format']) ? $body['format'] : 'full_html',
      '#default_value' => isset($body['value']) ? $body['value'] : '',
    ];
    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['body'] = $form_state->getValue('body');
  }

```

You would output the wysiwyg content via `processed_text`:

```
  public function build() {
    $build = [
      '#type' => 'container',
      'label' => ['#markup' => 'Body: '],
    ];
    if (!empty($this->configuration['body'])) {
      $build['body'] = [
        '#type' => 'processed_text',
        '#text' => $this->configuration['body']['value'],
        '#format' => $this->configuration['body']['format'],
      ];
    }
    return $build;
  }

}

```
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: Pathauto bulk update for taxonomy terms with unchecked “Generate automatic URL alias”
I have the same issue addressed for D7 here: Bulk Generating URL aliases for taxonomy terms doesn't do anything or here: Bulk update for unchecked "Generate automatic URL alias"

And I'm looking for a corresponding workaround for D8, querying the DB directly.

For D7 seems that the following solution works:

```
UPDATE pathauto_state SET pathauto="1" WHERE entity_type="taxonomy_term";

```

I did some research for D8:

1. cannot find any "pathauto\_state" table within a D8 database
2. so I tried to find how and where the “Generate automatic URL alias” is stored but without success (see also for this: Where is the "Generate automatic URL alias" setting stored?)

Thank you

# Answer
> 0 votes
As I know there is no simple SQL query to update "Generate automatic URL alias" status for nodes and terms for Drupal 8.

Data contained in table `key_value` but I don't think it's possible to use it directly.

---
Tags: 8, taxonomy-terms, path-aliases
---


# Question
Title: How to create Media video youtube entity programmatically?
I have Youtube URL such as: https://www.youtube.com/watch?v=asddasOds32

I need to create Media video youtube entity programmatically.

Can I have some example code to solve this task?

# Answer
Code example:

```
use Drupal\media\Entity\Media;

$media = Media::create([
  'bundle'      => 'my_youtube',
  'uid'         => 1,
  'name'        => 'my_video',
   'field_media_oembed_video' => [
    'value' => 'https://www.youtube.com/watch?v=iZ53oOOTsdc',
   ],
]);

$media->save();

```
> 2 votes

---
Tags: 8, media
---


# Question
Title: What is the replacement for menu_link_load()?
Drupal 7 has menu\_link\_load() to load a single menu item. What is the Drupal 8 equivalent?

# Answer
> 2 votes
Drupal 8 menu links are now content entities. The equivalent to loading a D7 menu link object would be loading a `MenuLinkContent` entity. This can be done via the static `Drupal\menu_link_content\Entity\MenuLinkContent::load()` method.

# Answer
> 2 votes
It should be considered good practice to rely on the **entity type manager** to load entities. First, the pattern is easy to remember and looks the same for any entity type. Just replace `menu_link_content` with `node` or `node_type` or whatever. Second, it supports the dependency injection container to be used in OOP code.

```
\Drupal::entityTypeManager()->getStorage('menu_link_content')->load($id);

```

Read Working with the Entity API for more info.

> Avoid using the static `Entity::load()` method in object oriented code. Instead use dependency injection to inject the entity type manager and load the entity with `$this->entityTypeManager->getStorage($entity_type)->load($entity_id)`. This ensures that the code is properly decoupled and can be unit tested.

Also this issue is a nice read as well: Node::load($nid) vs. \Drupal::entityTypeManager()-\>getStorage('node')-\>load($nid)

> Often I hear that `\Drupal::entityTypeManager()->getStorage('node')->load($nid)` should be used instead of `Node::load($nid)`. Is argued that using the later is not recommended. I've searched in the relevant doc page, issue or change record but none of them could give me a clue why one is the preferred way, than the other.

---
Tags: 8, navigation
---


title: How do I prevent node enumeration?

text:
# Question
Title: How do I prevent node enumeration?
I am currently developing a Drupal 8 site that will consist of one only central content type with a minimal menu structure. The user is supposed to navigate the site only by using a search/filter form (similar to a search engine) and I would like to disallow all methods for locating content other than using the search form.

The problem is: All content in Drupal is normally accessible by using `<site>/node/<somenumber>`, which makes it easy to locate all content by simply counting upwards (I think, this process is called **node enumeration**). I know, I can use the `Pathauto` module to generate a pattern for URL aliases (say, a random hash). Unfortunately, that won't prevent the original URLs from being accessible: When entered, they will simply be forwarded to the generated aliases.

So, my question is: Is there a way to prevent this node enumeration from being possible? Is it possible to have the node available **only** under the generated aliases and not forward the original URLs?

All help would be much appreciated.

# Answer
This is difficult, because it is core functionality. What you could do to prevent people from checking node/4, node/5 etc is blocking access when a url request has a certain structure. You'd need a custom module with an EventSubscriber.

Here is an example how to intercept such url requests and how to redirect them. In this case it is a taxonomy term view but the underlying thought is the same: https://stefvanlooveren.me/blog/redirect-taxonomy-terms-filtered-view-page

Further, you'd have to check in your html rendering that every reference to a node id is hidden. Quite some work but if it is really necessary its possible.
> 2 votes

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


# Question
Title: Override of commerce-order-receipt.html.twig template not working?
My theme is using Bootstrap barrio theme (bootstrap\_barrio) as a base theme. I'm trying to override Drupal commerce template `modules/contrib/commerce/modules/order/templates/commerce-order-receipt.html.twig` and it's not working for me. Even I copied that file to drupal/web/themes/my\_theme/templates ,cleared the cache, Commerce is still using original template file from commerce module.

What puzzles me is that base Barrio theme also has that template and it's also not used?!?

Do I have to set somewhere what theme should be used for email templates or something? Overriding other modules templates (including commerce templates) works fine. Documentation says "The email can be customized by overriding the Twig template in your theme just as you would any other template".

# Answer
Figured out what was the problem. I had to select my theme for sending emails on

**Configure the Mail System** admin page.

/admin/config/system/mailsystem

Other way some other theme is used.
> 5 votes

---
Tags: theming, commerce
---


# Question
Title: How can I use #tags in pager_default_initialize()?
I want different label for first/last/next/previous button in the custom navigation using pager\_default\_initialize(). How I can set an array that can change the button label.

```
$total_count =9999;
$page = pager_default_initialize($total_count, 30,$tags );
$pager = [
  '#type' => 'pager',
];

```

This give a pagination like :

```
« First ‹ Previous 1 2 3 4 5 6 7 8 9 … Next › Last »

```

I want pagination like :

```
« pratham ‹ pichhala 1 2 3 4 5 6 7 8 9 … aage › antim »

```

# Answer
> 0 votes
Simply copy `core/modules/system/templates/pager.html.twig` to `themes/custom/MYTHEME/templates/page.html.twig` and rename the labels. Flush cache. Twice.

If they are still English leave the `|t` or if they are in a language other than English remove the `|t` and note that they then ain't translatable anymore.

You should have found out about the location of the exact template in use when you enable Twig debugging. You then can inspect the name and location of the current template as HTML comments directly in the markup in your browser.

---

Alternatively use a preprocess hook to rename the labels dynamically:

```
/**
 * Implements template_preprocess_pager().
 */
function MYTHEME_preprocess_pager(&$variables) {
  if ($variables['items']['first']) {
    $variables['items']['first']['text'] = t('Yeah first page');
  }
  if ($variables['items']['previous']) {
    $variables['items']['previous']['text'] = t('Yeah previous page');
  }
  if ($variables['items']['next']) {
    $variables['items']['next']['text'] = t('Yeah next page');
  }
  if ($variables['items']['last']) {
    $variables['items']['last']['text'] = t('Yeah last page');
  }
}

```

---
Tags: 8, theming
---


# Question
Title: Assign a row class like "row-1" for row 1, "row-2" for row 2
I have a view that uses the Table format.

I want to add row classes like this:

* Row 1: `.row1`
* Row 2: `.row2`
* Row 3: `.row3`

In the Views UI, if I click *Settings* under **Format: Table**, then I can specify the **Row class**. This field allows tokens, but I can't find a token that refers to the views row itself.

How can I implement a row class that assigns a number based on the position of the row in the view?

# Answer
> 1 votes
There are plenty of ways to go about this question, my suggestion is overriding twig templates.

You would need to override the Twig template for that view. If you enable debug, clear cache, inspect element, you will see the template for that view. Then for that twig file, just use the loop index

```
loop.index  The current iteration of the loop. (1 indexed)

```

to track which row you are in.

---
Tags: 8, views
---


title: New workflow can't select content type

text:
# Question
Title: New workflow can't select content type
I'm trying to create a new workflow in Drupal. When I click "Content Types" beneath the "This workflow applies to:" section, it loads an empty modal. I have 6 content types but they fail to show.

There is an existing workflow that has the correct content types set. However, if I uncheck one of them, it won't be available if I try to add it back later.

I made a new, test content type. It will show as an option for workflows but the older, existing options will not.

Does anyone have any ideas as to why the content types won't load inside of the workflow editor?

# Answer
> 0 votes
It seems each content type can only be assigned to one workflow at a time.

Try removing removing a content type from the other working workflow, save it, and then adding it to the new workflow.

---
Tags: nodes
---


# Question
Title: Trigger Crop API programatically after node is created
Hi I am using Image Widget Crop so that users can crop images according to predefined image styles. All would have worked fine without any issues had I been using Drupal in the conventional 'monolithic' way. But I am not. Instead, I have a headless Drupal setup.

That means that I do not have a Drupal theme to render my content. The problem created because of that is that apparently (from what I've read online), the actual styled images created using Image Widget Crop/Crop API are actually created when they are called/loaded in a theme. Now the theme can be backend as well. Below is what I think this happens chronologically.

1. Create and save a post with an image cropped using Image Widget Crop.
2. Cropped/styled image does not get created in the file system.
3. Fetch the data using JSON API/Custom API Module
4. Returns with empty image field because cropped/styled image is not yet created.
5. Click on Edit post
6. Cropped/styled image created. Because the preview of the cropped image is called by the edit form/backend theme.
7. Fetch the data using JSON API/Custom API Module.
8. All works fine.

What I want to do is execute some kind of hook which creates the styled/cropped image when a post is saved(step 1). That way when I fetch the data using JSON API, it is readily available.

# Answer
> 1 votes
The solution is using Image Style Warmer

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


# Question
Title: How do I verify emails on a contact form?
I want to implement a functionality where anonymous users can contact node authors. I have created a contact form with email field for each node. I would like to send an email verification link to the email address for email ownership confirmation. The form submit should be complete only when that happens.

What would be the best approach to handle this? There is a module in drupal 7 which could work but I didn't come across anything for D8. Will appreciate any help with this.

# Answer
> 1 votes
As LvB points out in its comment, you cannot really check email on-the-fly.

I think you should store the submission as moderated, send a confirmation email to the frontend user, and only follow-up the submission to the author when the user clicks the confirmation the email.

You'll get the same result which is only send confirmed contacts to author, like a to two-step confirmation. You could have a webform handler to manage the submission status. Check https://www.drupal.org/docs/8/modules/webform/webform-cookbook to start seeing what a webform handler could do.

There is a module under development to do so https://www.drupal.org/project/webform\_double\_opt\_in but hey, it's still beta.

# Answer
> 0 votes
For validating an email just use client side validation in that case. mdn form validation This will use the browsers checks for valid email and not send the form to you unless it’s valid.

For verifying an email I would say use Drupal accounts (that already has a superior methode for email verification.)

Btw. you can not check if email is valid at all. The protocols involved do not allow a check like that. What you can do is try and send a message and hope it arrives at the other end. This would be a (as suggested) double take. But whether you are allowed to do so is another matter (it could be considered spam by local law). Safest bet is to either require an account or to to not validate it at all. (Possibly with a block list). And remember, do not make the cure worse that the disease. A mail validation could do that (quite a few sales people found that out)

---
Tags: 8, emails
---


title: Get a session value in a template file

text:
# Question
Title: Get a session value in a template file
I am trying to get value set in session in a template file, but I don't get the expected value. I tried two methods, but neither of them works for me.

The code in the custom module controller is the following.

```
$xyz ='tets';
$session = \Drupal::request()->getSession();
//$session->set('xyz', $roles);
$session->set('abc', $xyz);

```

The code in the template file is the following.

```
{% set varname = app.session.get('abc') %}
{{ varname }}

```

I tried using the following code as well.

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

```

# Answer
I solved this by send session variable in theme template\_preprocess and then call the variable in the twig file.

template.theme :-

```
template_preprocess($variables){
   $session = \Drupal::request()->getSession();
   $variables['abc'] = $session->get('abc');
}

```

Call variable in twig file :-

```
{{ abc }}

```
> 0 votes

---
Tags: 8, sessions
---


# Question
Title: How can I alter a query adding an OR clause for a relational field?
I have an "Event" node type with a number of fields: title, date, location, description, etc.

Because a number of events are similar, we added a "Parent event" entity reference field. Child events inherit fields (e.g. location, description) from the parent, if set.

We have a block that displays all of the events for a location, using a contextual filter. The problem is that the child events have an empty location – it is inherited from the parent event when we render the event page.

How can I adjust the view query to select all events with *either* the contextual location ID, *or* with a parent that has the location ID?

# Answer
> 1 votes
My solution:

* Add a *relationship* for content referenced from the entity reference field.
* Add a *contextual filter* for the entity reference field, using the *content ID* from the URL as the value. This includes events that have the location set directly.
* Add a *contextual filter* for the entity reference field, using the *content ID* from the URL as the value, **using the relationship**. This includes events are related to an event that has the location set.

Unfortunately, the contextual filter WHERE group uses `AND` by default, so no results are returned, so we have to change the `type` in the WHERE clause.

```
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(ViewExecutable $view, Sql $query) {
  if ($view->id() === 'events') {
    if ($view->current_display === 'block_2') {
      $query->where[0]['type'] = 'OR';
    }
  }
}

```

If there are more contextual filters, you have to create a new OR where group with the fields, and remove them from group `0`.

```
$group0 = &$query->where[0];

// Create a new OR group.
$group_id = $query->setWhereGroup('OR');

// Copy the conditions to the new where group.
$query->addWhereExpression(
    $group_id,
    $group0['conditions'][1]['field'],
    $group0['conditions'][1]['value']
);
$query->addWhereExpression(
    $group_id,
    $group0['conditions'][2]['field'],
    $group0['conditions'][2]['value']
);

// Remove from group 0
unset($group0['conditions'][1]);
unset($group0['conditions'][2]);

```

---
Tags: 8, views
---


# Question
Title: Webform Status in Webform Submission Twig Template
I'd like to use the current open/closed status of a webform in a conditional on the webform-submission-information.html.twig. There is a "webform" variable available to use in the `template_preprocess_webform_submission_information` function, but all that seems to do is print a link to the webform. When I try to use the usual methods that I'd usually use on a webform object, I just get WSOD. Something tells me that variable isn't actually an object.

For example, perhaps I could get the webform id and use that to figure out the status of the webform...

```
$form = $vars['webform']['details']['nid']['#value'];

```

Also, is there a resource for figuring out the pathing to the API is for the Webform? The documentation exists on the Drupal site certainly, but it'd be a lot easier if there was some kind of resource that gave us the path to all these data endpoints. As it stands, even if I figured out the correct function for extracting the webform's ID, I wouldn't have any clue how to find the status (open/closed) endpoint. There are some old d7 articles and issues out there, but it'd be nice if we didn't have to rely on issues and, instead, if there was intuitive documentation.

# Answer
Indeed, calling `{{ webform }}` inside `webform-submission-information.html.twig` only contains a link. But since you have the `webform_submission` you can get the webform and from there can call `isOpen` and `isClosed`.

```
<div class="current-webform-status">
  <b>{{ 'Current Webform status'|t }}:</b> {{ (webform_submission.getWebform.isOpen) ? 'Open'|t : 'Closed'|t }}
</div>

```

or

```
<div class="current-webform-status">
  <b>{{ 'Current Webform status'|t }}:</b>
  {% if webform_submission.getWebform.isOpen %}
    {{ 'Open'|t }}
  {% else %}
    {{ 'Closed'|t }}
  {% endif %}
</div>

```
> 2 votes

---
Tags: 8, theming, webforms
---


# Question
Title: How can I prevent users from submitting URLs in textfields?
Is there any way to prevent URLs in the textfields and if present prevent the submission of the form? I was looking around the interface to figure this out. I was looking to check for `http` and `https` in the string.

There's seems to be a way to check for a pattern in the string... but to me it seems to be the exact opposite of what I need. It seems as if you can only check that the string needs to be there. But I want to check that it's not there. How can I do this?

I am on Drupal 8.9.1. and Webform is version 8.x-5.16.

# Answer
Edit webform element, under form validation, checkmark pattern.

Use a negative regular expression

Ex: `^(?!:https|http).*$`
> 3 votes

---
Tags: 8, webforms
---


title: What does vetted role mean?

text:
# Question
Title: What does vetted role mean?
I just read in drupal.org site this comment:

> A user who doesn't have the vetted role cannot become the only maintainer, or the project maintainer, of a project that opted into security coverage, in the same way a user without the vetted role cannot take over a project that opted into security coverage.

I tried to found what is this on the site without luck and I really don't have an idea.

Does somebody know what means vetted role in drupal.org?

# Answer
> 6 votes
In order for a Drupal contributed module to be eligible to be tagged as a security monitored project, one or more of the maintainers have to be 'vetted'.

Here is the main Drupal security policy on this. See the "Which Projects are covered" section. There is a link in this to the process of becoming 'vetted'.

Basically, you submit a Drupal.org project to a queue. Eventually, security community members will review it for use of best security practices, code quality, and some other stuff. If approved, the maintainer becomes 'vetted'. Unfortunately, this process can take a long time to happen.

Once you have a project approved and are 'vetted', any other projects you maintain can be labeled as covered by the security community.

# Answer
> 5 votes
I used the term *vetted role* because *vetted* is the term that appears in the user profile, to users that on Drupal.org have the *Git administrator* role.

>

In places listing the possible roles Drupal.org can have, *Git vetted user* is one of them.

>

Before the ability of opting into security advisory coverage was introduced, that role allowed users to create a full project; without that role, user were only able to create sandbox projects. That is when the *vetted* role was introduced.

Nowadays, the documentation speaks of being able to opt into security coverage, for example Apply for permission to opt into security advisory coverage or Security advisory process and permissions policy. The term *vetted* is still mentioned in those pages, but in *Security advisory process and permissions policy* it appears only once. (It's probable that most users would not catch what *vetted* means, nor they will notice that term.)

Today, users who want to apply to opt into security coverage for the projects they create are the ones going to get the *vetted* role. Those aren't the only users who have that role, though. The *vetted* role has been given to:

* Users who have asked for the permission to be able to create full project (and not only sandbox projects). Now every user, even the ones who don't have the *confirmed* role, can create full projects, but they still need the *vetted* role to opt into security coverage for the projects they create.
* Users who in the past asked for the permission to commit code into the Drupal.org CVS repository. Now Drupal.org uses Git (in particular an instance of Gitlab running on a drupal.org sub-domain), but the users who asked to be able to write in the Drupal.org CVS repository had the *vetted* role given them.

**Disclaimer**

I am one of the users who has reviewed the requests to get the *vetted* role since the time Drupal.org used CVS.

---
Tags: community-official-site
---


title: Create Custom Select Webform Element

text:
# Question
Title: Create Custom Select Webform Element
I asked this last time with 'Select Other', but I am still not understanding how to change custom element's type. In this scenario, I am attempting to build a Select type webform element. I am reusing the Webform Example attached to the webform module. But my issue is that I can not change it from an `<input>` to a `<select>` type.

Inside, `\webform_example_element\src\Element\WebformExampleElement.php` I have tried:

```
  public function getInfo() {
    $class = get_class($this);
    return [
      '#title' => $this->t('Facility'),
      '#type' => 'Select',
      '#input' => false,
    ...
   }

```

AND I have tried:

```
  public static function processWebformAssignedBy(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#tree'] = true;
    $element['#type'] = 'select';
    $element['#input'] = false;
    $element['#options'] = [
      '1' => 'One',
      '2' => 'Two',
    ];

```

Using X-Debug, when the page is loaded I get:

```
$element = {array} [48]
 #type = "select"
 #title = "current_facility"
 #multiple = false
 #access_create_roles = {array} [2]
 #access_update_roles = {array} [2]
 #access_view_roles = {array} [2]
 #webform = "generate_system_number_form_1_"
 #webform_id = "generate_system_number_form_1_--current_facility"
 #webform_key = "current_facility"
 #webform_parent_key = "net_new_process_information"
 #webform_parent_flexbox = false
 #webform_depth = {int} 1
 #webform_children = {array} [0]
 #webform_multiple = false
 #webform_composite = false
 #webform_parents = {array} [2]
 #admin_title = "current_facility"
 #webform_plugin_id = "facility"
 #webform_submission = "121"
 #access = true
 #webform_element = true
 #allowed_tags = {array} [78]
 #element_validate = {array} [1]
 #pre_render = {array} [1]
 #after_build = {array} [1]
 #_webform_access = true
 #_webform_states = {array} [0]
 #theme = "input__webform_example_element__webform_generate_system_number_form_1__form__current_facility"
 #theme_wrappers = {array} [1]
 #formdazzle = {array} [3]
 #process = {array} [3]
 #input = false
 #value_callback = {array} [2]
 #defaults_loaded = true
 #tree = true
 #parents = {array} [1]
 #array_parents = {array} [3]
 #weight = {float} 0.007
 #processed = false
 #required = false
 #attributes = {array} [1]
 #title_display = "before"
 #description_display = "after"
 #errors = null
 #id = "edit-current-facility"
 #name = "current_facility"
 #value = ""
 #options = {array} [2]

```

But after returning, I still get an `<input>` field. Any suggestions how to alter the `input` type to be `select`? Thank you

# Answer
After long research about Webform elements, I have finally figured out the solution. Extend the Select Element. :)

```
use Drupal\Core\Render\Element\Select;

class Facility extends Select {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $properties = parent::getInfo();
    $class = get_class($this);
    $properties['#process'][] = [$class, 'processMyCustomSelect'];

    return $properties;
  }

 public static function processMyCustomSelect(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add and manipulate your element's properties and callbacks.
    return $element;
  }
}

```

this post really helped me out a lot: Webform Custom Radios/Checkboxes Element does not get rendered in webform : Drupal 8
> 1 votes

---
Tags: entities, webforms
---


title: Updating node title inside Rules Action

text:
# Question
Title: Updating node title inside Rules Action
I am creating a Rules Action that will update the node title after it is created.

Here is my code, but when I try to create new content using Postman, it keeps loading. I dont get response in Drupal logs.

```
...
class ContentTitle extends RulesActionBase {

  protected function doExecute(EntityInterface $entity) {

    $entity_id = $entity->id(); // Getting dynamic entity ID
    $controller = \Drupal::entityManager()->getStorage('node');
    $node = $controller->load($entity_id);

    $title = $entity->label();
    $item = $node->get('field_xyz')->value;
    $new_title = "Title is " . $title . $item;

    \Drupal::logger('custom_rules')->notice('new_title: ' . $new_title);

    $data = array(
      'type' => 'custom_content',
      'title' => [
        'value' => $new_title,
      ]
    );
    $node = Drupal::entityManager()
      ->getStorage('node')
      ->create($data);
    $node->save();
  }
}

```

Im getting the expected output in the logger.

I dont think I am setting the title in `$data` properly. Any suggestion is greatly appreciated. Thanks!

# Answer
You can set a node's title with the "Set a data value" action - you don't need to write your own action. I'm going to assume that you're putting this into your own action because there are other things you want to do that you haven't mentioned or because you are learning how to write an action - if this is ONLY about setting the title then I don't see the point of a custom action.

Problems with the approach and the partial solution given in the initial post:

1. You don't need to get the entity ID then load the entity from storage, because Rules is already passing you the loaded entity.
2. You're using entity instead of node, which wrong - Nodes have titles, Entities in general DON'T.
3. You're hardwiring in a title taken from a specific field 'field\_xyz'. Instead, you should pass in a string variable which holds the title. That way the Rule configuration can get the value out of 'field\_xyz' or out of 'field\_nlm' or from a thousand other places - writing the action with a string parameter will make it far more useful.
4. The EntityManager has been deprecated since Drupal 8.0 and should not be used. You should be using EntityTypeManager instead. But as I said in #1, this isn't even needed.
5. You don't have to save the node, Rules will handle the saving automatically.

This really only requires one line of code (plus some boilerplate code, like all plugins...). Here's a complete solution that takes two context variables:

1. The node to change.
2. The title to use.

```

namespace Drupal\my_module\Plugin\RulesAction;

use Drupal\node\NodeInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Sets the title of a content item.
 *
 * @RulesAction(
 *   id = "rules_node_set_title",
 *   label = @Translation("Sets the title of the selected content item"),
 *   category = @Translation("Content"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node",
 *       label = @Translation("Node"),
 *       description = @Translation("Specifies the content item to change."),
 *       assignment_restriction = "selector"
 *     ),
 *     "title" = @ContextDefinition("string",
 *       label = @Translation("Title"),
 *       description = @Translation("The new title.")
 *     ),
 *   }
 * )
 */
class NodeSetTitle extends RulesActionBase {

  /**
   * Executes the action with the given context.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node to modify.
   * @param string $title
   *   The new title.
   */
  protected function doExecute(NodeInterface $node, $title) {
    $node->setTitle($title);
  }

  /**
   * {@inheritdoc}
   */
  public function autoSaveContext() {
    // The node should be auto-saved after the execution.
    return ['node'];
  }

}

```
> 0 votes

# Answer
You can create node like below also:

```
use \Drupal\node\Entity\Node;

class ContentTitle extends RulesActionBase {

  protected function doExecute(EntityInterface $entity) {
    $entity_id = $entity->id(); // Getting dynamic entity ID
    $controller = \Drupal::entityManager()->getStorage('node');
    $node = $controller->load($entity_id);
    $title = $entity->label();
    $item = $node->get('field_xyz')->value;
    $new_title = "Title is " . $title . $item;
    \Drupal::logger('custom_rules')->notice('new_title: ' . $new_title);
    $node = Node::create([
      'type' => 'content_type',
      'title' => $new_title,
    ]);
    $node->save();
  }
}

```

In your code "title" should be only $new\_title not in the array as value. Even your code also looks fine except that title. I didn't any try of your code but I am suggesting to use above one.
> -1 votes

# Answer
Simple answer from https://drupal.stackexchange.com/a/249771/70281 did the trick for me.

```
$node->set('title', $new_title);
$node->save();

```
> -1 votes

---
Tags: 8, rules
---


# Question
Title: Reload webform_entity_select options (from new arguments) on ajax callback
I have a form with 3 fields: viticultor, variedad and parcela. All this fields are webform\_entity\_select widgets. My goal is refresh the values (if possible, using the entity reference view configured) of parcela field when i change (or set) values for fields viticultor and variedad.

It's possible to RErender or refresh the parcela field entity reference arguments with an ajax callback?

I've wrapped the parcela field into a Div with the webform UI. This is my custom code:

```
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

switch($form_id){
    case 'webform_submission_movimientos_de_uva_add_form':
    case 'webform_submission_movimientos_de_uva_edit_form':
        $form['elements']['parcela']['#access']=FALSE;
        $form['elements']['viticultor']['#ajax'] = [
            'callback' => 'ajax_select_parcela',
            'event' => 'change',
            'progress' => [
                'type' => 'throbber',
                'message' => 'Actualizando lista de parcelas...',]
        ];
        $form['elements']['variedad']['#ajax'] = [
            'callback' => 'ajax_select_parcela',
            'event' => 'change',
            'progress' => [
                'wrapper' => 'select-parcela-wrapper',
                'type' => 'throbber',
                'message' => 'Actualizando lista de parcelas...',]
        ];
        break;
}}

function ajax_select_parcela(array &$form, FormStateInterface $form_state) {
// get drupal rendering service
$renderer = \Drupal::service('renderer');

// instantiate new ajax response object
$response = new AjaxResponse();

//WHAT TO DO HERE??
return $response;}

```

I'm using Drupal 9.

Update:

This is my ajax function:

```
function crdo_movimientos_select_parcela(array &$form,  \Drupal\Core\Form\FormStateInterface $form_state) {
$form['elements']['parcela']['options']=[];
$form['elements']['parcela']['#selection_settings']['view']['arguments']=[
  $form_state->getValue('viticultor'),$form_state->getValue('variedad_de_uva')
];

return $form['elements']['parcela'];}

```

Field parcela is displayed in the form, but with options none... How to rebuild the field's options with the new arguments?

Update 2:

I've rewrited the field\_definition from the export webform devel Form API option, passing it the updated arguments, and even with specific arguments. But the field is rendered without options... I can't find the way for rebuild the #options. Any help will be apreciated.

This is the ajax function:

```
function crdo_movimientos_select_parcela(array &$form,  \Drupal\Core\Form\FormStateInterface $form_state) {
//if there are the two values (viticultor and variedad_de_uva), we unset and rebuild the parcela field element
if((!empty($form_state->getValue('viticultor'))) && (!empty($form_state->getValue('variedad_de_uva')))){
    unset($form['elements']['parcela']);
    \Drupal::messenger()->addMessage('Regeneramos campo parcela');
    $form['elements']['parcela'] = [
        '#type' => 'webform_entity_select',
        '#title' => t('Parcela'),
        '#target_type' => 'node',
        '#selection_handler' => 'views',
        '#selection_settings' => [
            'view' => [
                'view_name' => 'variedades_parcela_viticultor',
                'display_name' => 'entity_reference_1',
                'arguments' => [
                    '535',
                    '2',
                ],
            ],
        ],
        '#prefix' =>'<div id="select-parcela-wrapper">',
        '#suffix' =>'</div>',
    ];
}
// If we want to execute AJAX commands our callback needs to return
// an AjaxResponse object. let's create it and add our commands.
$response = new AjaxResponse();
// Issue a command that replaces the element #edit-output
// with the rendered markup of the field created above.
dpm($form['elements']['parcela']);
$response->addCommand(new ReplaceCommand('#select-parcela-wrapper', $form['elements']['parcela']));
// Finally return the AjaxResponse object.
return $response;}

```

I've tried to render the form element field before include it in the ReplaceCommand, but i obtain the same result...

# Answer
Final Update (Closing): I get it! The key is rewrite the arguments in the `hook_form_alter`. This function is called whenever the ajax callback returns.

I obtain the solution from here: Entity reference view depending on other field

Final code:

```
function crdo_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    switch ($form_id) {
        case 'user_form':
            // Añadimos una función adicional al enviar el formulario de reseteo de contraseña.
            // Enviamos un request a la aplicación velneo para actualizar su contraseña.
            $form['actions']['submit']['#submit'][] = 'crdo_user_pass_submit';
            break;

        case 'webform_submission_movimientos_de_uva_add_form':
        case 'webform_submission_movimientos_de_uva_edit_form':
            // Añadimos un div contenedor alrededor del campo parcela, para usar como objetivo de la llamada Ajax.
            $form['elements']['parcela']['#prefix'] = '<div id="select-parcela-wrapper">';
            $form['elements']['parcela']['#suffix'] = '</div>';

            $form['elements']['viticultor']['#ajax'] = [
                'callback' => 'crdo_movimientos_select_parcela',
                'event' => 'change',
                'wrapper' => 'select-parcela-wrapper',
                'progress' => [
                    'type' => 'throbber',
                    'message' => 'Actualizando lista de parcelas...',
                ],
            ];
            $form['elements']['variedad_de_uva']['#ajax'] = [
                'callback' => 'crdo_movimientos_select_parcela',
                'event' => 'change',
                'wrapper' => 'select-parcela-wrapper',
                'progress' => [
                    'type' => 'throbber',
                    'message' => 'Actualizando lista de parcelas...',
                ],
            ];
            if ((!empty($form_state->getValue('viticultor'))) && (!empty($form_state->getValue('variedad_de_uva')))) {
                // \Drupal::messenger()->addMessage('Regeneramos campo parcela');
                $form['elements']['parcela']['#selection_settings']['view']['arguments'] = [
                    $form_state->getValue('viticultor'),
                    $form_state->getValue('variedad_de_uva'),
                ];
                // dpm($form['elements']['parcela']);
            }
            break;
    }
}

function crdo_movimientos_select_parcela(array &$form, FormStateInterface $form_state) {
    return $form['elements']['parcela'];
}

```
> 1 votes

---
Tags: webforms
---


# Question
Title: How can I get the taxonomy term name from a term ID?
I'm trying to get a taxonomy term name by term ID. According to another post, I should load the term first:

```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy')->load($tid);

```

But then I get this error :

> Notice: Undefined property: Drupal\Core\Entity\Plugin\DataType\EntityReference::$target

What am I doing wrong? How can I get the term name?

# Answer
> 7 votes
```
 $term_name = \Drupal\taxonomy\Entity\Term::load($term_id)->get('name')->value;

```

You will get the Term Name

# Answer
> 40 votes
Or you can simply use The entity Term class:

```
use Drupal\taxonomy\Entity\Term;

```

and in your code:

```
$term = Term::load($tid);
$name = $term->getName();

```

# Answer
> 19 votes
The correct code is the following one.

```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

```

The entity type is *taxonomy\_term*, not *taxonomy*.

Then, use `$term->getName()`.

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


# Question
Title: How do I render a form in a div through a javascript call
I'm trying to load a form into a div using a javascript call. I can get the form in the div, but nothing works (autocomplete fields, wysiwyg fields, custom submit handler).

I know I must be missing something, but I can't figure out what it is.

What I have now to get the form:

```
$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');
$renderable = [
   '#theme' => 'my_form',
   '#form' => $form,
];
$rendered = Drupal::service('renderer')->renderPlain($renderable);

$response = new AjaxResponse();
$response->setData($rendered);
return $response;

```

I've also tried `renderRoot` instead of `renderPlain`, but to no avail.

The twig file looks like this (very simple):

```
<div id="form-container">
    {% include 'header.html.twig' with {
        type : 'manual'
    } %}
    <div class="content">
        {{ form }}
    </div>
</div>

```

Any help will be greatly appreciated.

# Answer
> 4 votes
You have to add ajax commands to the ajax response, using the unrendered render array:

```
$response->addCommand(new ReplaceCommand('#form-container', $renderable));

```

BTW you can only return a Drupal ajax response if you have triggered an ajax request via `ajax.js`. Outside of form submits you usually do this by adding the class `use-ajax` to a link. For custom js code see How to Trigger Existing, Non-Form Ajax from JavaScript Event

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


# Question
Title: How can I keep logs of all outgoing emails?
I am using SMTP Authentication Support module to send emails with drupal 8.When I see `watcdog mail-log` from admin it shows only emails sent for registration or password reset, that is also with single line like `registration email send to..`. I did not found any logs related to email sent me for orders status. I have installed `devel_mail_logger` to keep logs but than I did not received those email which are listed in `devel_mail_logger` log list, any suggestion how can I keep all email logs with content & errors(if any).

# Answer
Try to use https://www.drupal.org/project/mail\_safety I using it with swiftmailer module (configured with SMTP) and it works. You can configure it for store all outgoing emails.
> -1 votes

---
Tags: 8, emails, log-messages
---


# Question
Title: How to correctly format a POST request to the file_upload Rest Response?
This is my first time posting a StackExchange question, so thanks in advance for your patience.

We are attempting to upload an image to a headless Drupal application using the File Upload REST resource. In testing the endpoint with Postman, we've run into a weird issue. We are able to target the endpoint and upload an image fine through Postman's 'binary' body type, in which you just attach an image to the GUI and it does the rest for you. But if we use the 'raw' body type and pass in the Base64 code for the image, the image entity is created but the actual appears broken in Drupal. According to the linked documentation, it appears the binary data just needs to be passed in directly with the appropriate headers.

So my questions are: Is there a specific way to format or package Base64 image information to upload directly to Drupal? Am I falsely equating Base64 and binary data? Does anyone have any similar experience? Thanks a ton for taking a second to read this.

For context:

Our endpoint in both cases is `http://localhost:8000/file/upload/{entity_type_id}/{bundle}/{field_name}?_format=json`

And our headers are:

```
Content-Disposition: file;filename="test.jpg"
Content-Type: application/octet-stream

```

And when we attempt to preview the image in Drupal after passing the Base64 directly, this is what the preview looks like (an ominous white outlined square on a black background):

# Answer
> 1 votes
Recently I have faced the same issue in a file upload. For this, I have done base64\_decode() before the file\_save\_data() in Drupal. Example code:

```
  if (isset($file_data['title']) && isset($file_data['data'])) {
      // Get base64_encode of file data and explode to get data.
      $encodedImgString = explode(',', $file_data['data'], 2)[1];
      // Decode the data.
      $decodedImgString = base64_decode($encodedImgString);
      // Get the file name.
      $file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_data['title']);*/
      // Save the file using base_decode() data.
      $file = file_save_data($decodedImgString, 'public://' . $file_data['title'], FILE_EXISTS_RENAME);
      $file_result = [
        'target_id' => $file->id(),
        'title' => $file_data['title'],
      ];
    }

```

Hope this helps you.

**Note: Here I have used custom REST API for file uploads.**

# Answer
> 1 votes
I was stuck with the same issue, there are lots of posts saying that we should send the image content as base64 i.e.

```
    "filename": [
        {
            "value": "image.jpg"
        }
    ],
    "data": [
        {
            "value": "base64encoded image string"
        }
    ]
    ...

```

When I inspected the image on the destination site, I could see a square, just like reported in this thread. I openeded the file into a binary editor and the contents of the file were the array sent.

After struggling a lot, I figured how to make this work by sending the actual content of the image i.e.

```
<?php

    $curlHandler = curl_init();
    curl_setopt_array($curlHandler, [
      CURLOPT_URL => 'http://admin:password@site.local/file/upload/node/page/field_image',
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => [
        'Authorization: Basic ' . base64_encode('admin:password'),
      ],
      CURLOPT_HTTPHEADER => [
        'Content-Type: application/octet-stream',
        'Content-Disposition: file; filename="image.jpg"',
      ],
      CURLOPT_POST => TRUE,
      CURLOPT_POSTFIELDS => file_get_contents('./image.jpg'),
    ]);
    $response = curl_exec($curlHandler);
    curl_close($curlHandler);

```

This worked and allowed me to use the built in endpoint for /file/upload/node/{type}/{field\_name} with no need to write custom code.

---
Tags: 8
---


# Question
Title: Why recurring order becomes completed immediatelly after payment (no fulfillment status)?
I'm using Commerce datatrans module which originally supports only offsite payments. However I added extra functionality for recurring payment and it works well.

Only issue I have is that when method createPayment() I added is called by cron job and payment is made that order gets status "Completed".

For default types of orders (non-recurring ones) they have status "Fulfillment" so when all items are shipped order status can manually be changed to "Completed". I expected same thing with recurring orders.

In createPayment() function I added code I found on official documentation for that method:

```
$next_state = $capture ? 'completed' : 'authorization';
$payment->setState($next_state);
$payment->setRemoteId($transaction["uppTransactionId"]);
$payment->setExpiresTime(strtotime('+5 days'));
$payment->save();

```

Not sure should I change order status from that method. But again some other code is changing it form "Draft" to "Completed".

So my question is why it's not changed to "Fulfillment" but to "Completed" as soon as payment is done?

# Answer
> So my question is why it's not changed to "Fulfillment" but to "Completed" as soon as payment is done?

Because you're setting it to completed, the code you found is just *an example*.

For your case, it needs to be:

```
$next_state = $capture ? 'fulfillment' : 'authorization';

```
> 0 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: Overriding permissions selectively via settings.php/settings.local.php
The use case is a development module that you would only have installed on a local environment.

My thought was to use `$config` in settings.php to do this:

```
$config['user.role.anonymous']['permissions'][] = 'use browsersync';
$config['user.role.authenticated']['permissions'][] = 'use browsersync';

```

When doing this everything looks good in the permissions UI but in practice the permissions seem to be clobbered and permissions like 'access content' are no longer enabled for these users.

# Answer
> 6 votes
Permissions are clobbered because Drupal uses `NestedArray::mergeDeepArray()` to merge overrides with existing config.

For example, if we have this permissions

```
$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  - 'access content'
  - 'access comments'

```

and then add

```
$config['user.role.anonymous']['permissions'][] = 'use browsersync';

```

to `settings.php`, the result will be

```
$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  - 'use browsersync'
  - 'access comments'

```

An easy way to workaround this would be

```
$config['user.role.anonymous']['permissions'][9999] = 'use browsersync';

```

which will result in

```
$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  0:'access content'
  1:'access comments'
  9999: 'use browsersync'

```

But if you need to remove a permission via `settings.php`, then I honestly don't know how to do it, even with module config overrides system (which has an ability to load original config before providing the override). Maybe overriding the unwanted permission with `NULL` may work, but I haven't tried.

# Answer
> 0 votes
I'm not sure I completely understand your use case, but think https://www.drupal.org/project/secure\_permissions will work for you. It doesn't manage permissions in the settings.php. Instead it allows you to export permission to a hook that can be implemented across several modules. We have a module called cu\_debug\_admin\_bundle that enables devel, disables a few caching related modules. and sets a number of variables for local testing. The module also sets the permission so that devel output is visible to users with specific roles. Ideally that module isn't even deployed to production.

```
 /**
 * Define site permissions in code.
 *
 * Create a secure_permissions_data module directory and place this function
 * in secure_permissions_data.module.
 *
 * @param $role
 *   The role for which the permissions are being requested.
 *
 * @return
 *   An array defining all the permissions for the site.
 */

function cu_debug_admin_bundle_secure_permissions($role) {
  $permissions = array(
    'developer' => array(
      'access devel information',
      'access security review list',
      'run security checks',
    ),
  );
  if (isset($permissions[$role])) {
    return $permissions[$role];
  }
}

```

# Answer
> 0 votes
Following on form @Leksat's comment `Maybe overriding the unwanted permission with NULL may work`, this does work but you have to override the specific array key - see mock code below.

```
// Too early to use the File Storage class - so manually parse the yml file.
$user_role_anonymous = \Symfony\Component\Yaml\Yaml::parse(file_get_contents($settings['config_sync_directory'] . '/user.role.anonymous.yml'));
$permissions_to_remove = [
  'access devel information',
  'access kint',
];
foreach ($permissions_to_remove as $permission) {
  if (isset($user_role_anonymous['permissions'])) {
    if (($key = array_search($permission, $user_role_anonymous['permissions'])) !== FALSE) {
      $config['user.role.anonymous']['permissions'][$key] = NULL;
    }
  }
}

```

EDIT: better method using anonymous function for less variable pollution.

```
$config = isset($config) ? $config : [];
$config_directories = isset($config_directories) ? $config_directories : [];
$settings = isset($settings) ? $settings : [];

// Add or remove perrissons as needed.
$config = call_user_func(
  function ($config, $config_directories, $settings) {
    // Get sync folder.
    // Same as Drupal\Core\Site\Settings::initialize().
    if (!isset($settings['config_sync_directory']) && !empty($config_directories['sync'])) {
      $settings['config_sync_directory'] = $config_directories['sync'];
    }
    elseif (isset($settings['config_sync_directory'])) {
      $config_directories['sync'] = $settings['config_sync_directory'];
    }

    // Too early to use the FileStorage class - so manually parse the yml file.
    $user_roles_configs = [
      'user.role.anonymous' => \Symfony\Component\Yaml\Yaml::parse(file_get_contents($settings['config_sync_directory'] . '/user.role.anonymous.yml')),
      'user.role.authenticated' => \Symfony\Component\Yaml\Yaml::parse(file_get_contents($settings['config_sync_directory'] . '/user.role.authenticated.yml')),
    ];
    $permissions_to_remove = [
      'access devel information',
      'access kint',
    ];
    foreach ($user_roles_configs as $user_role_config_name => $user_roles_config) {
      foreach ($permissions_to_remove as $permission) {
        if (isset($user_roles_config['permissions'])) {
          if (($key = array_search($permission, $user_roles_config['permissions'])) !== FALSE) {
            $config[$user_role_config_name]['permissions'][$key] = NULL;
          }
        }
      }
    }
    return $config;
  },
  $config,
  $config_directories,
  $settings
);

```

---
Tags: 8, configuration
---


# Question
Title: Contextual views - show articles that the current user is interested in
## Aim

I am working on a Drupal 8 site that has articles which have a 'interests' field, and each User profile has a 'interests' field.

**I want to create a view that only shows articles that the currently logged in user is interested in.** For example, if the currently logged in user is interested in "Sports" and "Business", the view should show all articles that are tagged as either "Sports" or "Business".

## Attempts

I presume that the solution will involve using Relationships and Contextful Filters. I have read about both here and here.

I have checked previous answers, and think this one is pretty close to what I'm trying to do: Display content having the taxonomy of the logged in user

However, I couldn't seem to get it to work for Drupal 8

## Amends

Include of screenshot

# Answer
> 2 votes
## 1) Create users View

## 2) Add contextual filter of User ID

## 3) a) Add relationship of reference field

## 3) b) Checkmark require this relationship

## 4) a) Add relationship of Content with term

## 4) b) Checkmark require this relationship

## 5) Now in FIELDS it should allow you to add title field

## 6) Remove Name from fields.

## 7) Add FILTER CRITERIA of Published content

## Overall, should look like this:

---
Tags: 8, views
---


# Question
Title: Building a dynamic menu based on taxonomy terms
I'm new to Drupal and I am currently using Drupal 7. I need to know if what I am trying to do is even possible. If so I am going to need some pointers on how to implement it.

I have two vocabularies: *Category* and *Brand*. I have products that are tagged with a brand and one or more categories. I want a mega menu, dynamically built based on these terms. Basically, if there is a product tagged with category "A" and brand "X", a link should be created in the menu under products. So the menu would look like *Products \>\> A \>\> X*. Is there a way to accomplish this? I was thinking that I could create a custom module that would find all nodes of type product and create a category link for each new category it finds; then create a brand under the proper category.

# Answer
> 3 votes
You are looking for Taxonomy Menu module. Here is an excerpt from its project page:

> Transforms your taxonomy vocabularies into menus with ease!
>
> Features
>
> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

I found these tutorials helpful to get started.

First Tutorial (youtube video).

Second Tutorial (youtube video).

# Answer
> 1 votes
If you need a cross Vocabularies like Product \>\> Cat-A \>\> Brand-X then you can use Taxonomi Menu UI (https://www.drupal.org/project/taxonomy\_menu\_ui).

Taxonomy Menu UI works like "Node-Menu Setting", mean you can:

* Choose any parents: Brand-X has parent of Cat-A as your example
* Only show/hide certain Term on menu

---
Tags: 7, routes
---


# Question
Title: HTML tags after umlauts causing premature header sending - CK editor
I'm maintaining some old Drupal 7 site (not created by me) and since couple of months ago it started acting strange (I didn't make any change on site):

Inside some content type there is a formatted text field that is edited with CKEditor.

If field contains just a plain text and I try to save it (when editing the node) it works well.

If I make some text bold at beginning of the whole text and try to save it works well also.

But if I try to make some text bold after first umlaut character (site contains German text) and try to save I get 403 error - forbidden?!?

In drupal's error log I see the error:

> Warning: Cannot modify header information - headers already sent by (output started at /home/www/project\_name/includes/common.inc:2776) in drupal\_goto() (line 705 of /home/www/project\_name/includes/common.inc).

I even suspected that site has been hacked but I don't see any suspicious new files there.

Any idea?

```
/**
 * Performs end-of-request tasks.
 *
 * This function sets the page cache if appropriate, and allows modules to
 * react to the closing of the page by calling hook_exit().
 */
function drupal_page_footer() {
  global $user;

  module_invoke_all('exit');

  // Commit the user session, if needed.
  drupal_session_commit();

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  drupal_cache_system_paths();
  module_implements_write_cache();
  drupal_file_scan_write_cache();
  system_run_automated_cron();
}

```

That 2776 row is `ob_flush()` call. 705 is `header()` function call inside `drupal_goto()` function.

# Answer
Issue solved by server admin. It was about ModSecurity Apache2 settings. POSTs were rejected because they triggered new ModSecurity XSS alerts. So server admin excluded some rules. He found them in Apache2 error log and exluced them in Apache 2 conf file.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How do I debug/kint Simple XML Sitemap link array?
I am trying to find how I can debug/kint a variable/array from the Simple XML Sitemap?

I worked through the documentation here: https://www.drupal.org/docs/8/modules/simple-xml-sitemap/api-and-extending-the-module#s-api-hooks to find the hook I need.

My goal is to unset any links that have `node/` to remove published, but un-aliased nodes of included content types.

The array key `['path']` looks to be the unaliased URL and the below code removes all links except the home page. I am unsure how I can `kint($link)` in this function so I can see what other array keys are available to see what else I may use for comparison.

```
function HOOK_simple_sitemap_links_alter(array &$links, $sitemap_variant) {

  foreach ($links as $key => $link) {
    if (strpos($link['meta']['path'], 'node/') !== FALSE) {
      unset($links[$key]);
    }
  }
}

```

Is there a way to `kint()` these sitemap arrays? Or maybe some documentation that shows the structure of these arrays?

# Answer
> 3 votes
As Clive said, you will need to make sure that both the devel and kint modules are enabled. (NOTE: D8's Devel 4.0 now includes the kint module but requires 'composer require kint-php/kint' to be done to make it work) Then you can add your hook and just do a `ksm($links);` statement.

Make sure to clear cache so the hook will be found. Then doing a regenerate of the sitemap(s) in the gui will product the kint output that you can examine for the structure.

Also, not totally sure, but I think this hook has to be in a module and will not work in the .theme file.

FYI - Here's a code snippet from a working hook that does what you want, including removing untranslated nodes.

```
/**
 * Implements hook_simple_sitemap_links_alter().
 */
function my_module_simple_sitemap_links_alter(&$links, $variant) {
  foreach($links as $key => $link) {
    // Filter out any node/### URLs
    if ( preg_match("!(/[a-z-]*)?/node/\d?!", $link['url']) ) {
      unset( $links[$key] );
      continue;
    }
}

```

---
Tags: 8, xml-sitemap
---


# Question
Title: Configuration - > Zones admin page missing?
I've installed Drupal Commerce 2 and as explained here:

https://drupal-commerce.readthedocs.io/en/latest/v2/building-blocks/address/zones.html

there should be a "Zones" admin page at Configuration -\> Zones. But I don't have that page and I only have "default" zone?!?

Only relevant module I found is: https://www.drupal.org/project/address\_zone

but it exists only for Drupal 7?!

What I'm trying actually is to configure Commerce Product Tax, which exists only for D8 and at screenshot from module page: https://www.drupal.org/project/commerce\_product\_tax

... they do have zones "France" and "France (Corsica)", so this should be possible somehow I guess.

How to administrate those zones and why I don't have that page under "Configuration" in my back-end?

# Answer
> 0 votes
Use the European Union VAT

As it has France and France (Corsica)

---
Tags: commerce
---


# Question
Title: How to put a condition in TWIG "if the user is flagged"?
I have a site with Drupal 8 and the Flag module.

I would like to display a text when the user has the `association` role and when it is flagged with the following flag (his machine name):

```
flag_request_association_role

```

Then put its 2 conditions in a single line and how to know if the user is flagged ?

```
  {% if 'association' not in user.getroles and ??? %}
     <p>my text</p>
  {% endif %}

```

**UPDATE**

Here are my templates :

```
  {% if 'association' in user.getroles %}
    <div><i class="fas fa-circle text-success"></i> Votre compte association est actif.</div>
  {% elseif 'association' not in user.getroles and is_flagged_role_association %}
    <div><i class="fas fa-circle text-warning"></i> Votre compte association est en attente.</div>
  {% elseif 'association' not in user.getroles and not is_flagged_role_association %}
    <div><i class="fas fa-circle text-danger"></i> Votre compte association est inactif.</div>
    {{ content.flag_role_association }}
  {% endif %}

  <span class="border-top mt-4 mb-4"></span>

  <p>Les boutiques éphémères vous permettent d'exposer les créations des artisans présents sur la plateforme (pas de vente en ligne).</p>
  {% if 'pop_up_store' in user.getroles %}
    <div><i class="fas fa-circle text-success"></i> Votre compte boutique éphémère est actif.</div>
  {% elseif 'pop_up_store' not in user.getroles and is_flagged_role_pop_up_store %}
    <div><i class="fas fa-circle text-warning"></i> Votre compte boutique éphémère est en attente.</div>
  {% elseif 'pop_up_store' not in user.getroles and not is_flagged_role_pop_up_store %}
    <div><i class="fas fa-circle text-danger"></i> Votre compte boutique éphémère est inactif.</div>
    {{ content.flag_role_pop_up_store }}
  {% endif %}

  <span class="border-top mt-4 mb-4"></span>

  <p>Si vous êtes artisans, nous serions ravis de vous accueillir sur notre marketplace. Nous facturons une commission de 10% sur chaque vente. Vous recevrez une facture à chaque début de mois, si vous réalisez des ventes le mois précédent. Plus d'infos sur <a href="/node/271">cette page</a>.</p>
  <p>Pas de vente = Rien à payer</p>
  {% if 'marchand' in user.getroles %}
    <div><i class="fas fa-circle text-success"></i> Votre compte artisan est actif.</div>
  {% elseif 'marchand' not in user.getroles and is_flagged_role_artisan %}
    <div><i class="fas fa-circle text-warning"></i> Votre compte artisan est en attente.</div>
  {% elseif 'marchand' not in user.getroles and not is_flagged_role_artisan %}
    <div><i class="fas fa-circle text-danger"></i> Votre compte artisan est inactif.</div>
    {{ content.flag_role_artisan }}
  {% endif %}

```

bootstrap\_subtheme\_front\_office\_old.theme :

```
/**
 * Implements hook_preprocess_HOOK() for user.html.twig.
 */
function bootstrap_subtheme_front_office_old_preprocess_user(&$variables) {
  $flag_id = 'flag_role_association';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_to_flag = $variables['user'];
  $flag_status = $flag_service->getFlagging($flag, $user_to_flag);
  $variables['is_flagged_role_association'] = $flag_status;

  $flag_id = 'flag_role_pop_up_store';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_to_flag = $variables['user'];
  $flag_status = $flag_service->getFlagging($flag, $user_to_flag);
  $variables['is_flagged_role_pop_up_store'] = $flag_status;

  $flag_id = 'flag_role_artisan';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_to_flag = $variables['user'];
  $flag_status = $flag_service->getFlagging($flag, $user_to_flag);
  $variables['is_flagged_role_artisan'] = $flag_status;
}

```

# Answer
**mytheme.theme**

```
/**
 * Implements hook_preprocess_HOOK() for user.html.twig.
 */
function mytheme_preprocess_user(&$variables) {
  $flag_id = 'flag_request_association_role';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_to_flag = $variables['user'];
  $flag_status = $flag_service->getFlagging($flag, $user_to_flag); // get flag status
  $variables['is_flagged'] = $flag_status; // create variable for user.html.twig
}

```

> I would like to display a text when the user **has the association role** and when it is flagged

**user.html.twig**

```
  {% if user.hasRole('association') and is_flagged %}
    <p>my text</p>
  {% endif %}

```
> 0 votes

---
Tags: 8, theming, users, flags
---


# Question
Title: How do I write a behat test to go to user/UID/somewhere when I only know the username?
I'm trying to write Behat tests to verify my Drupal Commerce store.

My test creates some users, so I know the usernames but not the UIDs (the UIDs are assigned by Drupal in the test, so they will be different each time).

So, I want to get the UID based on the username, and then redirect to the payment method page for that user with a step like `When I go to the payment method page for username ABC`.

Here's my code:

```
  /**
   * @Then I go to the payment method page for username :username
   */
  public function iGoToThePaymentMethodPageForUsername($username) {
    $user_object = $this->userManager->getUser($username);
    $uid = $user_object->id;
    if (!(is_int($uid))) {
      throw new Exception("UID is not a number ('$uid')");
    }
    $this->visitPath("user/$uid/payment-methods");
  }

```

However, this code fails with the following error message:

```
  No user with ABC name is registered with the driver.

```

When I checked `this->userManager->getUsers()`, I found that it only has the users generated by the Drupal extension in the current scenario; I cannot access the users who have been registered in other scenarios or users who have already registered outside of Behat.

What's the correct way to get the user object for such a user?

# Answer
> 1 votes
You could use Sub-pathauto which will allow you to use */user/username/somewhere* instead.

---
Tags: users, commerce, testing
---


# Question
Title: Block in node view showing but does not show up when rendering node in Views
I have a node type that I have a specific block added to. I have some AJAX going on in the block. When you view the full node the block shows up.

When I go to Views and render the full node content that block doesn't show up, just the node content.

How can I get the block to show up in Views when rendering the full node?

I've read that maybe Panels would be a better solution than using blocks, especially considering I'm using Views.

# Answer
> 2 votes
You are mixing up full node (view mode) and single node (page, canonical URL). Blocks only get added to pages. In regions.

I'm not sure right now, but isn't there from core already a block reference field you can add to a node type? Use this. Or use the Block Field module. And then set your specific block as default value.

Alternatively you can use a pseudo field (a.k.a extra field) from a custom module to render your block. Has the advantage that it then can't be changed by editors.

---
Tags: views, blocks, 9
---


# Question
Title: Date Field Type - Text Field Widget is Gone?
I am noticing that the Date field type only has the availability of three widgets:

1. Select list
2. Date and time
3. Select list, no time

Can someone tell me why the "Text Field" widget is gone? Or am I missing something?

I have a use case where the user needs to be able to copy the date from another source and paste that value into the date field. It would be too time-consuming to have to pick the date from a "date picker" widget. It would be ok if it were a one-off situation but this user needs to be able to enter several at a time.

# Answer
> 4 votes
> I have a use case where the user needs to be able to copy the date from another source and paste that value into the date field.

## Bootstrap Datepicker

This will allow you to type/paste in and change the date format.

**Note:** composer won't install the library for you, you have to manually get the /dist folder from github and put in in the /libraries folder. So it has the `/libraries/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js` structure.

---

**Similar but don't quite do it**

Datetime Flatpickr Allows you to change date format, but doesn't allow you to type/paste in.

Bootstrap DateTime Picker Allows you to type/paste in, but doesn't allow changing the date format.

Single Date Time Picker doesn't allow you to type/paste in nor change the time format.

---
Tags: datetime, 9
---


# Question
Title: How do I get low level data from the Flag module?
Is it possible to get the following raw, low level data from the Flag Module and/or it's services?

* Flagging count as integer
* URL to flag/unflag as a string
* Current user's flagging status as boolean

I already know that I can do this:

```
$flag_link = \Drupal::service('flag.link_builder')->build('node',$nid,'bookmark');

```

But it will output the full blown markup with Ajax and everything.

I've done this:

```
$flag_service = Drupal::service('flag.count');
$counts = $flag_service->getEntityFlagCounts($node);

```

But I can't actually figure out what exactly `$counts` contains, I definitely can't output it as an integer on my template, I get an error.

# Answer
> 0 votes
To get the total flagging count:

```
$count_service = \Drupal::service('flag.count');
$flag_counts = $count_service->getEntityFlagCounts($node);
$count = $flag_counts['my_flag'];

```

To get the current user's flagging status:

```
$flag_service = \Drupal::service('flag');
$my_flag = $flag_service->getFlagById('my_flag');
$user = \Drupal::currentUser();
$is_flagged= $my_flag->isFlagged($node,$user);

```

to toggle the flagging status:

```
if(!$is_flagged){
    $flag_service->flag($my_flag , $node);
}

```

or

```
if($is_flagged){
    $flag_service->unflag($my_flag , $node);
}

```

Best to wrap all of this into an if clause

```
if( $user->isAuthenticated() ){ ... }

```

It's probably easiest to just build my own URL / route to take care of the toggling to fit my needs.

---
Tags: 8, flags
---


# Question
Title: Cannot get just the text of an option from submitted data
I'm using Webform 8.x-5.8.

I've got a select box referencing some content. Of course, the numeric option value is passed. But when I reference submitted data with tokens, I just want to handle the plain text appearing with the options, but a concatenation of the text and the sequence " (NID)" is displayed instead, where NID is the content ID. An example with dummy code, names and values - just to roughly show what I suppose is happening behind - is following.

```
<select name="my_parameter">
<option value="80" selected>Some text</option>
...
...
...
</select>

```

By selecting *Some text*, "80" is passed.

My aim is displaying "Some text" picking it up from the submitted values.

Tried with `[webform_submission:values:my_parameter]` and `[webform_submission:values:my_parameter:value]`. Anyway I get *Some text (80)*.

What am I supposed to do in order to get rid of that final NID in brackets?

Thanks in advance!

Andrea

# Answer
I scanned Webform's code base for `[webform_submission:values:` and eventually found the webform.token.inc file to list a number of Webform tokens from submission values. One of them being `entity:*`. And another being `delta`.

```
'<li>element_key:entity:*</li>' .
'<li>element_key:delta:entity:*</li>'

```

> The 'entity:\*' applies to the referenced entity
> The 'delta' is the numeric index for specific value

And when I scan Drupal core's code base for `:entity:title]` there's `[comment:entity:title]`. When I scan for just `:title]` there's `[node:title]` among the first hits. Okay, with all that I'd assume it must work with either:

```
[webform_submission:values:ELEMENT_KEY:entity:title]

```

Or if it's a multi-value field try it with a `:delta` of `0` to ensure you only get the first referenced node's title.

```
[webform_submission:values:ELEMENT_KEY:0:entity:title]

```

---

Just found out for taxonomy terms it's `:name` at the end:

```
[webform_submission:values:ELEMENT_KEY:entity:name]

```
> 1 votes

---
Tags: webforms, tokens
---


# Question
Title: Redirect to webform from controller and back to custom form
I have a use case where I'm creating a custom form, but for business reasons, I need to obtain customer information in a separate webform prior to granting access to my custom form. So my workflow needs to be as follows:

1. Customer attempts to access form at `/my-custom-form` url
2. Customer is redirected to customer information webform at `/customer-information-form`
3. Customer fills out customer info form and submits it.
4. On submission, customer is redirected to `/my-custom-form` url.

My thought was to use a controller for the `/my-custom-form` url, and just do a redirect to the webform, and then when the webform has been submitted, redirect back to the form, having to note that the webform is submitted. However, what I'm having problems finding is how to redirect using an internal URL using the `Drupal\Core\Url` class. In order to use the `redirect()` method that is included in the `ControllerBase` class, it has to be a defined route name (e.g. `my_module.my_custom_route`. If I try something like this:

```
$url_object = \Drupal::service('path.validator') ->getUrlIfValid('/customer-information-form');
$route_name = $url_object->getRouteName();
$this->redirect($route_name);

```

`$route_name` = `entity.webform.canonical`, which throws an error, since that's a generic route name.

So my question is, how do I redirect my user to my webform using an internal path, especially when it is just a generic webform?

**UPDATE:** So the `ControllerBase` class has a `redirect()` method that from what I've seen, should allow me to redirect. However, when I use this code in my controller function:

```
$url_object = \Drupal::service('path.validator')->getUrlIfValid('/my-custom-form');
$route_name = $url_object->getRouteName();
$route_params = $url_object->getRouteParameters();
$this->redirect($route_name, $route_params);

```

but when I run it, I get an error that my controller must return a response. If I add some simple markup like so

```
return [
  '#type' => 'markup',
  '#markup' => $this->t('Hello, World!'),
];

```

Then I get that markup instead of the redirect happening. What is the purpose of that `redirect()` method if it doesn't redirect?

# Answer
> 1 votes
Personally, I would create a multi step/page webform or multi step/page custom form instead of having two separate forms, but to answer your question:

In your webform settings:

In your custom form code

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    // redirect
    if (!\Drupal::request()->query->get('hello') == 'world') { // if url doesn't have ?hello=world
      $path = '/customer-information-form';
      $response = new \Symfony\Component\HttpFoundation\RedirectResponse($path);
      $response->send();
    }

```

# Answer
> 2 votes
> What is the purpose of that redirect() method if it doesn't redirect?

You find this method in both, controller and form:

ControllerBase::redirect()

FormBase::redirect()

It creates a redirect response and you return it if a certain condition is met:

```
if (...) {
   return $this->redirect($route_name);
}

```

Example: https://drupal.stackexchange.com/a/277596/47547

---
Tags: 8, forms, webforms, redirection
---


# Question
Title: Change entity reference field widget based on condition?
I am using Drupal 8. In user registration form, I use an entity reference field to a profile. I wanted to display inline entity reference form widget or entity select widget based on role.

For this, I tried to use `hook__field_widget_form_alter()`, but it didn't work.

Is there any way to solve this problem?

# Answer
For D7, you use hook\_field\_widget\_properties\_ENTITY\_TYPE\_alter but the problem is that in D8 this hook no longer exists.

Took a while to figure out an answer for D8, but here it is.

Since D8 allows you to create Form Display Modes:

### 1) Add a form mode

### 2) Select the entity type, User in this case

### 3) Add name to it

### 4) In Manage Form Display, click on Custom Display Settings and checkmark it

### 5) Click on the alternate view mode and change widget

Then in custom module you change the view mode if it has a certain role

```
/**
 * Implements hook_entity_form_display_alter()
 */
function mymodule_entity_form_display_alter(\Drupal\Core\Entity\Display\EntityFormDisplayInterface &$form_display, array $context) {
  if ($context['entity_type'] == 'user' && $context['bundle'] == 'user') {
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    if ($current_user->hasRole('administrator')) {
      // change the display mode
      $id = $context['entity_type'] . '.' . $context['bundle'] . '.alternate';
      $storage = \Drupal::entityTypeManager()
        ->getStorage('entity_form_display');
      $alt_display = $storage->load($id);
      $form_display = $alt_display;
    }
  }
}

```
> 0 votes

---
Tags: users, hooks
---


# Question
Title: Exclude nodes referenced from another content type's node
I have two content type:

1. Content type A
2. Content type B

In content type B I have one reference field which referencing Content type A.

Now I want to build a list of Content type A, which is not reference yet (from content type B).

I was did it in drupal 7 by RELATIONSHIPS (referencing field\_name), and FILTER CRITERIA (NID Is Null /(empty)

But in drupal 8 its not working, I search everywhere but didn't able to solve this issue. So I am here for your help.

Thank you so much.

# Answer
> 0 votes
In content type B (basic page), I named the refence field `field_ref_article`

### 1) Create view of content type A (article)

### 2) Add relationship "Content Using \[field\_name\]"

### 3) Leave require unchecked

### 4) Add FILTER CRITERIA of \[field\_name\]

### 5) Set relationship to \[field\_name\] and operator is empty (null)

### Overall should look like this

---
Tags: 8, views
---


# Question
Title: Missing form state values after adding submit function
I added a submit function in the form\_alter hook when inserting a node:

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

```

In the save\_as\_draft() function, I want to get the address value from the form state, but there are no values (except for the additional submit button).

```
function save_as_draft(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  var_dump($form_state->getValue('field_address'));                      // outputs NULL
  var_dump($form_state->get('field_address'));                           // outputs NULL
  var_dump($form['field_address']['widget'][0]['value']['#value']);      // outputs 'Address value'
  var_dump(array_keys($form_state->getValues())); // outputs { [0]=>  "save_as_draft" [1]=> "op" }
}

```

How can I get the form\_state values in this alternative submit function without validating the whole form?

Is there another way of retrieving the form values instead of digging through the widget arrays?

# Answer
Entity forms usually run as first submit handler the entity builder functions. Then following submit handlers can get the processed field values directly from the form object entity:

```
$entity = $form_state->getFormObject()->getEntity();
$field_values = $entity->field_foo->getValue();

```
> 1 votes

# Answer
the correct $form\_state get value should be

```
*recommended* : $form_state->getValue('key');
or
$form_state->getValues()['key']

```
> 0 votes

# Answer
> How can I get the form\_state values in this alternative submit function without validating the whole form?

```
$form['actions']['save_as_draft'] = [
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ['::submitForm', '::save'],
];
array_unshift($form['#validate'], 'save_as_draft'); // adds a custom validate that runs before the default node validate.

```

Now this should work

```
function save_as_draft(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  if ($form_state->getTriggeringElement()['#parents'][0] == 'save_as_draft') { // check Save As Draft button was clicked
    var_dump($form_state->getValue('field_address'));
  }
}

```
> 0 votes

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


# Question
Title: How to count number of published nodes of a specific content type in twig template?
I'm looking for a way to achieve this in my Twig file; if the number of published entities of a content type 'promotions' is at least one, a certain entity should be displayed in a content type Shop. I'm trying to show a banner only if there is at least one published promotion entity.

I could use some help with the if-function. I've written it down with I'm trying to do.

```
if(published promotion entities > 0){
{{ drupal_entity('node', 2668) }}
}

```

Any ideas to get me going? Thanks!

# Answer
In a preprocess hook function for your template, you can code something like this.

```
function MYTHEME_preprocess_TEMPLATE_HOOK(&$variables) {
    $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
    $query->condition('type', 'promotions');
    $query->condition('status', 1);
    $query->range(0, 1); // only need one
    $results = $query->execute();
    $variables['has_published_promotions'] = (bool)count($results);
}

```

`has_published_promotions` will be available in your Twig template and will be `TRUE` only when there are published nodes of that type.
> 2 votes

# Answer
Create a view with a filter of published nodes of that content type. With the snippet below you can add `{{ published_count }}` to your page.html.twig

```
use \Drupal\views\Views;

function MYTHEME_preprocess_page(&$variables) {
  // make the result count available as a variable in page.html.twig
  $view = Views::getView('published_promotions');
  $view->setDisplay('default');
  $view->execute();
  $variables['published_count'] = count($view->result);
}

```

Now you can do the following in Twig:

```
{% if published_count > 0 %} // print banner here {% endif %}

```

More: https://stefvanlooveren.me/blog/get-views-row-count-twig-drupal-8
> 1 votes

---
Tags: theming
---