# Question
Title: Dynamic results label for Views with Taxonomy Filters
I'm using Drupal 8 Views with Better Exposed Filters to filter a custom content type by two custom taxonomy vocabularies.

Results are filtered by:

* **Content: Published (=Yes)**,
* **Content: Content type (in Custom-Type)**,
* **Content: Taxonomy Vocabulary1 (exposed)**,
* **Content: Taxonomy Vocabulary2 (exposed)**,

The filters are working as desired, and the "No results behavior" generates a label on the results (technically, it's a **Global: Text area**, not a label) that says:

> **No results found**

When there are results, the client requires a similarly-formatted label on the results that will say something like this:

> Viewing **12** of **42** results for: **\[Vocabulary1 Term\]** with **\[Vocabulary2 Term\]**

Can I accomplish this with Views UI, or should I handle it in the Twig template? Theme suggestions say that the Twig template in use is `field--paragraph--field-views--views-reference.html.twig`.

**NOTE:** As a pager, I'm using Infinite Scroll to reveal 12 new results at a time. At the bottom of each screen full of results, there's a button that says:

> Load More \[Custom-Type\]s

Infinite Scroll options are very similar to what I want:

> The following tokens are supported:
>
> `@next_page_count` -- the next page record count
>
> `@total` -- the total amount of results returned from the view

Instead of showing the `@next_page_count`, I really need the current page count (which will increment by 12 results each time the button is pressed, and by the remainder for the last screenful.) And instead of rendering this text on the button, the client wants it back at the top of the results.

# Answer
> 1 votes
Your question doesn't seem to be related to Better Exposed Filters, BEF only format the actual form elements of the exposed form, not the display of the view results.

---

You can use the **Result summary** option you can add to the `Header` or `Footer` area in Views. It's under the `Global` Category, here are the listed tokens:

```
You may use HTML code in this field. The following tokens are supported:

@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@label -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@current_record_count -- the current page record count
@page_count -- the total page count

```

---

You can also use the **Text area** option that comes with some more options, including the arguments from Contextual and Exposed filters (if you turn on the `Use replacement tokens from the first row`):

```
view

[view:base-field] - Base field: The base field used for this view.
[view:base-table] - Base table: The base table used for this view.
[view:current-page] - Current page: The current page of results the view is on.
[view:description] - Description: The description of the view.
[view:id] - ID: The machine-readable ID of the view.
[view:items-per-page] - Items per page: The number of items per page.
[view:label] - Label: The label of the view.
[view:page-count] - Page count: The total page count.
[view:title] - Title: The title of current display of the view.
[view:total-rows] - Total rows: The total amount of results returned from the view. The current display will be used.
[view:url] - URL: The URL of the view.

```

---

In your case you're filtering by Taxonomy Entity Reference field (that information is directly in the node). But the ER fields only store the ID number of the referenced entity (TID in your case) and not anything else, which mean the Taxonomy term name isn't saved inside the node.

There is some magic done in Views for Taxonomy that makes it seem like the term data is available but those are targeted specific parts. Generally speaking you have to add a Relationship for that ER field in order to pull in data about the referenced entities.

So in you case you need to add the Relatinship for the Color and Size (how ever you have them called), and then add the `Taxonomy: Name` field for both cases.

Now when you open the `Use replacement tokens from the first row` option you will see the tokens for those fields that show term Names more directly, something like `{{ name_1 }} == Taxonomy term: Name`.

You will probably want to use some twig logic when to show it, check for Exposed filter being used.

---
Tags: views, 8, theming, taxonomy-terms
---


title: How can I get lat/lon from an address?

text:
# Question
Title: How can I get lat/lon from an address?
I have these modules

```
addressfield
geofield
geocoder

```

Is there any function to which I can pass an address like `Stree, zipcode city, Country` and it returns a lat/lon from that address?

I have searched in the code of geofield and geocoder but unable to find any helper function.

# Answer
Using google geocoding with geocoder module, you may use another geocoding provider, i think this requires a google map token now given google's new rules :

```
// @return Geometry Returns a geoPHP geometry object. Generally a Point.
$point = geocoder('google', $address);
$lat = $point->coords[1];
$lon = $point->coords[0];

```

I did this long time ago, please check.
> 1 votes

---
Tags: 7, location
---


# Question
Title: How can you add a template for a custom confirmation page URL?
I want to show custom message on confirmation page (on custom URL). I created a custom URL in \*.routing.yml file and added a method in controller class that returns an array :

```
return [
  '#theme' => 'mycustom_confirmation',
  '#test_var' => 'Test Value',
];

```

Next, in \*.module file,

1. I added hook\_theme function to return below array:

```
    'mycustom_confirmation' => [
          'variables' => ['mycustom_var' => NULL, 'webform' => NULL, 'source_entity' => NULL, 'webform_submission' => NULL],
        ]

```
2. I added template\_preprocess\_mycustom\_confirmation function to add my customized variables.

Then I created a template file: mycustom-confirmation.html.twig file where I consume the customized variables to show custom message.

After all that, when I landed to confirmation URL (that I set in to admin/structure/webform/manage/webinar\_training\_request\_1/settings/confirmation page) after webform submission , I dont see any message. I dont understand what I missed in module.

# Answer
> 1 votes
This would be a nice starting point:

/erlendsays.module

```
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function erlendsays_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  array_unshift($form['actions']['submit']['#submit'], 'store_doublecheck_form_result');
}

function store_doublecheck_form_result(array $form, FormStateInterface $form_state) {
  Drupal::request()->getSession()->set("webform_result", $form_state->getValues());
}

/**
 * Implements hook_theme().
 */
function erlendsays_theme() {
  return [
    'doublecheck_form_result' => [
      'variables' => [
        'form_result' => NULL,
      ],
      'template' => 'doublecheck_form_result',
    ],
  ];
}

```

/erlendsays.routing.yml

```
erlendsays.doublecheck_form_result:
  path: '/doublecheckformresults'
  defaults:
    _controller: '\Drupal\erlendsays\Controller\DoublecheckFormResultController::index'
    _title: 'DoubleCheck Form results'
  requirements:
    _permission: 'access content'

```

/erlendsays/templates/doublecheck\_form\_result.html.twig

```
<p>TODO: print the form result.</p>

```

/erlendsays/src/Controller/DoublecheckFormResultController.php

```
<?php

namespace Drupal\erlendsays\Controller;

use Drupal\Core\Controller\ControllerBase;

class DoublecheckFormResultController extends ControllerBase {

  public function index() {
    return [
      '#theme' => 'doublecheck_form_result',
      '#form_result' => \Drupal::request()->getSession()->get("webform_result"),
    ];
  }

}

```

---
Tags: 8, webforms
---


title: entity_autocomplete, multiple users

text:
# Question
Title: entity_autocomplete, multiple users
I would like a form element able to select multiple users.

```
$form['forward_users'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => t('Forward to these users (if multiple, select and add a comma \',\')'),
  '#target_type' => 'user',
  '#multiple' => TRUE,
);

```

`$form_state->getValue('forward_users')` returns only the last user ID.

I also tried this code.

```
$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('roles', 'int_tactf')
  ->execute();

foreach ($ids as $id) {
  $temp_user = \Drupal\user\Entity\User::load($id);
  $tactf_users[$id] = $temp_user->getAccountName();
}

$form['forward_users'] = array(
  '#type' => 'select',
  '#title' => t('Forward to these users'),
  '#multiple' => TRUE,
  '#options' => $tactf_users,
  '#size' => 3,
);

```

In the form submission handler, `$form_state->getValue('forward_users')` doesn't return the selected users.

# Answer
> 0 votes
To select multiple users with a *entity\_autocomplete* form field you need to use `'#tags' => TRUE` instead of `'#multiple' => TRUE`. The code you are using should be similar to the following one.

```
$form['forward_users'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => t('Forward to these users (if multiple, select and add a comma \',\')'),
  '#target_type' => 'user',
  'tags' => TRUE,
);

```

---
Tags: 8, forms
---


title: Custom e-mail translation in Drupal 8

text:
# Question
Title: Custom e-mail translation in Drupal 8
I need to send some e-mails depending on some actions. These e-mails should be translated depending on the target user's preferred language. I've seen that the mail function has a language parameter, but for me, it's not really do anything.

```
  $renderArray = [
    '#theme' => 'email_notification_content_update',
    '#name' => $node->getOwner()->getDisplayName(),
    '#content_title' => $node->getTitle(),
    '#content_url' => $node->toUrl('canonical', ['absolute' => TRUE])
      ->toString(),
    '#unfollow_url' => Url::fromRoute('flag.field_entry.delete', [
      'flag' => 'flag_name',
      'entity_id' => $node->id(),
    ])->setAbsolute()->toString(),
  ];

  $this->mailManager->mail(
    'my_module',
    'email_notification_content_update',
    $follower->getEmail(),
    $follower->language()->getId(),
    [
      'body' => $this->renderer->renderRoot($renderArray),
      'subject' => $this->t('An update of the content @title has been updated.', ['@title' => $node->getTitle()]),
    ]
  );

```

Currently, the e-mail text is in twig file (with links) and the parameters are passed to it at render. Now I can put the whole twig file in `{% trans %}` tags, but is there a better way? Like using the mail function's language parameter? Is there a better way to make a custom e-mail sending and have translations to them?

# Answer
> 0 votes
Be aware that the rendering (and therefore the translation) happens at $this-\>renderer-\>renderRoot(). I'd create a mail key handler, and build the body inside that handler. I'm not sure, but it may be that drupal switches to the given language at the -\>mail function before processing the custom hook.

```
  $this->mailManager->mail(
    'mymodule',
    'content_update',
    $follower->getEmail(),
    $follower->language()->getId(),
    [
      'node' => $node,
    ]
  );

```

/mymodule.module

```
<?php

use Drupal\Core\Url;

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $renderer = Drupal::service('renderer');

  if ($key === 'content_update') {
    $node = $params['node'];
    $renderArray = [
      '#theme' => 'email_notification_content_update',
      '#name' => $node->getOwner()->getDisplayName(),
      '#content_title' => $node->getTitle(),
      '#content_url' => $node->toUrl('canonical', ['absolute' => TRUE])
        ->toString(),
      '#unfollow_url' => Url::fromRoute('flag.field_entry.delete', [
        'flag' => 'flag_name',
        'entity_id' => $node->id(),
      ])->setAbsolute()->toString(),
    ];
    $message['body'] = $renderer->renderRoot($renderArray);
    $message['subject'] = t("Content :title has been updated", [':title' => $node->label()]),
  }
}

```

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


# Question
Title: How to reuse existing images in field type "Image"
I have custom ContentType with one field of type Image. Currently, when I edit a node I can only upload new images from local to server. I want to have the option to select images already existing on the server.

I think that the way to go is to use the EntityBrowser and/or FileBrowser modules but I don't know how to make this work. I can create the EntityBrowser instance but how do I tell the ContentType field Image to use it?

I'm on Drupal 8.

Your help is appreciated. --Josef

# Answer
Projects are built from the start to use the Media module and reference entities instead of files directly. That is how Entity Browser can help.

Here is how it's usually done:
https://www.drupal.org/docs/8/modules/entity-browser/how-to-configure-an-image-widget-to-re-use-existing-files.

More useful resouces:
https://www.drupal.org/docs/8/core/modules/media/faq-transition-from-media-entity-to-media-in-core
Is there any way to reuse the same file or image?

There's a way to convert your files into entities, there is the Migrate File Entities to Media Entities module, and some useful info about it:
Migrate File Entities to Media Entities in Drupal 8,
How do I migrate file entities into media entities?
> 5 votes

---
Tags: nodes, media
---


# Question
Title: How to check if a referenced entity is being used in other places?
I have a paragraph component that has a single field (reference) that calls on other paragraph components. I'd like to remove one of the paragraph reference field options so that users do not accidentally select it, however, when I do this I start receiving errors across my multisite environment that a reference no longer exists. Is there a quick way to check if a paragraph (or any entity) is being used and in which places (preferably one that shows paths) so that I can remove the reference before deleting this paragraph reference option from my paragraph component?

Any and all assistance would be greatly appreciated, thanks!

# Answer
> 2 votes
> Is there a quick way to check if a paragraph (or any entity) is being used and in which places (preferably one that shows paths) so that I can remove the reference before deleting this paragraph reference option from my paragraph component?

A paragraph can only be used in one place. So I'm first answering the part "or any entity", which also reflects the question title, and address the paragraphs specifics later.

I would do this in two steps. First find all entity reference fields which are configured to target this entity type, then run an entity query for each field.

As example how to find all entities where term #1 is used:

```
use Drupal\field\Entity\FieldStorageConfig;

$target_id = '1';
$target_type = 'taxonomy_term';

$map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('entity_reference');
$results = [];
foreach ($map as $entity_type => $fields) {
  foreach ($fields as $field_name => $field) {
    // we are only interested in configured fields, not base fields
    $config = FieldStorageConfig::loadByName($entity_type, $field_name);
    if ($config && $config->getSetting('target_type') == $target_type) {
      $ids = \Drupal::entityQuery($entity_type)
        ->condition($field_name, $target_id)
        ->execute();
      $results[$entity_type][$field_name] = $ids;
    }
  }
}

```

If the field is configured in a paragraph type, the IDs you find are of paragraph entities. Load the paragraph and get the parent entity with `$paragraph->getParentEntity()`. For nested paragraphs do this multiple times, until you find a non paragraph entity, for example a node.

# Answer
> 1 votes
You want to build Views showing "backwards" pointing Entity Reference connections. It can be confusing to call them Child-Parent or Parent-Child, so be careful which stance some resource take.

In the end, you want to list all nodes that reference the "current" node, they point to it through a Paragraph field, which is an Entity Reference field.

You can build that with the help of the "backwards" Relationship that is usually called something like `Content referenced from field_myERfield`. This Relationship pulls into your views information about other nodes that reference the nodes originally listed in your Views.

If you start with a usual list of nodes, with the field Title, you will see a list of all nodes on your site showing the nodes' titles.

With the use of the mentioned Relationship you can add another Title Field, and set it to use the Relationship (the original Title isn't using any Relationships). This time the Title field will show the Title of the nodes that reference the node showing in the first Title field! So you'll know whether the node you want to delete is referenced elsewhere, or it's safe to delete it.

You can add a Contextual filter for "current" node, to show only results related to a particular node. This way you can delete the first Title field and only keep the one showing the backwards reference. So if you enter a node ID into the Views Preview, you will get a list of all the nodes that reference the node with the ID you entered! This way the interface may be more intuitive to use but it will work without it.

Here are some Q/A you might want to read for more details and clarity:

How to use view's relationships to pull user entity reference data?

Referencing nodes reciprocally

How do I show a list of nodes referenced by a field?

Related content in a view using entity reference

Display related media entities

---
Tags: 8, entities, paragraphs
---


# Question
Title: How to change the value of a commerce token?
When an order is submitted on our D7 site an email is sent to us with all the details of the order, including the payment method.

I use the token `[commerce-order:payment-method]` in the commerce email configuration page , which works fine, but I would like to change the value of that token to something that is more readable, like "This order is paid".

This is what I have so far in a custom module:

```
    function mymodule_tokens_alter(array &$replacements, array $context) {

  if ($context['type'] == 'commerce-order') {
    // Find token starting with commerce-order:payment-method.
    if ($value_tokens = token_find_with_prefix($context['tokens'], 'payment-method')) {
      if (!empty($value_tokens['payment-method']) && $value_tokens['payment-method'] === 'card_payment') {
        $replacements[$value_tokens['payment-method']] = 'This order is paid';
      }
    }
  }
}

```

The token's value still is card\_payment, when the email arrives, so I have probably misunderstood something. Anyone?

# Answer
> 1 votes
`token_find_with_prefix()` doesn't return, in your case, the *\[commerce-order:payment-method\]* token, but tokens like *\[commerce-order:payment-method:date\]* or *\[commerce-order:payment-method:client\]*, if they exist.

The correct code you should use is the following one.

```
function mymodule_tokens_alter(array &$replacements, array $context) {
  if ($context['type'] == 'commerce-order') {
    if (!empty($replacements['payment-method']) && $replacements['payment-method'] == 'card_payment') {
      $replacements['payment-method'] = 'This order is paid';
    }
  }
}

```

As side note, altering the value returned for the *\[commerce-order:payment-method\]* token doesn't alter the value returned for similar tokens like *\[commerce-order:payment-method-title\]*. If you need to alter the value returned for *\[commerce-order:payment-method-title\]*, the code needs to be similar to the following one.

```
function mymodule_tokens_alter(array &$replacements, array $context) {
  if ($context['type'] == 'commerce-order') {
    if (!empty($replacements['payment-method-title']) && $replacements['payment-method-title'] == 'the payment title you want to change') {
      $replacements['payment-method-title'] = 'This order is paid';
    }
  }
}

```

Remember to change `'the payment title you want to change'` with the effective payment title you need to alter, which probably isn't `'card_payment'` (but that is something you need to verify).

# Answer
> 0 votes
I am sure the answer provided by kiamlaluno is correct, and I don't know why it doesn't work for me. Maybe it does work and another commerce module change the value back again, but in case anyone else is struggling with similar problems I would like to share a very simple workaround.

The payment method form is created with the hook `hook_commerce_payment_method_info()`. As an option to this hook it is possible to use an extra field called `display_title`, which will be used to display the form's title to users. If this field is not specified it defaults to the `title` field. More info here.

So, in this case the field `title` becomes free to use for other purposes and as this field's value also is available "out of the box" as a replacement token (`[commerce-order:payment-method-title]`) in the `admin/commerce/config/email` page, I used this field in my email, which worked straight away.

```
/**
 * Implements hook_commerce_payment_method_info().
 */
function invoice_payments_commerce_payment_method_info() {
  $payment_method = array();

  $payment_method['card_payment'] = array(
    'base' => 'card_payment',
    'weight' => 0,
    'title' => t('This order is paid'),
    'display_title' => t('Card payment'),
    'description' => t('Pay your order with card.'),
    'active' => TRUE,
    'offsite' => FALSE,
    'offsite_autoredirect' => FALSE,
  );

  return $payment_method;
}

```

And then in the Order email configuration page:

En ny beställning har gjorts på hemsidan.

```
Payment:

[commerce-order:payment-method-title] // will show "This order is paid" when this payment method is used
etc....

```

---
Tags: 7, commerce, tokens
---


# Question
Title: How to use Views Photos Grid module with custom minimal theme
I use Views Photos Grid module and it shows the results correctly with Stark theme. However, it shows all the images stacked in only place in my custom theme. I do include modules css and js files:

```
<link rel="stylesheet" href="/modules/views_photo_grid/css/views-photo-grid.css">
<script src="/core/misc/drupalSettingsLoader.js?v=8.6.3"></script>
<script src="/core/misc/drupal.js?v=8.6.3"></script>
<script src="/modules/views_photo_grid/js/views-photo-grid.js"></script>

```

I also render the expected divs:

```
<section class="viewnodes">
<div class="container">
<div class="col-10">
<div class="views-photo-grid-container">

<div class="views-photo-grid-item">
  <a href="/node/30">
    <img src="/sites/default/files/styles/screenshot/public/2019-01/img04.jpg?itok=yxujuA6O" width="300" height="300" alt="asdf" typeof="foaf:Image" />
  </a>
</div>

...more views-photo-grid-item divs are here...

</div><!--views-photo-grid-container-->
</div><!--col-10-->
</div><!--container-->
</section><!--viewnodes-->

```

Java script console shows no errors. I've checked in debugger that the main JS function `(function ($, Drupal, drupalSettings)` is called but none of the other JS functions is called. Could this be the cause?

# Answer
Issue was missing JS includes. The working set is:

```
  <script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"screenshots","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","google_analytics":{"trackOutbound":true,"trackMailto":true,"trackDownload":true,"trackDownloadExtensions":"7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip"},"viewsPhotoGrid":{"gridPadding":"1"},"user":{"uid":0,"permissionsHash":"797a0805952a191ed3acd8cc0feee5a8b53895cab4446ce069563dbdd87139da"}}</script>

  <script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>
  <script src="//code.jquery.com/jquery-3.3.1.min.js?v=3.2.1"></script>
  <script src="/core/misc/drupalSettingsLoader.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.init.js?v=8.6.3"></script>
  <script src="/modules/views_photo_grid/js/views-photo-grid.js"></script>

```

It doesn't work without the first messy line with `data-drupal-selector`. I wish I knew was is this good for...
> -1 votes

---
Tags: theming, javascript
---


# Question
Title: why views items per page set to specific values
Why does the Views module accep uses the number of items per page that is in pre-defined sets like 5, 10, 25, 50, and doesn't accept values outside those values?

I know how to change it; I just need an explanation.

# Answer
To be brutally simple: Because someone thought it to be good UX, maintainers agreed, and no one convinced them other way since then. That's all to it.

---

There are many reasons for drop-down instead of text field. For example simplicity. User cannot enter bad values, so there is no need for bad value handling. Testing - you can programatically set other amounts, all right, but there you have ones they tested their module for, and take some responsibility that they work properly. Of course, maybe someone simply liked it that way. No way to know for sure what was the most important part in this decision.
> 3 votes

# Answer
You can do it by using `views_pag_views_pre_build()`

```
function views_pag_views_pre_build(&$view) {
    if ($view->name == "pagination") {
            $view->init_pager();
            $view->set_items_per_page('10');

    }
}

```

Reference Human Love
> 1 votes

# Answer
the function names dont look correct here for the latest version of D8

should be

```
$view->initPager();
$view->setItemsPerPage(10); // or any other integer value

```
> 0 votes

---
Tags: views, paging
---


# Question
Title: How can I display a message when "add another item" on an Inline Entity Form Multiple field is clicked?
In Drupal 8 inline entity form is there a "form\_alter" or "submit handler" or some type of ajax callback for when a user clicks "add another item"?

What I would like to do is display a message to the user when they click "add another item" on a Inline Entity Form Multiple field.

Struggling to find the right path.

# Answer
> 1 votes
You can do this using JS. Add a click event listener on the `Add item` button. When the button is clicked you set a message.

Something like this should work:

```
$('.add-item-class').on('click', function () {
  const messages = new Drupal.Message();
  messages.add('You clicked the add item button!');
});

```

Make sure you have `Drupal` available in your JS file by adding it as a dependency in your libraries file.

```
js:
  path/to/js-file.js: {}
  dependencies:
    - core/drupal
    - core/jquery

```

Please note that the `Drupal.Message()` was first introduced in `Drupal 8.7`, so if you use an older version it would not work.

Another possible solution is to create a route that sets the message, using `\Drupal::messenger()->addMessage('')`.

Your controller will do like this:

```
\Drupal::messenger()->addMessage($this->t('Your added an item!'));
$messages = ['#type' => 'status_messages'];
return new JsonResponse(['message' => Json::encode(\Drupal::service('renderer')->renderRoot($messages))]);

```

And your JS file like this:

```
$('.add-item-class').on('click', function () {
  $.get('/path/to/your-route', function (response) {
    $(context).find('.region-highlighted').prepend(JSON.parse(response.message));
    setTimeout(function () {
      $(context).find('.region-highlighted .messages').remove();
    }, 5000);
  });
});

```

This appends the message to the `highlighted` region and removes it after 5 seconds. You can place it anywhere you want.

# Answer
> 1 votes
The IEF Api has a hook for performing alterations before the entity form is included on the IEF widget. You can add your message after checking you're on the right form/entity.

```
/**
 * Perform alterations before an entity form is included in the IEF widget.
 *
 * @param $entity_form
 *   Nested array of form elements that comprise the entity form.
 * @param $form_state
 *   The form state of the parent form.
 */
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_line_item') {
    $entity_form['quantity']['#description'] = t('New quantity description.');
  }
}

```

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


# Question
Title: Configuration syncronization not importing everything
I have a remote server which I initially setup with a default Drupal **8.7.7** install. I have since been building the site on my local development server and would now like to transfer the developments to the remote server.

I exported the configuration using `drush config:export`

I committed the the exported items to git and pushed them to the remote server. I then ran `composer install --no-dev` followed by `drush updb` on the remote server and logged in.
I then went to the configuration synchronization setting and clicked on the import all button.

Everything seems to be working fine however 12 items will not sync. I have tried importing them via the import -\> single item option and tried importing everything via `drush cim`, however the following items still will not sync and show no errors:

I have repeated the process a number of times to check it wasn't a one off error.

The only similarity I can see is that they are all *core.entity\_view\_display* settings apart from the *one core.entity\_form\_display* item. Each one has different differences.

How can I debug why these items won't syncronize?

# Answer
> 1 votes
It appears as though the issue I had relates to this issue: **Display mode configurations don't get updated with new fields** https://www.drupal.org/project/drupal/issues/2915036

I haven't tried the patch yet, but after saving the individual display modes the fields then get put into the export and sync properly.

---
Tags: configuration
---


# Question
Title: How to get the uncached version of request headers?
We need to programmatically get the request headers using the `mymodule_preprocess_page` hook. To do this we tried the following, however, because we have CDN, Varnish, and Drupal Cache all enabled, the request headers are being pulled from cache so if in the initial request the header value we are looking for is set to false, it is false in all requests afterwards.

**How can we get the uncached request headers?**

Here is what we tried, but it didn't work.

```
function mymodule_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $request_hdrs = $request->headers;
  // This is the one that seems to be always caching. (true or false)
  // my-header is coming from another server.
  $request_custom = $request->get('my-header');

  // log this for troubleshooting
  \Drupal::logger('mymodule')->log(RfcLogLevel::INFRO, 'header value'.$request_custom);

  if($request_custom) {
    // based on the header value, redirect to another url.
    $response = new Symfony\Component\HttpFoundation\RedirectResponse('www.myurl.com');
    $response->send();
    return;
  }

}

```

# Answer
> 2 votes
Concerning CDNs or Varnish you need to ask in a different place. In Drupal you find two caches for requests/responses:

1. The *Internal Page Cache*, which is implemented in a kernel middleware, and you need to define a middleware with a higher priority to handle the uncached request.
2. The *Dynamic Page Cache*, which is implemented in a kernel request subscriber, and you need an event subscriber with a higher priority to handle the uncached request.

By the way, when you implement one of these methods, don't send the response, return it or set it in the event.

Example for a redirect middleware: https://drupal.stackexchange.com/a/247478/47547

---
Tags: 8, hooks, redirection, http-request
---


# Question
Title: Allowing anonymous user based on condition
I'm currently working on a custom module with an access form and set permissions for anonymous users.

I'm trying to make it so that when an anonymous user enters the password in the access form, they are logged successfully into 'node/3.'

The trick is, 'node/3' and any other basic page node is blocked for anonymous users via the following code I placed in my .MODULE file.

```
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
function cookie_authentication_node_access(NodeInterface $node, $op, AccountInterface $account) {
if ($account->isAnonymous() && $node->gettype() == 'page') {
return AccessResult::forbidden()->cachePerPermissions();
}

return AccessResult::neutral();
}

```

Now, how do I get the anonymous user to access the page only for the condition that the password is entered in the access form?

Here's the code for the access form:

```
<?php
/**
* @file
* Contains \Drupal\resume\Form\CookieForm.
*/
namespace Drupal\cookie_authentication\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
class CookieForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'cookie_authentication';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state)       {
     $form['password'] = array(
      '#type' => 'textfield',
      '#title' => t('Access'),
      '#required' => TRUE,
     );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#button_type' => 'primary',
     );
    return $form;
  }
  /**
   * {@inheritdoc}
   */

    public function validateForm(array &$form, FormStateInterface  $form_state) {
        $values = $form_state->getValue('password');
        //$configValue =  $config->get('access');
        $configValue = \Drupal::config('cookie_authentication.settings')->get('access');
         if ($values != $configValue) {
            $form_state->setErrorByName('password', $this->t('This value is not valid!'));
        }
    }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $password = $form_state->getValue('password');
    setcookie("password", $password );
    drupal_set_message('valid code');
    $response = Url::fromUserInput('/node/3');
    $form_state->setRedirectUrl($response);

}

}

```

The password is loaded through a config form I built into the back-end...

# Answer
You can store a value on the session if the password match and then check that value:

```
$_SESSION['password_match'] = TRUE;

```

Or even better, as suggested by @4k4 you can do it the D8 way.

CookieForm class:

```
$session = $this->getRequest()->getSession();
$session->set('password_match', TRUE);

```

hook:

```
$password_match = \Drupal::request()->getSession()->get('password_match');

```
> 1 votes

---
Tags: forms
---


# Question
Title: How do I exclude a node from an entity reference field?
I have a *homepage* content type which has a *featured\_article* field, an entity reference field that allows the editor to choose a single node from the *Article* nodes. That node is displayed as *Featured article* on the homepage.

Together the featured article on the homepage, I'm rendering a view (block) that displays the latest articles. I would like to avoid the node selected as featured article doesn't appear in the view. How can I achieve this?

This is my first Drupal project (coming from Craft and ExpressionEngine), and I'm struggling to figure out how to properly configure the view. I expect that I need to use a contextual filter together with a relationship, but I haven't had any luck. I could probably work in a conditional in the Twig template, but I'd prefer to keep the logic in the view if at all possible.

# Answer
> 1 votes
Welcome to Drupal Answers :)

You are right, you can do that with the help of a Relationship and a Contextual filter, but details are important.

In your Latest articles Views add the Relationship named something like `Content referenced from field_myERfield` for your featured article field. Be careful about the wording there because there are two Relationships available for the same field, you want the "backwards" one. Don't require the Relationship, otherwise you'll get no results if your home page isn't an article type.

Add the Contextual ID filter and set it to use the Relationship you've just added. `Provide default value` and choose `Content ID from URL`. Under Validation choose `Content` and `Article`, and other options that make sense in your case.

Then under `More` choose `Exclude`. That is how you exclude the currently featured article(s) from the latest articles list.

If you don't choose `Exclude` you'll only see the featured article in the results.

---
Tags: views, nodes
---


# Question
Title: How can I set up Protected Pages so users only have to log in once?
I'm using the Protected Pages module to make an area of the website - which is about 13 pages - password protected. The problem is that users have to enter the password to view every page rather than being able to enter the password once and then being able to see the entire section of the website (the members portal).

I had only one thing in the list of password protected pages which was `/members` which is part of the url. Every page that is supposed to be password protected has a url of `website.com/members/pageName` but that didn't work because anyone could just put the url straight into the browser and the page would should up without having to enter the password.

So, i added all 13 pages to the list of password protected pages but now users have to enter the password on every page.

We have two menus on the site. The public menu and members menu. When a user logs in to the members portal the menu changes and when you select a page from the menu, you have to enter the password every time, but we want it so users only have to enter the password once and they can see all the pages in the members portal.

How do I set that up?

# Answer
> 0 votes
Protected pages is really intended for one off password protection of webpages on a site. In order to have users login once to access a section of content, you should setup a user role assigned to a specific content type.

In the case where your existing content requiring authentication is the same content type as the non authenticated content, you can use the TAC Lite (taxonomy access control lite) module. To restructure the existing site to use this:

1. Create a new taxonomy to distinguish the password protected nodes from the others
2. Assign your custom term to the nodes to distinguish that they need authentication to view.
3. Install TAC Lite module.
4. Setup a new user role to associate with viewing permissions for the nodes with the assigned term.
5. Configure TAC Lite for the node type with term and user role.
6. Remove protected pages passwords for the given pages.
7. Clear caches
8. Test accessing (without login, you should see permission denied messaging)
9. Optionally, install r4032login module to automatically direct nonauthenticated users trying to access this section to the login page, and subsequently redirect back to requested url.

For future site builds or enhancements, I would recommend just setting up a distinct authenticated only content type and installing r4032login.

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


# Question
Title: How to display custom block anywhere in a div?
I am creating one drupal 8 theme based on bootstrap framework, for banners I created one custom block, named as 'Homepage banner', without creating any region, how to display this on my homepage template 'page--front.html.twig'.

# Answer
1. Install the twig tweak module
2. Insert the following code in your page--front.html.twig

```
{{ drupal_entity('block_content', 1) }}

```

Where "1" is the block id. You can see the block ID when you edit the custom block, it's in the URL - E.g. my-drupal-site.com/block/1
> 0 votes

---
Tags: theming, bootstrap-theme
---


# Question
Title: How to alter the search api views exposed form field value?
I have a search api view. Which has an exposed some exposed filters.

The exposed filters contains postal code, city and latlong field.

The user will enter the city and postal code and then in the code I will get a latlong from that address and will assign to the latlong field.

I have tried the following code but it is not working.

```
function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-id') {
    array_unshift($form['#submit'], 'mymodule_maps_exposed_form_submit');
  }
}

function mymodule_maps_exposed_form_submit(&$form, &$form_state) {
  $address = $form_state['values']['zipcode'] . ' ' . $form_state['values']['city'];
  $latlong = somefunction($address);
  // Tried all of these options but nothing is working.
  $form_state['values']['latlong'] = $latlong;
  $form_state['input']['latlong'] = $latlong;
  $form_state['view']->exposed_input['latlong'] = $latlong;
  $form_state['view']->display_handler->handlers['filter']['latlong']->validated_exposed_input = $latlong;
  $form_state['view']->display_handler->handlers['filter']['latlong']->value = $latlong;
  // This line adds the value to the form field but the filter doesn't apply.
  $form_state['complete form']['latlong']['#value'] = $latlong;
  $form_state['complete form']['latlong']['#default_value'] = $latlong;
}

```

Is there any trick I am missing? Can someone guide me? Anyone who can give a hint?

# Answer
I have found an answer. I am sharing it here so that it can help someone.

Instead of form\_alter hook, we can use `hook_views_pre_view`.

Here is the code

```
/**
 * Implements hook_views_pre_view().
 */
function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view_name') {
    $address = 'some address';
    $latlong = somefunction($address);
    $view->get_exposed_input();
    $view->exposed_input['latlon'] = $latlon;
    $view->execute().
  }
}

```
> 0 votes

---
Tags: 7, views, forms
---


# Question
Title: Drupal 8 - Add custom HTML with script to embed on a page as block
I need to add a custom form that has scripts and styles into a page as a block. Its dynamic, so I couldn't attach the scripts (#attached) as libraries. I just need to place the contents as is.

```
$build['test'] = [
  '#markup' => $test_code,
  '#allowed_tags' => [
    'script',
    'style',
    'form',
    'input',
  ],
];

```

I tried it as shown above, but this wasn't working. So, I removed, scripts and style as shown below and that works:

```
$build['test'] = [
  '#markup' => $test_code,
  '#allowed_tags' => [
    'form',
    'input',
  ],
];

```

Any possible solution to render the contents without filtering scripts and style.

# Answer
> 1 votes
You can use :

```
$build['test'] = [
  '#children' => $test_code,
];

```

---
Tags: 8, forms, blocks, input-formats
---


# Question
Title: How do I find a Form_ID for hook_form_FORM_ID_alter?
I want to alter the form for a content type I created for videos. The type is called Videos. How would I use hook\_form\_alter to alter the form to create the content?

# Answer
> 9 votes
The form ID is used as the id attribute on the form when it renders.

For content types the pattern is also predictable: `node-[TYPE_NAME]-form`. So in your case you're looking for: `hook_form_node_videos_form_alter()`.

Another way to handle it is to use the main `hook_form_alter()` and check the $form\_id parameter when you load the form you'd like to target.

# Answer
> 4 votes
You can also just look at the generated markup. the form\_id is always present as a hidden form\_element, so just search for "form\_id" in the source code and you should find it. Make sure you're looking at the correct form wrapper, often there are multiple forms (e.g. search/signup/login blocks)

# Answer
> 3 votes
Enable the development module then in your own .module file to get the form\_id

`function hook_form_alter(&$form, &$form_state, $form_id) {
 dpm(form_id);//get the form_id
 dpm(form);//get the form
 }`

Save the file flush the cache and you can see the form\_id.

# Answer
> 0 votes
In Drupal 8, navigate to the devel tab on the webform, click on render. Expand the variables and search for 'webform\_id'. You can find the webform id here.

---
Tags: 8, forms
---


title: Why is hook_update_N not running?

text:
# Question
Title: Why is hook_update_N not running?
I am porting a module to Drupal 7. The module has `hook_update_N()` functions called from `hook_install()`. There are some insert queries made inside one of the `hook_update_N()` functions. But my `hook_update_N` function is not running. Is there any way to explicitly invoke `hook_update_N` functions?

I know my question is almost same as this How to get hook\_install() to run all hook\_update\_N()?. But I don't understand how `hook_update_N()` is called. I have run updates in my Drupal site which I think also run updates of custom modules but it seems `hook_update_N()` is not getting triggered. Because, I have added `error_log()` function inside `hook_update_N()` but the log file is empty.

# Answer
Drupal stores which update hooks has been run as it only runs the update hooks once. If a specific update hook is not run, the most probable reasons is

* It has already been run
* An update hook that needs to be run before fails.

You can see in the system table all the modules enabled and the `schema_version` shows which update has been run last.
> 6 votes

# Answer
Another reason why an update hook would not run is a mismatch between the update hook name and the major release number of the module (see .info file).

For example: the update hook mymodule\_update\_7001 does not run if the module version is 7.x.1.0. In such case you must rename the hook to mymodule\_update\_7101.

See the hook\_update API documentation
> 14 votes

# Answer
I had an issue where I installed a new module, but the install failed. The schema\_version remained at -1, which prevented further updates for that module. Setting the version to 0 fixed it.

For the curious, I moved the schema of an existing table to a new module. The failure happened when it couldn't create the existing table, which I expected. The module was enabled as expected, but I didn't realize that the schema\_version didn't update.
> 2 votes

# Answer
One reason hook\_update\_N() function won't do anything is that an update with the same or higher number (than the number you used on your hook\_update\_N() function) has already run.

You can see the last update number that ran for your module by querying the 'system' table on Drupal 7. 'schema\_version' is a column on the 'system' table that stores the version number of the last update applied to your module. For your new hook\_update\_N() function to work, the number (N) you use on it has to be higher than the number currently stored in the 'schema\_version' column for that module.

I used the following query in MySql command line (after first issuing a 'use' command to specify my Drupal 7 database name).

mysql\> select name, type, status, schema\_version from system where type = 'module' and name = 'my\_module\_name';

The 'schema\_version' column will have a number. The number you use on your new update function must be higher than that.
> 1 votes

# Answer
I just had this issue, and thought I'd add to the pile since I can't see it mentioned in other answers.

My issue was with Drupal 8.7 and the issue was the module name had uppercase characters which caused it to fail any checks for updates. For example: `myModule`.

The reason is `drupal_get_schema_versions()` has a static array of `$updates` which is an associative array of available update schema versions keyed by module names. But the module names are all in lowercase. For example `$updates['mymodule']`. This causes the logics to fail and not return anything, making Drupal think there are no updates.
> 1 votes

---
Tags: 7, updating
---


# Question
Title: I have a site that is translated in English and French - can't change "Home" link in menu
My entire Drupal 8 site has been translated except I can't find where to change the translation of the "Home" link. When the site is in French mode (with the /fr) all my menu items show the appropriate French translation except for "Home" which I would like to read "Accueil" when I've switched to French. Thanks for any insights.

# Answer
Most likely, the "Home" menu link is coming from the UI text in Drupal Core.

You should be able to enable the "Interface Translation (locale)" module and then obtain **.po** or **.pot** files for the respective language (as described on the Drupal.org internationalization page).

Refer to https://www.drupal.org/node/1814954 for information about editing the .po/.pot files and https://www.drupal.org/node/314231 for info about obtaining them.
> 0 votes

---
Tags: i18n-l10n, navigation
---


# Question
Title: Redirect to view display after form submission
I'm using a `form_alter` hook to add a custom submit callback. I want to redirect the user to a particular page display of a view. However, I'm having trouble figuring out how to specify the path.

In my custom submit hook, I tried `$form_state->setRedirect('/my-view/page/path');` but that didn't work. From searching, I found this question, Redirect after form submission, but the answers indicate to specify the machine name of a path from a routing yaml file.

I'm wanting to redirect the user to a views page display that I built in the UI, so I don't have any routing.yml file (that I'm aware of) where I could glean a machine name of a path from.

How do I set the redirect in a custom submit handler to a page display of a view?

# Answer
> 1 votes
Routes are not only defined in yaml files, but also dynamically in route subscribers.

`Drupal\views\EventSubscriber\RouteSubscriber` collects routes from all views displays which implement `DisplayRouterInterface::collectRoutes`, like the *Page* display:

*PathPluginBase::collectRoutes:*

```
  public function collectRoutes(RouteCollection $collection) {
    $view_id = $this->view->storage->id();
    $display_id = $this->display['id'];

    $route = $this->getRoute($view_id, $display_id);

    if (!($route_name = $this->getOption('route_name'))) {
      $route_name = "view.$view_id.$display_id";
    }
    $collection->add($route_name, $route);
    return ["$view_id.$display_id" => $route_name];
  }

```

This produces route names like `view.my_view.page_1` and you can redirect in a form submit:

```
$form_state->setRedirect('view.my_view.page_1');

```

---
Tags: views, forms, redirection
---


# Question
Title: What is the pattern '<front>' referred to in Drupal speak?
Is the pattern used to denote the front page in Drupal referred to as token or something else? Does it exist in Drupal 8?

# Answer
> 0 votes
According to this Drupal 8 issue queue, `<front>` is a "special token." Yes, it still works in Drupal 8.

Reading the whole issue queue will give you some insight into the core developers' thought processes as they decided whether or not to support this legacy Drupalism in Drupal 8. They had a lot of good reasons to drop support for it, but they erred on the side of caution and left it in.

You can also try it for yourself in a Drupal 8 site; it definitely still works!

Help text for adding a menu link says:

> Start typing the title of a piece of content to select it. You can also enter an internal path such as `/node/add` or an external URL such as `http://example.com`. Enter `<front>` to link to the front page.

I guess you might want to give more weight to Clive's comments above, since his answer is based on the actual code and comments in Drupal core. Technically, all strings processed by `index.php` are considered "paths" and the ones that resolve to valid destinations are "routes." (Under the hood, Drupal 8's routing system is based on the routing provided by the Symfony HTTP kernel, and is used to connect paths to controller logic.)

---
Tags: 8
---


# Question
Title: Broken/missing handler error for my custom views filter?
I am trying to write a custom filter for views. The goal is to filter by alias, but that's not important now. It seems like I am missing a step to get view to recognize my filter hander after adding my filter in `hook_views_data_alter` as in the following:

```
/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}

```

I am able to get the filter to show in a view filter list. Now, my filter handler defined in `/docroot/modules/custom/alias_views_filter/Plugin/views/filter/Alias.php` but it does not seem to be picked up by views and I always get `Broken/missing handler` whenever I try to add the filter. Here is my handler definition:

```
<?php

namespace Drupal\alias_views_filter\Plugin\views\filter;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\StringFilter;
use Drupal\views\ViewExecutable;
use Drupal\Core\Form\FormStateInterface;

/**
 * Filters by alias.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("entity_alias")
 */
class Alias extends StringFilter {

  /**
   * The current display.
   *
   * @var string
   *   The current display of the view.
   */
  protected $currentDisplay;

  /**
   * @var views_plugin_query_default
   */
  public $query;

  /**
   * Constructs a new StringFilter object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    // this does seem to get evaluated at all ?
    die('Death in handler');
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['fields'] = ['default' => []];

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Filter by alias');
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $this->view->initStyle();
  }

  function query() {
    $this->ensureMyTable();
    $field = $this->tableAlias."nid"; //table_alias.".nid";
    $nids = $this->getNidsByAliasString($this->value);
    if (!empty($nids)) {
      $this->query->addWhere('AND', $this->options['group'], $field, $nids, 'IN');
    }
  }

  function getNidsByAliasString($aliasString) {
    $query = db_select('url_alias');
    $query->condition('alias', '%'.$aliasString.'%', 'LIKE');
    $result = $query
      ->fields('url_alias')
      ->execute();

    $nids = array();
    foreach ($result as $data) {
      array_push($nids, end(explode("/",$data->source)));
    }
    return $nids;
  }

}

```

Am missing a step or naming the filter incorrectly?

Checking the logs, I am getting these errors:

```
Notice: Undefined index: field in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
Notice: Undefined index: table in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
Notice: Undefined index: id in Drupal\views\Plugin\ViewsHandlerManager->getHandler()

```

# Answer
> 0 votes
Specify the data table instead of the base table, just replace node with node\_field\_data in your hook and run drush cr.

```
/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node_field_data']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}

```

---
Tags: views, 8
---


# Question
Title: What is error: "Base table or view not found: 1146"
Base table or view not found: 1146 Table '(database).(entity)\__(field\_name)' doesn't exist

I have problems running my site since i deleted field (field\_name) from entity (entity), to be clear entity was created from ContentEntityType.

**What kind of field is it, if it has it's own table and those two underscores in table name?**

**How can i create field of this kind to solve this error?**

It is quite urgent and my bad is i don't have any database backups.

# Answer
Found the fix!!! (Yes, i am user96758)

After 3 hours of investigation, internet and uncle Google wasn't helpfull at all.

The problem was that field was created via Drupal UI in Content Type -\> Manage fields. And it was deleted programatically by using UPDATE (code example below), not by using UI.

```
function hook_update_N(&$sandbox){
    $update_manager = Drupal::service('entity.definition_update_manager');
    $definition = $update_manager->getFieldStorageDefinition('field_name', 'entity_id');
    $update_manager->uninstallFieldStorageDefinition($definition);
    return t('Entity: field was uninstalled');
}

```

I have installed module named "Devel", which is pretty good damn module and every developer should have it.

I was finding **anything** that contains name of my problematic field.

Thanks to Devel module i was able to find config of this field. Usually you can see all configs at url **(your\_site)/devel/config**

Well, i was desperate, so the last chance was to delete the config i found. Usually the fields are named: **field.field.(entity).(entity).(field\_name)**

I removed the config with this code below

```
Drupal::configFactory()
    ->getEditable('field.field.(entity).(entity).(field_name)')
    ->delete();

```

Then i **CLEARED CACHE** and **IT WORKS AGAIN**!
> 2 votes

---
Tags: entities, database
---


# Question
Title: Send mail notification when node of given type gets created
Use case: a small site where I want to warn all users by mail whenever a new content of a particular type is created. I thought I would try Rules+Actions to handle this.

I'm working on a vanilla Drupal 8 test site on my workstation, so there is just "Article" and "Basic Page".

I've installed the Rules module ok. I've looked at several videos explaining how this works in Drupal 7 and they looked reasonable straightforward. Now I'm trying to do something in D8 and finding it less than obvious.

Specifically, I've created the rule to fire when new content is created, and now I'm on a page editing Condition, where I want to specify that the node type is "Article". Using "Data selection" mode in the "Entity" field I select "node.type". This seems logical, but what on earth do I put in "Type"? No matter what I put I get a message something like this: "Data selector node.entity for context Entity is invalid. Unable to apply data selector 'entity' at 'entity' " - which is about as unexplicit as you can get.

Maybe I'm jumping the gun and Rules is not usable yet? Or maybe I've just not understood it at all...

But I would really appreciate if somebody could explain to me what seems quite straightforward in principle. How do I add a condition to my Rule that will cause the rule to fire only on a specific content type?

# Answer
> 1 votes
Answering the "what do I put in the 'type' box?" question, the answer appears to be the same as for D7 - that is, the same status you'd pass to *drupal\_set\_message()*.

This gives you options of:

* status
* warning
* error

As to the state of D8 and specifically D8 rules, I share your pain - and it's nine months since you asked the question!

# Answer
> 0 votes
I don't know what the status of Rules was when this question was first asked, but the following is a complete example of how to use the "Node is of type" condition to check if a newly-created node is an article. I have had a similar rule working on my site for more than two years now - Rules has definitely been working and usable since then for things like this.

```
langcode: en
status: false
dependencies: {  }
id: new_article_created
label: 'New article created'
events:
  -
    event_name: 'rules_entity_insert:node'
description: 'Issue #2852342-16: Shows a system message when a new node of type ''article'' is created.'
tags: { }
config_version: '3'
expression:
  id: rules_rule
  uuid: f8e466d6-51d6-41ea-93f1-34436470f3c3
  conditions:
    id: rules_and
    uuid: 7776a869-e0c6-4499-b09e-da727722213e
    conditions:
      -
        id: rules_condition
        uuid: 6bf893f5-7bcf-420c-9a62-7e1cb9a884f6
        context_values:
          types:
            - article
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: f0bcccfd-685f-4a74-a4fd-0d36b540037a
    actions:
      -
        id: rules_action
        uuid: ec599dbc-cb40-448b-b37b-129d956c2eb7
        context_values:
          message: '<b>New article created:</b> {{ node.title }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message

```

---
Tags: 8, rules
---


# Question
Title: What is the difference in State API and Config API?
It is a bit confusing to understand the difference in State API and Config API in Drupal 8. I went through the documentation of both on drupal.org but it is not clear to me yet.

Do we define both State config and Config variables in config/install directory? And How are they both distinguished?

# Answer
> 1 votes
Configuration is a place to store information that you want to synchronize from development to production. This information is often created during site building and is not typically generated by regular users during normal site operation.

You should use the State API, not Configuration API, for storing local variables that shouldn't travel between instances.

The State API provides a place for developers to store information about the system's state.

State information differs from configuration in the following ways:

* It is specific to an individual environment.
* You will never deploy to deploy it between environments.
* Configuration is stored in the database, and can be exported to files (allowing migration). State is stored in the database, and cannot be exported.

---
Tags: 8, configuration
---


# Question
Title: How do we replace the token <front> in a custom module?
I am using the following in my custom module but the token is not being replaced. Is this a namespace issue?

```
$token_service = \Drupal::token();
$post_login = $token_service->replace('<front>');

```

# Answer
As already mentioned, `<front>` is a route, not a token, so you can't use the token API to work with it.

You can resolve it using the Url class:

```
$path = \Drupal\Core\Url::fromRoute('<front>')->toString();

// $path is equal to '/'

```

But I'm not sure how useful that will be. Perhaps you want to get the front page that's set in config instead:

```
$path = \Drupal::config('system.site')->get('page.front');

```
> 1 votes

---
Tags: 8, tokens
---


# Question
Title: How can I get the checked attribute into Better Exposed Filters input type radios?
i'm having a BEF exposed filter representing a taxonomy, they're radios.

It works well, but when i select a radio, it won't get in its HTML tag the property «*checked*». I guess the selected value of the radios is stored somehow at *$form\_state*, but this prevents existence of «*checked*» tag at HTML level. :-(

at jQuery level, i can select and play with the «checked» property, so it's working at javascript level.

the person who does the CSS needs that «*checked*» property at HTML level ... is there a way to insert it in the HTML?

# Answer
> 1 votes
The person who does the CSS needs to design the dynamic property `:checked`, not the static attribute `[checked]`. The 2nd one is static in the HTML code and never updated after the intial page load, the first one is the currently selected input.

---
Tags: 8, forms
---


# Question
Title: How can I add a custom CSS class to checkboxes labels?
I'm using Drupal 8 with the Form API and the AJAX API, now I want to add a custom CSS class to every checkbox label, because I need to use the bootstrap custom checkboxes.

PHP (slimmed):

```
$form['colors'] = array(
    '#type' => 'checkboxes',
    '#options' => array('1' => $this->t('Black'), '2' => $this->t('White')),
    '#attributes' => [
        'class' => ['custom-control-input'],
    ],
    '#prefix' => '<div class="foobar">',
    '#suffix' => '</div>'
);

```

HTML Result (please notice every label has the class "option"):

```
<div class="custom-control custom-checkbox">
  <div class="foobar">
    <div id="edit-colors" class="form-checkboxes">
      <div class="js-form-item form-item js-form-type-checkbox form-item-colors-1 js-form-item-colors-1">
        <input
          class="custom-control-input form-checkbox"
          data-drupal-selector="edit-colors-1"
          data-msg-required="Black is required."
          type="checkbox"
          id="edit-colors-1"
          name="colors[1]"
          value="1"
        />
        <label for="edit-colors-1" class="option">Black</label>
      </div>
      <div class="js-form-item form-item js-form-type-checkbox form-item-colors-2 js-form-item-colors-2">
        <input
          class="custom-control-input form-checkbox"
          data-drupal-selector="edit-colors-2"
          data-msg-required="White is required."
          type="checkbox"
          id="edit-colors-2"
          name="colors[2]"
          value="2"
        />
        <label for="edit-colors-2" class="option">White</label>
      </div>
    </div>
  </div>
</div>

```

My Twig Code:

```
<div class="custom-control custom-checkbox">
 {{form.colors}}
</div>

```

I know about the "**template\_preprocess\_form\_element**" function, but I had no luck.

Do you guys have any ideas or tipps? Is there a simple way to modify the label class, or should I try the "Form Options Attributes" Plugin?

Thanks

# Answer
> 5 votes
According to issue #2774255 and line 38 in the FormElementLabelTest.php you should be able to use `#label_attributes` for this.

> ```
> '#label_attributes' => ['class' => ['meow']],
>
> ```

---

Update: Seems you can also try to do this by implementing `template_preprocess_form_element`. There's an example on line 493 in the form.inc. In your theme implement `template_preprocess_form_element` and hopefully you find some unique identifiers in there to have this class added only for elements in certain forms or elements of certain types. And then it's

```
$variables['label']['#attributes'] => ['class' => ['meow']]

```

---

Last but not least there's the new Formdazzle! module you could try to use to override the label element templates directly.

> ### Drupal form theming with less pain
>
> Theming Drupal forms can be difficult and time-consuming. This module provides a set of utilities that make form theming easier.
>
> Currently, this module provides theme suggestions for forms that are much more useful than those provided by Drupal core.
>
> * Theme suggestions for all form elements (including buttons)
> * Theme suggestions for all form element labels
> * All theme suggestions include the form ID and the form element name; e.g. `[element-type]--[form-id]--[form-element-name].html.twig`

---
Tags: 8, forms
---


# Question
Title: how to prevent a theme from using templates of a sub themes (placed inside the parent theme dir)?
my folder structure looks something like this:

```
 themes
└─  foo
   ├─  bar
   │  ├─  templates
   │  │  └─  node.html.twig
   │  └─  bar.info.yml
   ├─  templates
   │  └─  page.html.twig
   ├─  foo.info.yml
   └─  foo.libraries.yml

```

now I run a multisite. one site is using the `foo` theme and the other uses `bar`.

The site using the `foo` theme also invokes the template `/theme/foo/var/templates/node.html.twig`

1. Why is that so?
2. I thought the `foo` theme only invokes templates inside its own `templates` folder? I expected this to be the point of the `templates` folder. Is that assumption wrong?
3. can I prevent this behavior without moving the subtheme somewhere else?

# Answer
Themes are not allowed to be placed inside one another, as oppose to modules. Even though it works, there are undesired side effects.
> 1 votes

# Answer
This directory structure is shows one single theme called `foo`. The sub-directory `bar` has no meaning at all for Drupal, it is below `/themes/foo`and as such part of `foo`.

Your node file has to go into `/themes/bar/templates/OPTIONAL/SUBDIR/DOES/NOT/MATTER/node.html.twig`

Every theme, even subthemes, has to go in it's own `/theme`-directory. Please red read the docs for sub-themes.
> 0 votes

---
Tags: theming, subsites
---


title: Render Twig template as XML

text:
# Question
Title: Render Twig template as XML
I want to send an XML mail using Drupal's `mailManager`.

I have created a custom twig template in my module that will the the mail body.

Here's what my template looks like, `my-module-xml-mail.html.twig`:

```
<record>
  <name>{{ name }}</name>
  <phone>{{ phone }}</phone>
  <email>{{ email }}</email>
</record>

```

And my template definition:

```
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module_xml_mail' => [
      'variables' => [
        'name' => NULL,
        'phone' => NULL,
        'email' => NULL,
      ]
    ]
  ];
}

```

And where I send the mail:

```
$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => $rendered,
]);

```

The problem is that when the mail is sent all the XML tags are stripped and only the values from the tags are sent.

How can I send the XML as plain text?

I thought about creating a `my-module-xml-mail.xml.twig` if that's possible, but when `"kinting"` the result from the renderer service it looks like renderer is not stripping any tags.

Do I need to send any headers to the mail, in order to send the XML as plain text?

# Answer
I found a solution myself.

The problem is that Drupal's mail system converts HTML to plain text, and therefore strips all HTML tags.

A workaround to this is to replace all `<` and `>` characters with their unicode string and send the mail as `text/plain`.

I did like this:

```
$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => str_replace(['<', '>'], ['<', '>'], $rendered->__toString()),
]);

```
> 1 votes

---
Tags: 8, emails
---


title: Drupal.settings merging when using AJAX

text:
# Question
Title: Drupal.settings merging when using AJAX
I have an AJAX form. I'm using drupal\_add\_js() after AJAX calls to update 'settings' and pass new information to my Drupal.behaviour object. However, the results are being merged instead of replaced. I know this is by design but it's messing up my Javascript code because I end up with information from the last callback. Does anyone know of a good workaround for this?

**Update:**

Current workaround is overriding the code so settings is replaced rather than merged, though only for the page my form is in.

```
Drupal.ajax.prototype.commands.settings = function (ajax, response, status) {
  ajax.settings = response.settings;
};

```

Feels wrong, but things are working as expected.

**Solution:**

The final solution I used, as solved by Alice Heaton, isn't to override code in ajax.js, instead I returned both the form and an AJAX command in the forms AJAX callback:

```
function my_ajax_callback($form, $form_state) {
  $commands = array();
  $commands[] = ajax_command_settings(array(
    'key1' => 'value1',
    'key2' => 'value2',
  ));
  $output = drupal_render($form['locator']);
  $commands[] = ajax_command_insert(NULL, $output);

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 6 votes
So when you use `drupal_add_js` to add settings during an ajax callback, this indeed merges the results. On the server side this is done in `ajax_render` (called from `ajax_deliver` or equivalent) which adds an ajax\_command\_settings command, instructing it to merge the results.

On the client side the merging is done by calling jQuery.extend, which causes the behaviour you have seen, and cannot be changed.

There is no work around if you want your results to be inserted into `Drupal.settings`. However you can pass your settings to your behaviour directly without using `Drupal.settings`. For this you would add a call to ajax\_command\_settings yourself. It would be something like this:

```
function mymodule_ajax_callback() {
  $commands = array();
  // ...
  $commands[] = ajax_command_settings(array(
    'key1' => 'value1',
    'key2' => 'value2',
  ));
  ajax_deliver(array(
    '#type' => 'ajax',
    '#commands' => $commands
  ));
}

```

Note that if your callback is called fom the Form API's `#ajax['callback']` then it runs `ajax_deliver` on the value returned by the callback, so you shouldn't call it yourself.

On your script on the client side, your settings will be available as the second parameter of your behaviour attach method:

```
Drupal.behaviors.mymodule = {
  attach: function (context, settings) {
    // Here settings contains your settings
  }
};

```

(edit: sorry, previous answer was very wrong)

# Answer
> 2 votes
As Alice Heaton mentioned its a problem with jQuery.extend, However there is an alternate way to replace the settings in Drupal.settings i.e Creating your own AJAX command. Here is the steps to create them,

* Create a callback for your new AJAX command,

```
function ajax_command_settings_replace($argument) {
  return array(
    'command' => 'settingsReplace',
    'settings' => $argument,
  );
}

```
* Extend the Drupal.ajax.prototype.commands to add method for your custom AJAX command

```
Drupal.ajax.prototype.commands.settingsReplace = function (ajax, response, status) {
  ajax.settings = response.settings;
};

```
* Now use your own AJAX command

```
function my_ajax_callback($form, $form_state) {
  $commands = array();
  $commands[] = ajax_command_settings_replace(array(
    'key1' => 'value1',
    'key2' => 'value2',
  ));
  $output = drupal_render($form['locator']);
  $commands[] = ajax_command_insert(NULL, $output);

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 1 votes
If you hog the settings array by overwriting it with ajax\_command\_replace, no other modules may pass their settings to the user. This can be a problem if your form relies on other modules.

It seems the only way to include other modules is to allow AJAX to merge the settings variable. Which means none of the above solutions work. An alternative may be to simply check if your jquery script has done its work and then simply deleting the relevant setting. Then you can keep your custom settings in `$form['#attached']`.

```
(function ($) {
  Drupal.behaviors.my_behaviour = {
    attach: function(context, settings) {
      if (work_is_done()) {
        settings.mysetting = null;
      }
      if (settings.mysetting) {
        do_work();
      }
    }
  }
})(jQuery, Drupal);

```

# Answer
> 0 votes
If the settings you don't need to merge are custom settings, there is an option to pass them to frontend as a JSON string and decode them from JS. It will const you some additional JSON processing, but will avoid issues with merging.

---
Tags: ajax
---


title: How can I change the page title?

text:
# Question
Title: How can I change the page title?
In Drupal 7, I could change the page title with `drupal_set_title(t('New page title'))`. When I try it in Drupal 8, I get a *There is no such function* error.

How can I change the page title?

# Answer
> 46 votes
As reported in drupal\_set\_title() and drupal\_get\_title() were removed that function is deprecated in Drupal 8.

For a dynamic title set from a controller, the code the change record suggests is the following one.

```
mymodule.test:
  path: '/mymodule/test'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Test::getContent'
    _title_callback: '\Drupal\mymodule\Controller\Test::getTitle'

```

The controller code is the following one.

```
class Test {

  /**
   * Returns a page title.
   */
  public function getTitle() {
    return  'Foo: ' . \Drupal::config()->get('system.site')->get('name');
  }

  /**
   * Returns a page render array.
   */
  public function getContent() {
    $build = array();
    $build['#markup'] = 'Hello Drupal';
    return $build;
  }

}

```

Alternatively, as the same change record suggests, you could use the `#title` property in a render array. This should be generally avoided, since the title for the page when fully rendered could be different from the title in other contexts (like in the breadcrumbs).

```
class Test {

  /**
   * Renders a page with a title.
   *
   * @return array
   *   A render array as expected by drupal_render()
   */
   public function getContentWithTitle() {
     $build = array();
     $build['#markup'] = 'Hello Drupal';
     $build['#title'] = 'Foo: ' . Drupal::config()->get('system.site')->get('name');
     return $build;
   }

}

```

# Answer
> 9 votes
**drupal\_set\_title() in Drupal 8**

```
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', 'New Title');
}

```

**drupal\_get\_title() in Drupal 8**

```
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $title = \Drupal::service('title_resolver')->getTitle($request, $route);
}

```

**Views**

To change the view title, both `<h1>` and `<head><title>`, according to this. Create a custom module and place the following in the .module file:

```
/**
 * Implements hook_views_post_render().
 */
function mymodule_views_post_render(Drupal\views\ViewExecutable $view) {
  if ($view->element['#view_id'] == 'id_of_view') {
    if ($view->element['#display_id'] == 'id_of_display') {
      $title = 'test';
      $view->setTitle($title); // Sets h1
      $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
      $route->setDefault('_title_callback', function() use ($title) {
        return $title; // sets <head><title>
      });
    }
  }
}

```

# Answer
> 9 votes
Change the title tag in the head of your HTML document.

```
function mymodule_preprocess_html(&$variables) {

  $variables['head_title']['title'] = $something;
}

```

Change the title that appears in the page content.

```
function mymodule_preprocess_block(&$variables) {

  if ('page_title_block' == $variables['plugin_id']) {
    $variables['content']['#title'] = $something;
  }
}

```

# Answer
> 5 votes
That function was removed from Drupal 8.
Change record: drupal\_set\_title() and drupal\_get\_title() were removed.

You could now set the title when defining the routes in `modulename.routing.yml`. Example of how it could be done, is shown the change record link above.

# Answer
> 5 votes
I found in D8 that if you're wanting to alter the title for an entity view, you can use hook\_ENTITY\_TYPE\_view\_alter(). For example, here's how you could change the view of a user entity with a field on the user "field\_display\_name", rather than the user ID as the title:

```
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  $build['#title'] = $entity->get('field_display_name')->getString();
}

```

# Answer
> 4 votes
I've found another way, which may be simpler if you don't have a controller and want to modify the title throughout your website. You can use it to modify the title based on the current node.

First, remove the tag in your html.html.twig Then, hook hook\_page\_attachments\_alter

```
function mytemplate_page_attachments_alter(array &$page) {
    $page['#attached']['html_head'][] = [
        [
          '#tag' => 'title',
          '#value' => "My title"
        ],
        'title'
    ];
}

```

You can get the current node of taxonomy term with

```
$node = \Drupal::routeMatch()->getParameter('node');
$term = \Drupal::routeMatch()->getParameter('taxonomy_term')

```

# Answer
> 3 votes
Getting the page title works fine as written in @rpayanm's answer. But setting it turned out to be quite complicated. Finally found out that `hook_preprocess_HOOK()` could simply be used to preprocess the page title quite easily.

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

  if ($MYLOGIC === TRUE) {

    $variables['title'] = 'New Title';
  }
}

```

---

And as already mentioned in other answers here you might additionally use `hook_preprocess_html()` to set the HTML head title tag accordingly.

# Answer
> 2 votes
Take a look at Automatic Entity Label, a very well crafted contributed module for setting node titles and the like.

(Note that 'page title' is a more colloquial way of saying 'entity label', where 'page' is a content entity and 'label' encompasses the title and the equivalent for other entities e.g. comment subjects, taxonomy term names.)

While op appears to be asking for guidance on writing custom code, it's not clear from available details that custom code is the best recommendation. For readers without a very specific reason for duplicating a feature available from contributed code, the Drupal community strongly advises (and site owners strongly benefit from) adopting an existing module.

# Answer
> 2 votes
`drupal_set_title()` and `drupal_get_title()` both are removed from drupal 8 but the best part is this there is a separate block for `page_title`. User can hide or add this block on any page/region.

There are 2 solutions for this.

1. Disable `title_block` on particular page and add new custom block with some markup for title. Now place this block just after the `title_block` in drupal block section.
2. By using `hook_preprocess_block()` function in your `custom_theme.theme` file.
Here is the code example:

```
function custom_themename_preprocess_block(&$variables) {
  if ('page_title_block' == $variables['plugin_id']) {
    $request = \Drupal::request();
    $path = $request->getRequestUri(); // get current path
    if(strpos($path, 'user')) { //check current path is user profile page
      $variables['content']['#title'] = 'My Profile';
    }
  }
}

```

In my case I have used above 2nd method, which will work only for user profile page.

# Answer
> 1 votes
I struggled with this and tried all of the solutions above. The solution that finally worked was:

```
function mymodule_preprocess_html(&$variables) {
  $variables['head_title']['title'] = $something;
}

```

but only after I updated my custom module weight:

```
drush php:eval "module_set_weight('mymodule', 10);"

```

# Answer
> 0 votes
i have changed the page\_title block for user/uid to a different custom account field name like this :

```
function hook_preprocess_block(&$variables) {
  $path = \Drupal::request()->getpathInfo();
  $arg = explode('/', $path);
  if (isset($arg[2]) && $arg[2] == 'user' && isset($arg[3])) {
    if (isset($variables['elements']['content']['#type']) && $variables['elements']['content']['#type'] == 'page_title') {
      $account = \Drupal\user\Entity\User::load($arg[3]);
      if(isset($account) && isset($account->field_mycustomfield->value)){
        $variables['content']['#title']['#markup']=$account->field_mycustomfield->value;
      }
    }
  }
}

```

---
Tags: 8
---


# Question
Title: What is the command to execute after manually editing the composer.json file?
I want to build a site broadly based on an exiting site and was thinking that the best way to do this would be to copy and paste required modules from the existing site composer.json and paste them into the new composer.json. What would be the correct command to download the modules via Composer once the file has been amended?

I think `composer update` is the command, but I don't know if it also updates dependencies that should not be updated.

# Answer
You are better off calling `composer require some/library`. This will update the files accordingly and install the library as well. That said, you can run `composer install` after manually editing `composer.json`.
> 2 votes

# Answer
Yes, after editing composer.json run `composer update`. If it update things you don't want then add more restrictive version constraints for those packages. To use composer most efficiently your project should be in a state where you can use `composer update` after editing composer.json. If not rollback and try again.
> 2 votes

# Answer
Erase a composer.lock file temporarily, though it could have its own drawbacks, like loosing the very specific version numbers of dependencies, thus beside probably also bypassing the cache and being slower, yet, it fulfills the requirements of having those concrete versions, questionable is if the very exact commit instances necessarily as in composer.lock file. On the other side, dependencies should be written in such a way, that it should be easily upgradable and preferrable to update any time without breaking some dependency - minors are not breaking versions.

Though sometimes, like changing composer JSON configuration like a platform or minimum stability requirements you often than not don't have other chance than just editing and actualizing the file manually.
> 0 votes

---
Tags: installation, composer
---


title: Problem with OAuth2 refresh token

text:
# Question
Title: Problem with OAuth2 refresh token
I have the following problem with the simple\_oauth module.

1. I can get the initial jwt token with a POST request to `/oauth/token` with the following form data:

```
username: user
password: password
client_id: xxxx
client_secret: yyy
scope: oauth
grant_type: password

```
2. This token has the actual access token and the refresh token. So I have an interceptor in Angular to refresh the token when we get a 403 return code. The call to refresh the token is again a POST request to `/oauth/token` with a slightly different payload:

```
client_id: xxxx
client_secret: yyy
scope: oauth
grant_type: refresh_token
refresh_token: def5020092674bfb5c570c518c112fbc78ec6ddb2d...

```
3. This call also succeeds but when I try to use the returned token I will get 403 returns. It is like the tokens produced using one grant type or the other have different scopes...

Have you experienced this problem? Do you know what can I do to solve it? Thank you very much in advance.

# Answer
> 0 votes
Status code 403 (Forbidden) does not mean that you are not properly authenticated. Since you received all tokens properly you are authenticated successfully. 401 Unauthorized means that you do not have a proper token, i.e. you are not authenticated).

If you receive 403 then you simply are not allowed to access the requested resource with the token you presented. The account you used does not have access privilege for whatever you are trying to access.

If I would have to guess:

1. Either you used the wrong account (e.g. Stage account used on Production) =\> use the correct account
2. Your account was not set up to access the endpoint. =\> talk to whoever created the account

Edit: It comes down to "Authentication != Authorization" ("who am I" vs. "what am I allowed to do").

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


# Question
Title: 404 Not Shown For Custom Module - Drupal 7
In a `hook_menu()` implementation, I am defining a route for login.

```
function my_account_menu() {
  $items['login'] = array(
    'title' => 'Customer Login',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('my_account_login_form'),
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK
  );

  return $items;
}

```

However, if I try accessing login/asdfdsa, it still loads the login page, instead of showing a 404 error.

Is there an error on the code I wrote, or in the module?

# Answer
> 0 votes
It's the expected behavior, and it's described in the documentation for `hook_menu()`, even it could not be clear, at a quick read.

> ### Callback Functions
>
> The definition for each path may include a page callback function, which is invoked when the registered path is requested. If there is no other registered path that fits the requested path better, any further path components are passed to the callback function. For example, your module could register path 'abc/def':
>
> ```
> function mymodule_menu() {
>   $items['abc/def'] = array(
>     'page callback' => 'mymodule_abc_view',
>   );
>   return $items;
> }
>
> function mymodule_abc_view($ghi = 0, $jkl = '') {
>   // ...
> }
>
> ```
>
> When path 'abc/def' is requested, no further path components are in the request, and no additional arguments are passed to the callback function (so `$ghi` and `$jkl` would take the default values as defined in the function signature). When 'abc/def/123/foo' is requested, `$ghi` will be '123' and `$jkl` will be 'foo'. Note that this automatic passing of optional path arguments applies only to page and theme callback functions.

This means that, for example with login/asdfdsa, Drupal will first check if there are modules that handle that path. If there aren't modules handling that path, Drupal will check if there are modules handling every path matching login/\*; if there aren't modules for those paths, Drupal will check if there are modules that handle login. In your case, that is your module. (I left out how Drupal handles the path aliases, as in this case isn't relevant.)

That happens also for other paths, for example node/1. If you have a node whose ID is 1, /node/1 shows it. If you try to access a path like, for example, /node/1/sdfgrgjpqwd432az, you will still see that node. (*sdfgrgjpqwd432az* is just a random string, to be sure I am not using a path for which a module defines a page callback.)

---
Tags: 7, routes
---


# Question
Title: How can I display all levels in Simple hierarchical select
I created select hierarchy ( taxonomy with 3 level), but in default it shows only one level , how can I display all 3 level in default page? : -Any- + -Any- + -Any-

I do not want it to automatically generate other fields.I want to display by default all the select input

# Answer
I had the same problem and found the answer was to create a custom module and not use SHS. Here's how I did it with Drupal 8 ... and some info on how done with D7: https://drupal.stackexchange.com/a/269296/18513
> 0 votes

# Answer
In Drupal 8 you will need to use the "business rules" module to add hierarchical select...
> 0 votes

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


title: Umami content not created

text:
# Question
Title: Umami content not created
I'm creating a new Drupal 8 site using Lando/Pantheon - and then installing the Umami profile. I've done this before with no problems.

This morning when I try, the site is created and it looks like the Umami theme is in place. However, the content is not created.

Is there any way to create the content after the profile is installed?

Note: Oddly, drush is saying that the demo\_umami\_content module is not found but is able to find demo\_umami\_tour. ~/Desktop/lando/lando-panth $ lando drush pmi demo\_umami\_content demo\_umami\_content was not found.

# Answer
The *Umami demo: Content* module is not found from Drush, nor is it visible in the list of modules, because it is set as hidden in demo\_umami\_content.info.yml. If you change the `hidden: true` line in `hidden: false`, you will be able to uninstall the module, and re-install it. This will execute again `demo_umami_content_install()`, which imports the content.

```
/**
 * Implements hook_install().
 */
function demo_umami_content_install() {
  if (!\Drupal::service('config.installer')->isSyncing()) {
    \Drupal::classResolver(InstallHelper::class)->importContent();
  }
}

```

If that doesn't work, the alternative is re-install Drupal using Unami as installation profile.
> 3 votes

---
Tags: installation, installation-profiles
---


title: Custom text/html in custom form module

text:
# Question
Title: Custom text/html in custom form module
I am following this tutorial and I've already created my custom form as Drupal 8 module.

I wonder, how to add custom text/html in form? I mean when somebody goes to the path pointed in `*.routing.yml`, I would like to display not only form fields, but also some intro html/text.

I know the form building is here:

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

$form['name_surname'] = array(
  '#type' => 'textfield',
  '#title' => t('Name and surname:'),
  '#required' => TRUE,
);
...
}

```

But I don't know what kind of entry (or `#type`) should I insert to get just an custom html/text block between fields or above them all?

# Answer
`#field_prefix` `#field_suffix` and `#description` should do the trick. Here's more info about FormElement. I believe you can also ~~set an element to type `markup` and then~~ use `#markup` to create an element that's just HTML (see ya.teck's answer).
> 7 votes

# Answer
> What kind of entry (or #type) should I insert to get just an custom html/text block between fields or above them all?

Item element type provides a display-only form element with an optional title and description.

```
$form['help'] = [
  '#type' => 'item',
  '#title' => t('Block title'),
  '#markup' => t('Block content'),
];

```

You may also add arbitrary content to render arrays using the #markup render array key as follows.

```
$form['text']['#markup'] = t('Some text.');

```
> 24 votes

# Answer
With Using `markup` you can add Html markups into your form.for an instance :

```
$form['help'] = [
    '#type' => 'markup',
    '#markup' => '<a href="#">Find out more</a>',
    '#weight' => '3',

];

```
> 2 votes

---
Tags: 8, forms
---


title: Formatting currency in Drupal Commerce

text:
# Question
Title: Formatting currency in Drupal Commerce
I am using Views and Drupal Commerce in Drupal 7 to display a list catalogue of products (books).

By default the price column is formatted "12.34 ZAR" which is a format that is only really used in an international currency trade context for South African Rand. How do I override the format so that I can display it as "R12.34" which is the more common format.

# Answer
> 5 votes
You can do it just for your site using hook\_commerce\_currency\_info\_alter(), but more appropriately check out the information in the Drupal Commerce FAQ on Currency Formatting to get the proper format in core. The reason it's showing up as 12.34 ZAR is because that's just the bland default format we use for currencies we didn't know how to format. : )

# Answer
> 2 votes
You can use the Commerce Currency Settings module. This will allow formatting to be configured from the Web UI.

# Answer
> 0 votes
Commerce Currency Settings module changes the Currency format sitewide. I recommend using the:

1. Price formatter: Raw amount, exclude it from display
2. Global: Math expression, e.g. \[commerce\_price\]/100 (Drupal commerce often uses the minor unit: pennies etc.)
3. Global: Custom text, e.g. R\[expression\]

This will allow you to use Views to display as you wish in the View without additional coding or modules.

This method can also be used for schema.org price itemprop, which requires decimal syntax without symbol, see: https://schema.org/price

---
Tags: views, commerce
---


# Question
Title: New Relic shows the token hook being called a lot
I've just installed NewRelic on a Drupal 7 website, and I'm now going through the most obvious issues that jump out at me.

Looking at the Drupal specific menu items, I notice the "Token" module accounts for about 1 min active time in 30 minutes clock time.

The list of hooks shows the "tokens" hook accounting for 203 seconds, which is about 80% of the total time. Each call takes less than 0.02ms, but the hook gets called over **18 million times** in 30 minutes clock time. The closest one is node\_view with 500 thousand calls. That seems more reasonable.

I can't, right off the bat, find a way to dig into the call tree for the Drupal hooks.

My questions:

* Does the amount of calls to the tokens hook seem normal?
* Is there a way in New Relic to find out where most hook invokes originate?

# Answer
> 0 votes
I wrote a tiny module to log all calls to the tokens hook, so that I'd have some sort of idea where the tokens were coming from:

```
<?php

function token_logger_tokens($type, $tokens, array $data = array(), array $options = array()) {
  watchdog('token_logger', print_r($tokens, TRUE), array());
  // Activate to fill up your database fast!
  // watchdog('token_logger', print_r(debug_backtrace(FALSE, 20), TRUE), array());
}

```

Turns out this was mostly the `file_entity` module running image alt en title tags through tokens, so that they could be overridden with another pattern if so desired:

```
// file_entity.file.inc:279

$alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
$title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
// a little further down the line in a loop
$output = token_replace($alt, array('file' => $file), $replace_options);
// a little further still
$output = token_replace($title, array('file' => $file), $replace_options);

```

That adds up to 2 calls to the token hook per file loaded. If you have a busy website with a fair amount of images, it adds up quickly. About 800 calls each time the homepage is loaded, specifically.

I think I'll patch the file\_entity module to cut out tokens for the default option, and verify it makes a difference speed-wise.

---
Tags: tokens
---