# Question
Title: How to execute login feature on Chrome browser
Just using Behat with drupal 8 and facing problem with login behat script to run. Below are the my code :

behat.yml

```
default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      base_url: http://localhost:8080/drupal-dev/web
      javascript_session: selenium2
      browser_name: 'chrome'
      selenium2: ~
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: drupal
      drupal:
        drupal_root: web/
      region_map:
        navigation: ".navbar-header"
        navigation_collapsible: "#navbar-collapse"
        header: ".region-header"
        highlighted: ".highlighted"
        help: ".region-help"
        content: ".region-content"
        sidebar_first: ".region-sidebar-first"
        sidebar_second: ".region-sidebar-second"
        footer: ".footer"

```

login.feature

```
@javascript
Feature: login check

Scenario: user login is working
  Given I am on "/user"
  When I fill in "john" for "edit-name"
  And I fill in "john for "edit-pass"
  And I press "Log in"
  Then I should see "Add content"

```

While i execute the vendor\bin\behat then it will open the chrome browser and redirect to user login page but failed from second step. See below error message :

```
@javascript
Feature: login check

  Scenario: user login is working             # features\bootstrap\login.feature:4
    Given I am on "/user"                     # Drupal\DrupalExtension\Context\MinkContext::visit()
    When I fill in "john" for "edit-name"   # Drupal\DrupalExtension\Context\MinkContext::fillField()
      Form field with id|name|label|value|placeholder "edit-name" not found. (Behat\Mink\Exception\ElementNotFoundException)
    And I fill in "john" for "edit-pass" # Drupal\DrupalExtension\Context\MinkContext::fillField()
    And I press "Log in"                      # Drupal\DrupalExtension\Context\MinkContext::pressButton()
    Then I should see "Add content"           # Drupal\DrupalExtension\Context\MinkContext::assertPageContainsText()

--- Failed scenarios:

    features\bootstrap\login.feature:4

1 scenario (1 failed)
5 steps (1 passed, 1 failed, 3 skipped)
0m15.30s (17.82Mb)

```

And same feature file working fine and all steps passed if i replaced from @javasript to @api.

# Answer
Just resolved the issue via changing selenium server version from 3.1 to 2.53
> 0 votes

# Answer
Here's a `@javascript` tagged scenario that's working for me.

```
Feature: Login testing.

  @javascript
  Scenario: Testing the user cant login with bas credentials.
    Given I visit "user/login"
    And I fill in "name" with "foo"
    And I fill in "pass" with "bar"
    When I press "op"
    Then I should see an ".error" element

```
> 0 votes

---
Tags: 8, testing
---


title: Drupal::httpClient() and proxy settings

text:
# Question
Title: Drupal::httpClient() and proxy settings
I've defined a proxy in my settings.php:

```
$settings['http_client_config']['proxy']['http'] = 'http://ip:port';
$settings['http_client_config']['proxy']['https'] = 'http://ip:port';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

```

In real I've replaced ip and port with nummeric values.

In a custom module I've defined:

```
$client = \Drupal::httpClient();
//$request = $client->get($this->source_url.'service=wms&request=getcapabilities');

```

These works, when Im not behind a proxy. How, can I add the proxy settings to this request?

```
$set =\Drupal\Core\Site\Settings::get('http_client_config');
$proxy = $set['proxy'];
//Get GetCapabilies.
$client = \Drupal::httpClient();
$request = $client->get($this->source_url.'service=wms&request=getcapabilities');

```

I don't find any way to add the proxy settings.

# Answer
> 1 votes
You can pass all http client config to the "client factory". You can also include your own custom settings.

```
$settings = \Drupal::service('settings');
$clientConfig = $settings->get('http_client_config') ?? [];
$client = \Drupal::service('http_client_factory')
                   ->fromOptions($clientConfig);

```

---
Tags: http-request
---


title: Author image in comments twig

text:
# Question
Title: Author image in comments twig
I succesfully get user name, surname and date to render in comment.html.twig like this

```
function MYTHEMENAME_preprocess_comment(&$variables) {
    $comment = $variables['comment'];
    $variables['user_name_comment'] = $comment->getOwner()->field_first_name->value;
    $variables['user_surname_comment'] = $comment->getOwner()->field_last_name->value;
    $variables['created'] = \Drupal::service('date.formatter')->format($variables['comment']->getCreatedTime(), 'conference_date');
}

```

In node template i got field\_picture to render like this

```
$variables['author_picture'] = $node->getOwner()->field_picture->entity->url();

```

But i can't get my **field\_picture** from user to render in comment twig file. I try to show the author's picture of every comment.

Any ideas?

# Answer
> 0 votes
When you want to display an entity field based on the "Manage Display" settings, you should go just `{{ content.my_field }}`. If you `"kint" content (var dump it)` you can see that each content field element has also "theme" key/property, which tells twig how to render that field

# Answer
> 0 votes
Create Template Preprocess Comment in your Theme file

```
function template_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $account = $comment->getOwner();
  $variables['user_picture'] = file_create_url($account->user_picture->entity->getFileUri());
}

```

---
Tags: theming, comments
---


title: Disable email user notifications

text:
# Question
Title: Disable email user notifications
It's possible in Drupal 8 disable all users notifications? New account, forgot password, etc

I'm using one external tool to send these emails and I don't need these notifications.

Thanks

# Answer
One of the easiest ways to make sure no emails are going out is to add

Mailcontrol (https://www.drupal.org/project/mailcontrol) which lets you specify what emails go out.

or

Maillog (https://www.drupal.org/project/maillog) which logs all emails and has an option to not send any emails to users. This will prevent all emails from leaving the system and log them if needed. It was designed to test sites but works well in this use case also.

Your other option is to go through and handle them one by one via code. There is no easy button inside of Drupal that will just turn off the service that I know of.

Sorry to just recommend a module, but given your needs this seems like a pretty obvious choice.
> 2 votes

# Answer
You may want to use mailsystem module. mailsytem

Then goto **Admin-\>Configuration-\>Mailsystem** and select *Mail Collector* option in both **Formatter** and **Sender** .

This collect the mail within the drupal system without actually sending it.

More info: Mail Collector
> 2 votes

# Answer
Here is the comprehensive set of solutions for addressing this problem in Drupal 7 and Drupal 8

Managing mail handling for development or testing on a Drupal 7/8 Site
> 0 votes

---
Tags: 8, users, emails
---


# Question
Title: Set new theme setting to default on theme update
**Working**

1. We have a custom base theme.
2. There are custom theme settings with default values.
3. When the theme is initially installed, the theme settings are correctly set as default. Good.
4. This custom base theme is now on our many live sites.

**Not working**

5. We added a new custom theme setting to the base theme, and set a default value.
6. When we update the base theme on a site, the new theme setting is there. Good.
7. However, the default value is not filled in.

**Question** How do I set the default value of a new theme setting when the theme is updated?

# Answer
> 4 votes
From what I can tell, themes do not process update hooks since they do not have a schema value tracked in the `key_value` table. So a `hook_update_N` is not possible in this case.

This means that you have a couple of options.

### Option 1

If the theme is going to be updated in code, but not updated right away through the UI form, you will probably want run a drush command as part of the theme update.

`drush config-set THEME.settings NEW_SETTING NEW_SETTING_VALUE'`

**Reference:** https://drushcommands.com/drush-8x/config/config-set/

This will allow you to set it once and then any future updates/overrides can be handled as usual through the configuration system.

### Option 2

If you are talking about a theme that is part of a distribution, and you don't have access to the system to run the drush command, then you could set a default value on the `hook_form_system_theme_settings_alter` function. This would not provide the value to the system when it loads the config, but it would provide a default to users when they update the theme and save the settings form.

If you did it that way, you would need to provide a fallback in your theme for if/when that value is not present to prevent unexpected behavior if the new setting value isn't yet set in the site's settings file.

### Option 3

If you have access to the codebases for the affected systems, like in a site factory, then you could technically provide the new value in the exported configuration file itself and then it would be picked up upon config import.

---
Tags: 8
---


# Question
Title: Limit Webform Submission to one per quarter per user
I need to limit one webform submission per quarter. For each quarter, the user can only make one submission. I want to use one webform. Here are some examples of the date period and the due date. How can I achieve the desired outcome with Webforms?

* Q1 (Oct. 1, 2019 – Dec. 30, 2019): due by Jan. 15, 2020
* Q2 (Jan. 1, 2020 – Mar. 30, 2020): due by Apr. 15, 2020
* Q3 (Apr. 1, 2020 – Jun. 30, 2020): due by Jul. 15, 2020

# Answer
ok so here is how to do that.. you need to create a module and set Drupal cron to run once a day on your hosting provider then you need your webform to have email unique then do this ....

```
/**
 * Implements hook_cron().
 */
function YOURMODULE_cron() {
  $current_month = date('m');
  // Get first month of quarter
  $new_month = (3 * floor(($current_month - 1 ) / 3)) + 1;
  $new_month = substr('0' . $new_month, -2);
  $first_quarter_day_date = date('Y') . '-' . $new_month . '-01';
  $today = date('Y-m-d');
  // So this is the first day of the quarter.
  if ($first_quarter_day_date == $today) {
    // Use cache to make sure this runs once.
    $cid = 'clear_out_webform_date';
    $cached = \Drupal::cache()->get($cid);
    $run = TRUE;
    if (!empty($cached)) {
      if (!empty($cached->data['date'])) {
        if ($cached->data['date'] == $today) {
          $run = FALSE;
        }
      }
    }

    if ($run == TRUE) {
      // change this to your webform id
      $webform_id = 'contact';

      // Export all submissions to file.
      $webform = \Drupal\webform\Entity\Webform::load($webform_id);
      $submission_exporter = \Drupal::service('webform_submission.exporter');
      $export_options = $submission_exporter->getDefaultExportOptions();
      $export_options['delimiter'] = ';';
      $export_options['multiple_delimiter'] = ',';
      $submission_exporter->setWebform($webform);
      $submission_exporter->setExporter($export_options);
      $submission_exporter->generate();
      $file_path = $submission_exporter->getExportFilePath();
      // rename the file to something good.
      $filename = $today.'-export.csv';
      $uri = 'public://' . $filename;
      $fileContent = file_get_contents($file_path);
      $destination = $uri;
      // Save the file to be a file entity.
      $file = file_save_data(
        $fileContent,
        $destination,
        FILE_EXISTS_RENAME
      );
      if (is_object($file)) {
        // Probably email your self a reminder here.
        // ^^ file is now an entity so you can do something like.
        // load a know entity and append the file to a document field.
        // or just download it as in the public file dir.

        // Delete previous quarter submissions.
        $query = \Drupal::entityQuery('webform_submission')
          ->condition('webform_id', $webform_id);
        $result = $query->execute();
        if (!empty($result)) {
          $webform_submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
          $submissions = $webform_submission_storage->loadMultiple($result);
          foreach ($submissions as $submission) {
            $submission->delete();
          }
        }
      }
      // set the cache to today so it wont run again.
      \Drupal::cache()->set($cid, ['date' => $today]);
    }
  }
}

```

have fun and good luck.
> 0 votes

---
Tags: webforms
---


# Question
Title: How to create a default image per taxonomy term?
I want to associate a different default image with each taxonomy term.

I saw this module - https://www.drupal.org/project/taxonomy\_image \- but it's in alpha.

Anyone got any recommendations how to do this?

Many thanks!

# Answer
When creating a vocabulary you can add a image field this is the only way to add a default image for all future taxonomy terms (in that vocab) so then when you create the term you would simply add your image to that term be it "default" or other.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Taxonomy Term View with Expose filter Dropdown of Terms Name
I Have a view of Taxonomy and "not Content". In this View I want a Expose filter of Term Name. But when ever i add Term Name as expose taxonomy's filter it shows text box and not Dropdown.

Without using relationship with content is it possible to get Dropdown filter of term's name as expose filter in Drupal 8 ?

# Answer
to get a dropdown filter you dont have to choose the taxonomy name rather the taxonomy term and select the vacabulary.

You follow this steps to get what you need :

1- https://monosnap.com/direct/Zw1q6Ww9If5vQZAAQsvysCt3TmL4L7

2- https://monosnap.com/direct/P4YbmYcXooNk7eLd1kev5y9sRyxekW

3- https://monosnap.com/direct/7gI69kySC5ciKtaBeBtbRRkCQS9Mf1)
> 0 votes

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


# Question
Title: Injecting metadata into all nodes within one folder
For my school I need to add metadata into the tag of every node/page within the folder /course/

The metadata is the same for every page in this folder:

```
<meta class="swiftype" name="tags" data-type="string" content="course" />

```

This will allow me to use weighting for all our course pages in the Swiftype search app.

I've narrowed it down to the html.html.twig file in \core\modules\system\templates - where I believe I need to be adding something along the lines of:

```
if (preg_match('$^course/', $_SERVER['REQUEST_URI']])) { print_metatag }

```

But I won't be wanting to use print\_metatag. Instead I should be using the fixed metadata referenced above.

Can anyone help me figure out what I need to use, and where, to apply this metadata to all those /course/ nodes/pages.

Many thanks!

# Answer
You won't be able to use PHP like that in Twig, but your logic isn't far off. One of the reasons Drupal 8 switched to using Twig was to avoid having potentially unsafe PHP in template files – this sort of thing generally belongs in a module rather than in a template, especially as it's not related to the presentation of content.

Drupal doesn't have a concept of folders, but we can look at the path of the content (e.g. `/courses/drupal-development` or `/contact-us` or `/news/2018/cool-thing-that-happened`) and work out if it's 'under' courses or not that way.

Something like this *should* work, but is untested:

```
/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$page) {
  $current_path = \Drupal::service('path.current')->getPath();
  $exploded_path = explode('/', $current_path);

  // Add Swiftype metatag, see https://swiftype.com/documentation/site-search/crawler-configuration/meta-tags.
  if ($exploded_path[1] === 'courses') {
    $metatag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'tags',
        'data-type' => 'course',
        'class' => 'swiftype',
        'content' => 'course',
      ],
    ];

    $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
  }
}

```

Or to do it by content type:

```
/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->getType() === 'instance') {
      $metatag = [
        '#tag' => 'meta',
        '#attributes' => [
          'name' => 'tags',
          'data-type' => 'course',
          'class' => 'swiftype',
          'content' => 'course',
        ],
      ];

      $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
    }
  }
}

```

If you need help setting up a module then take a look at https://befused.com/drupal/first-drupal8-module \- but you can stop once you've created a `your_module_name.module` file – this is the file that the code above will go into.
> 2 votes

# Answer
The answer linked in the comments is for a render array you build yourself. If you want to attach something to an existing render array you would need to look for a render element (#theme, #type, #markup) you can attach it to. You could look for such a render element in $variables, but a preprocess hook is an exception to this rule. Here the (only) officially supported method of attaching bubbleable metadata (#cache, #attached) is the top level of $variables, even if there is no render element. Drupal looks for such metadata and bubbles it up.

Example:

```
/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {

  if ($variables['node']->getType() == 'article' && $variables['view_mode'] == 'full') {

    $metatag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'tags',
        'data-type' => 'course',
        'class' => 'swiftype',
        'content' => 'course',
      ],
    ];

    $variables['#attached']['html_head'][] = [$metatag, 'swiftype_course'];

  }
}

```
> 2 votes

# Answer
So there are three methods really.

1. I won't go over, since it is what Phil said
2. Create a custom module extending metatag. This is in many way ideal, but is the most complicated method. Given your stated experience level, this is likely a challenge, and probably not worth it for such a static option.
3. Use the html template you identified. For this just copy `core/themes/classy/templates/layout/html.html.twig` to `%your_theme/templates/layout/` as `html--node--instance.html.twig`. Or if you you already have an `html.html.twig` in yuor theme, copy that to the new name. Then add your metatag directly into the new template.

Do note that any of those three options will require you to clear caches or they won't take effect.
> 1 votes

---
Tags: 8
---


title: Error while updating

text:
# Question
Title: Error while updating
Updated Drupal from 8.7.8 to 8.8.0 with:

```
composer update --with-dependencies

```

That part went well, but when I run:

```
drush updb

```

I get following error:

```
In ProcessBase.php line 188:

  Unable to decode output into JSON: Syntax error

  Error: Call to a member function getConfigDependencyKey() on null in Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid-
  >calculateDependencies() (line 394 of /var/www/html/drupal/web/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndex
  Tid.php).

```

Checked the code a bit and it goes like:

```
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

    $vocabulary = $this->vocabularyStorage->load($this->options['vid']);
    $dependencies[$vocabulary->getConfigDependencyKey()][] = $vocabulary->getConfigDependencyName(); // <-- line 394

...

```

And `$this->options['vid']` is empty and `$vocabulary` var becomes null.

Any idea what's wrong here?

# Answer
> 2 votes
just to make you aware in case you're using the Pathauto module and you didn't notice:

> Changes to path aliases and a critical note for sites using the Pathauto contributed module If you have the contributed Pathauto module enabled, you must update to the latest version of Pathauto **before** you update to Drupal 8.8.0. Failure to update Pathauto before updating core could result in data loss. Drupal 8.8.0 declares a conflict with Pathauto 8.x-1.5 or lower for this reason.

https://www.drupal.org/project/drupal/releases/8.8.0

Can't say anything about your specific error though.

---
Tags: 8, updating
---


# Question
Title: How do I prevent a Node from being deleted?
I want to make some checks and, under certain circumstances, prevent a node from being deleted.

My module makes checks in `HOOK_form_BASE_FORM_ID_alter()` when the node is being created, but I cannot see where I can get control when the node is being deleted.

# Answer
This does what I want.

The *Agenda* Node cannot be deleted if there are any *Meeting* Nodes that refer to it.

Ideally, I’d have preferred that the validation handler would be called when the user clicked the *Delete* on the primary tasks tabs whereas it is called on the confirmation form. Good enough, though.

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

function agenda_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    // ...
    case "node_agenda_delete_form":
      $form['#validate'][] = '_agenda_delete_validation';
      break;
    // ...
  }
}

function _agenda_delete_validation(&$form, FormStateInterface $form_state) {
  $agenda_node = $form_state->getFormObject()->getEntity();
  $agenda_name = $agenda_node->getTitle();
  $agenda_node_id = $agenda_node->id();
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'meeting')
    ->condition('field_agenda', $agenda_node_id);
  $nids = $query->execute();
  $count_nids = count($nids);
  if ($count_nids > 0) {
    $msg_stem = ($count_nids == 1) ? 'There is one Meeting that references "' : 'There are '.$count_nids.' Meetings that reference "';
    $form_state->setError($form, $msg_stem.$agenda_name.'". It cannot be deleted yet.' );
  }
}

```

With many thanks to @Clive and @Berdir who gave great answers that I was able to follow up.
> 5 votes

# Answer
Using `hook_node_access()` is one option:

```
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

...

function MYMODULE_node_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'delete') {
    if (some_access_function($entity, $account)) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

  return AccessResult::neutral();
}

```

This method has the advantage of preventing deletion through other methods (e.g. REST) at the same time, and will automatically remove the delete link and tab from the node form anyway.
> 16 votes

# Answer
What kind of check?

What's easy is to prevent delete *access*. Implement the hook `hook_node_access(NodeInterface $node, $operation, AccountInterface $account)` and return AccessResult::forbidden() if your condition matches for $operation delete.

That doesn't prevent deletion through the API but it will automatically hide any delete button/link/action in the UI and users won't be able to delete that node.
> 8 votes

# Answer
For Drupal 8

There is a module prevent node delete

https://www.drupal.org/project/prevent\_node\_delete
> 1 votes

---
Tags: nodes, 8
---


title: Run code once on each page load

text:
# Question
Title: Run code once on each page load
In the past there were some hooks, such as described here: How to run check on each page load?

to execute arbitrary code on each page load.

Now this has been replaced with an event based approach. I wrote this to check it out:

```
class MyModuleEventSubscriber implements EventSubscriberInterface {
    public function onLoad(GetResponseEvent $event) {
        \Drupal::logger('my_module')->info('test');
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[KernelEvents::REQUEST][] = ['onLoad'];

        return $events;
    }
}

```

However, it seems like there is any number of requests on each page load—it actually captures each request, and in my case there are five (5). My intended code, however, has to call an outside API, and I'd like to avoid unnecessary calls.

Is there an event that is guaranteed to run just once on each page load, without saving a state on my side (that seems quite complicated for this problem)?

# Answer
> 0 votes
You can see an article on the subject here without using Events

https://chromatichq.com/blog/replacing-hookboot-and-hookinit-functionality-drupal-8

Possible that it will meet your needs.

> **Replacing hook\_boot and hook\_init Functionality in Drupal 8**
>
> The change notice page states:
>
> Using StackMiddleware
>
> This comment on the hook\_boot change notice page provides an example of using StackMiddleware. It provides 95% of the functionality needed to run logic on cached pages by utilizing a tagged service with the http\_middleware tag. Since the new class is a service, it will have full access to other core and contrib services, allowing for much greater functionality. The example shows the following for a module’s \*.services.yml file:
>
> ```
> services:   http_middleware.mymodule:
>   class: Drupal\mymodule\StackMiddleware\MyModule
>   tags:
>     - { name: http_middleware, priority: 180, responder: true }
>
> ```
>
> This is a pretty standard service definition, but note the items added to the tags property that register our service with the http\_middleware tag and also set a priority. In order to bypass the page cache, understanding the page\_cache.services.yml file is helpful. There, a similar definition can be found, but with a higher priority value.
>
> ```
> services:   http_middleware.page_cache:
>     class: Drupal\page_cache\StackMiddleware\PageCache
>     arguments: ['@cache.render', '@page_cache_request_policy', '@page_cache_response_policy']
>     tags:
>       - { name: http_middleware, priority: 200, responder: true }
>
> ```
>
> Higher priority services are run first. So to trigger logic before the page cache module takes over the request, a priority greater than 200 is needed.
>
> ```
> services:   http_middleware.mymodule:
>     class: Drupal\mymodule\StackMiddleware\MyModule
>     tags:
>       - { name: http_middleware, priority: 210, responder: true }
>
> ```
>
> With this change in the services files, and proper setup of the service as described by the comment, the http\_middleware.mymodule service should now be called on every page load, even on fully cached pages.
>
> ```
> namespace Drupal\example\StackMiddleware;
>
> use Symfony\Component\HttpFoundation\Request;
> use Symfony\Component\HttpKernel\HttpKernelInterface;
>
> /**
>  * Performs a custom task.
>  */
> class ExampleStackMiddleware implements HttpKernelInterface {
>
>   /**
>    * The wrapped HTTP kernel.
>    *
>    * @var \Symfony\Component\HttpKernel\HttpKernelInterface
>    */
>   protected $httpKernel;
>
>   /**
>    * Creates a HTTP middleware handler.
>    *
>    * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
>    *   The HTTP kernel.
>    */
>   public function __construct(HttpKernelInterface $kernel) {
>     $this->httpKernel = $kernel;
>   }
>
>   /**
>    * {@inheritdoc}
>    */
>   public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
>     // Custom logic goes here.
>
>     return $this->httpKernel->handle($request, $type, $catch);
>   }
> }
>
> ```
>
> Verifying the Results
>
> A quick and easy way to test all of this is to simply add `\Drupal::logger('test')->notice(‘not cached’)`; into the functions triggered by each of the approaches above. Ensure that the Drupal cache is enabled, and simply refresh a page while watching your log (drush ws --tail). Then verify the logic is being called as expected.

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


# Question
Title: I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick
I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick.

I added a css file and edited the slick skin php file to use the css file depending on the user's choice. I also added a bootstrap class to the slick.html.twig template so that the slider would disappear on mobile devices.

Should I make a custom module that acts like slick\_examples?

# Answer
In my opinion, the easiest way to preserve changes to contributed code is to manage your dependencies through Composer and use patches. When you update slick in the future, the output of the command will directly tell you which of your patches have been broken by the update.
> 4 votes

# Answer
As far a I can tell from your description of the changes you've made, you should be able to implement all of these in a custom module.

That should save you the trouble of patching existing modules.
> 0 votes

# Answer
i thought that you can override or extend controllers or plugin, its the only way to preserve the changes after updates
> -1 votes

---
Tags: 8, updating
---


# Question
Title: Latest update to 8.7 with Commerce caused Edit buttons to appear in place of shipping/billing information
After updating core to 8.7, the input fields for shipping and billing information are now hidden and Edit buttons are in their place. This has allowed users to checkout without entering shipping and billing information. How can I show the required fields by default and get rid of the Edit button?

# Answer
> 3 votes
It looks like you have Commerce AutoSKU installed. The authors of the module modify one of Drupal's validation constraints which checks if fields are empty or not. This causes the addressbook form element to break, which what you're seeing, on top of other problems.

The issue is reported here, https://www.drupal.org/project/commerce\_autosku/issues/3086828

The solution is to either uninstall the commerce\_autosku module *or* apply the patch in comment #3: https://www.drupal.org/files/issues/2019-10-18/3086828-3.patch

---
Tags: commerce
---


# Question
Title: Display the URL of where the content is located in my search results
I'm using SOLR search/search API on my Drupal 8 site and I've set the view to display the following two fields:

* Content datasource: Title *(The title & link to the page)*
* Search: Excerpt *(Highlighted text of the searched keywords found on the page)*

I would also like to display the URL of the page that the content is located below those two fields. However, there is no URL field to add. I've also tried to get just the URL from the 'Title' field, but can't seem to get it from there either.

Below is an example of what I'm trying to achieve.

Would anyone have any ideas as to how to add that at all?

# Answer
> 1 votes
Search API provides several general fields (e.g. Aggregated field, Rendered HTML output, URI, etc.) which are available to all Datasources.

Edit your index, when on the Fields tab, click Add fields and under the General heading add URI. You will need to re-index your content and the new fields should be available.

---
Tags: views, 8, search
---


# Question
Title: Ckeditor Wordcount plugin - How to target specific textareas
I'm using the CKEditor - WYSIWYG HTML editor Drupal 7 module and wordcount plugin. I've added the wordcount plugin file in the ckeditor plugins directory and got it working, however my config max word and character count etc is the same for all fields. I would like to specify different max word and character counts for specific fields. Here is my config:

ckeditor.config.js

Using CKEDITOR.replace I did the following:

```
  CKEDITOR.replace('edit-body-und-0-summary',
      {
          extraPlugins: 'wordcount',
          wordcount: {
              showCharCount: true,
              maxCharCount: 123
          }
      });

```

This worked, but after refreshing the page it went back to the global max word and character count. The Textrea ID is `edit-body-und-0-summary` but this tag is repeated elsewhere in the page.

How do I go about adding a unique ID to the textarea tag and having different word counts for different fields e.g. Summary and Body fields

# Answer
I figured it out, hope this helps anyone else out there.

I added the following to my Adminimal Sub theme to add a class to the summary textarea:

```
function adminimal_sub_form_alter(&$form, &$form_state, $form_id) {
 if (isset($form['#node']) && $form['#node']->type == 'article') {
 // Add class to body textarea for various content types. This is used for the Ckeditor wordcount plugin to target summary textarea.
   $form['body']['und']['0']['summary']['#attributes']['class']['0'] = 'article-summary';
 }
}

```

Then downloaded the Ckeditor 4 Wordcount plugin and saved it in the plugins directory (sites/all/libraries/ckeditor/plugins).

In the Drupal UI I went to configuration \> CKEditor Filtered HTML (edit) and in the Custom Javascript configuration under Advanced options I added a path to my ckeditor.config.js (config.customConfig = '/sites/all/themes/global/js/ckeditor.config.js';).

This is my ckeditor.config.js:

```
CKEDITOR.editorConfig = function(config) {

 if (this.element.hasClass('article-summary')) {
 config.wordcount = {
    showCharCount: true,
    maxCharCount: 170
    }
}
// Make CKEditor's edit area as high as the textarea would be.
 if (this.element.$.rows > 0) {
    config.height = this.element.$.rows * 20 + 'px';
 }
}

```

Here I can set the maxwordcount and loads more besides, but for this project only needed the maxwordcount. This way if the Drupal Ckeditor module gets updated this file will not be affected.
> 0 votes

---
Tags: 7
---


# Question
Title: impossible to save source code in wysiwyg blocks if <a> does not contains some strings
It is impossible to use an icon as anchor in wysiwyg blocks.

```
<a href="https://myfburl"><i class="fab fa-facebook-f "></i></a>

```

The content is lost when editing back a block

it only works for strings

```
 <a href="https://myfburl">some text</a>

```

# Answer
If this only happens when a `Text format` is associated with a `WYSIWYG profile`, regardless of the format's `Text filters` or the `Editor` assigned to it, then try using a non-breaking space (` `) as the anchor text:

```
<a href="https://myfburl"><i class="fab fa-facebook-f "></i> </a>

```
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Altering UserPasswordForm redirect with a custom submit
I want to alter the redirect of UserPasswordForm from Drupal’s core, I did this

```
function maubl_user_form_alter(&$form, FormStateInterface $form_state, $form_id){
switch($form_id) {
case 'user_pass':
    $form['actions']['submit']['#submit'][] = 'maubl_user_submit_forgot_pass';
    break;
}
function maubl_user_submit_forgot_pass(&$form, \Drupal\Core\Form\FormStateInterface $formState){

  $formState->setRedirect('<front>');

}

```

It does do the redirect correctly, but the submit from UserPasswordForm doesnt excute anymore, so the mail doesnt get sent, does anyone know why and how I can fix that ?

# Answer
By adding a submit handler to the submit element you override the main submit handler attached to the form. The use case for this option is if you want a submit element to have a completely different action.

Append your submit handler to the form and it should work as you have intended:

```
$form['#submit'][] = 'maubl_user_submit_forgot_pass';

```
> 0 votes

---
Tags: 8, forms, hooks
---


# Question
Title: How to copy/clone menu of a node when clone with Entity Clone module?
When cloning a node using Entity Clone module, the menu link are not copied. As menu link item is created and managed on the node form level, there is no reference of the menu link item in the node entity level. See menu\_ui\_form\_node\_form\_alter for more details.

# Answer
> 1 votes
Issue #2839833 has a proposal to add entity clone plugin to node entity to handle this special case.

Alternatively, we could use the event. Luckily Entity Clone module dispatches an event before & after clone for the other modules to act. Here is the code for menu copy:

```
  // mymodule.services.yml

 mymodule.entity_clone.subscriber:
    class: Drupal\mymodule\EventSubscriber\EntityCloneSubscriber
    tags:
      - { name: 'event_subscriber' }

```

Subscribe to the post clone event:

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Entity\EntityInterface;
use Drupal\entity_clone\Event\EntityCloneEvent;
use Drupal\entity_clone\Event\EntityCloneEvents;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\node\NodeInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Crates menu item after node clone.
 */
class EntityCloneSubscriber implements EventSubscriberInterface {

  /**
   * Entity post clone handler.
   *
   * @param \Drupal\entity_clone\Event\EntityCloneEvent $event
   *   An event object.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function onPostClone(EntityCloneEvent $event) {
    $entity = $event->getEntity();

    // Act only on node clone.
    if (!($entity instanceof  NodeInterface)) {
      return;
    }
    $cloned_entity = $event->getClonedEntity();
    $values = menu_ui_get_menu_link_defaults($entity);

    // Copy menu item, if available.
    if (!empty($values['entity_id'])) {
      $this->cloneNodeMenuLinkContent($cloned_entity, $values);
    }
  }

  /**
   * Clones menu link content associated with the node.
   *
   * @param \Drupal\Core\Entity\EntityInterface $cloned_entity
   *   Cloned node.
   * @param array $values
   *   An array of menu link content values.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function cloneNodeMenuLinkContent(EntityInterface $cloned_entity, array $values) {
    $menu_item = MenuLinkContent::load($values['entity_id']);
    $menu_name = $values['menu_name'];

    // Create new menu link content with original value.
    $cloned_menu_item = MenuLinkContent::create([
      'link' => ['uri' => 'entity:node/' . $cloned_entity->id()],
      'langcode' => $cloned_entity->language()->getId(),
    ]);
    $cloned_menu_item->enabled->value = $menu_item->isEnabled() ? 1 : 0;
    $cloned_menu_item->title->value = trim($cloned_entity->getTitle());
    $cloned_menu_item->description->value = trim($values['description']);
    $cloned_menu_item->menu_name->value = $menu_name;
    $cloned_menu_item->parent->value = $values['parent'];
    $cloned_menu_item->weight->value = isset($values['weight']) ? $values['weight'] : 0;
    $cloned_menu_item->save();
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[EntityCloneEvents::POST_CLONE][] = ['onPostClone', 200];
    return $events;
  }

}

```

---
Tags: 8, entities
---


title: Display view on all page routes

text:
# Question
Title: Display view on all page routes
I would like to display a multi value media field and its file type and size in a content type and display it in a table layout. I thought using a view would be the best way to pull the media file type and file size and any references it has using views relations.

The view uses Relations to get the media type and size and uses a Contextual filter - Content ID from URL. Now I am printing the display in a node template like this using Twig tweak.

{{ drupal\_view('materials', 'block\_1') }}

The table and media values display fine when published on route entity.node.canonical.

But the media values do not display on other routes and tabs like /latest routename entity.node.latest\_version and /full routename entity.node.preview. The table markup displays but not the media values inside. I have tried printing the view using the drupal\_block method and had the same results.

# Answer
The content id is missing from your function call you have to add it like this

{{ drupal\_view('who\_s\_new', 'block\_1', arg\_1, arg\_2, arg\_3) }}

or you can render your view in custom block and add it in every page via 'block layout'

https://www.webwash.net/programmatically-create-block-drupal-8/

```
$view = views_get_view('view_name');
$view->set_display('view_block_name');
$view->set_arguments(array($tid));
// change the amount of items to show
$view->set_items_per_page(4);
$view->pre_execute();
$view->execute();
$view->render();

```
> 0 votes

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


# Question
Title: How do I theme a link from a template file?
A twig template is rendering a list of links that come with classes. The basic:

```
{{ mylink }}

```

twig code will output something like

```
<a href="#" class="someclass" >the text</a>

```

Not all links have classes. I want to write a twig template that will instead output something like this:

```
<a href="#" class="someclass" >
  <span class="sprite someclass" ></span>
  the text</a>

```

What I've tried:

1. I looked for the twig template to override. Unfortunately it seems that links are not rendered by a twig template.
2. I tried updating the twig variable like

```
set mylink['#title'] = "<span>...</span>" ~ mylink['#title']

```

But it won't let me do that.

# Answer
Here's a twig only solution for a particular field that needs this treatment; it's not a generic solution for all links everywhere.

some-template.twig:

```
<ul class="field--name-field-links">
  {% for item in content.field_links %}
  {% if item['#title'] %}
    <li>
      <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >
        {% if item['#options']['attributes']['class'] %}
          <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>
        {% endif %}
        {{ item['#title'] }}
      </a>
    </li>
  {% endif %}
  {% endfor %}
</ul>

```
> 8 votes

# Answer
I'm not found a way to change link '#markup' in twig, but there is way to change it on render phase.
I made this little module that extend Link functionality and make it able to inject some stuff on rendered link. So lets do some code, I will explain in comments...

## **Module file structure:**

```
better_link
 | - src
   | - Element
     | BetterLink.php
   | - Plugin
     | - FieldFormatter
       | BetterLinkFormatter.php
 | better_link.info.yml
 | better_link.module

```

## File contents:

**better\_link.info.yml**

```
name: 'Better link'
type: module
package: 'Field types'
description: 'A very nice better link'
core: '8.x'
dependencies:
  - field
  - link

```

**better\_link.module**

```
<?php

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 * Just some words about the module.
 */
function better_link_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.better_link':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Provide a improved link formatter and renderer for a custom link markup.') . '</p>';
      $output .= '<p>' . t('Will be added a span html tag right before link content.') . '</p>';
      $output .= '<p>' . t(' - Link class can be added throught manage display.') . '</p>';
      $output .= '<p>' . t(' - Span class can be added throught manage display.') . '</p>';
      return $output;
  }
}

```

**BetterLinkFormatter.php**

```
<?php

/**
 * @file
 * Contains \Drupal\better_link\Plugin\Field\FieldFormatter\BetterLinkFormatter.
 */

namespace Drupal\better_link\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Form\FormStateInterface;
use Drupal\link\Plugin\Field\FieldFormatter\LinkFormatter;

/**
* Plugin implementation of the 'better_link' formatter.
*
* @FieldFormatter(
*   id = "better_link",
*   label = @Translation("Better Link"),
*   field_types = {
*     "link"
*   }
* )
*/
class BetterLinkFormatter extends LinkFormatter {
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = parent::defaultSettings();
    //Keeping simple...
    $settings['span_class'] = '';
    $settings['link_class'] = '';
    //... but feel free to add, tag_name, buble_class, wraper_or_inside
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);
    //Make sure that you always store a name that can be used as class
    $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));
    $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));
    $this->setSettings($settings);

    $form['link_class'] = array(
      '#title' => $this->t('Inject this class to link'),
      '#type' => 'textfield',
      '#default_value' => $settings['link_class'],
    );
    $form['span_class'] = array(
      '#title' => $this->t('Inject this class to span'),
      '#type' => 'textfield',
      '#default_value' => $settings['span_class'],
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();
    //Same here. Somehow if you use setSettings here don't reflect in settingsForm
    $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));
    $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));
    $this->setSettings($settings);

    //Summary is located in the right side of your field (in manage display)
    if (!empty($settings['link_class'])) {
      $summary[] = t("Class '@class' will be used in link element.", array('@class' => $settings['link_class']));
    }
    else {
      $summary[] = t('No class is defined for link element.');
    }

    if (!empty($settings['span_class'])) {
      $summary[] = t("Class '@class' will be used in span element.", array('@class' => $settings['span_class']));
    }
    else {
      $summary[] = t('No class is defined for span element.');
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = parent::viewElements($items, $langcode);
    //Yeah, here too, same 'problem'.
    $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));
    $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));

    foreach ($items as $delta => $item) {
      //Lets change the render element type and inject some options that will
      //be used in render phase
      if (isset($elements[$delta]['#type'])) {
        $elements[$delta]['#type'] = 'better_link';
        $elements[$delta]['#options']['#link_class'] = $settings['link_class'];
        $elements[$delta]['#options']['#span_class'] = $settings['span_class'];
      }
    }
    //Next step, render phase, see ya...
    return $elements;
  }
}

```

**BetterLink.php**

```
<?php

/**
 * @file
 * Contains \Drupal\better_link\Element\BetterLink.
 */

namespace Drupal\better_link\Element;

use Drupal\Core\Render\Element\Link;

/**
 * Provides a better_link render element. Almost the same as link.
 *
 * @RenderElement("better_link")
 */
class BetterLink extends Link {
  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return array(
      '#pre_render' => array(
        array($class, 'preRenderLink'),
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function preRenderLink($element) {
    //Hello again. Lets work.
    //Before Drupal create the rendered link element lets inject our stuff...
    //...Our class to link
    $element['#options']['attributes']['class'][] = $element['#options']['#link_class'];
    //...Build span classes
    $span_classes = $element['#options']['#span_class'] . ' ' . $element['#options']['#link_class'];
    //...And get rid them.
    unset($element['#options']['#link_class']);
    unset($element['#options']['#span_class']);
    //Lets Drupal do the hard work
    $element = parent::preRenderLink($element);
    //Here is where the magic happens ;)
    if (!empty($element['#markup'])) {
      //Inject our span right before link content.
      $element['#markup'] = str_replace('">', "\"><span class='$span_classes'></span>", $element['#markup']);
      //Side comment - Thank you spaceless, str_replace can be used here
    }
    //Now, whatever you change in your url or another object will not maintain,
    //the only thing that will be returned in the end is
    //$element['#markup'], so this is the only thing you can change.
    return $element;
  }
}

```

## Important:

This will work for all of your **link fields**, sure, if you change its formatter in manage display (editing your node type).

I hope that can be useful.

Request to @artfulrobot: Can you test this module? I think that translate issue can be solved this way.
> 7 votes

# Answer
you can just add a render array to #title, like:

```
['#title'] = array('#markup' => '<i class="my-icons">yummy</i>' . $item['content']['#title']);

```

---

## Old long answer:

You can override the link generator service

Create a module (alternative\_linkgenerator), with an info file alternative\_linkgenerator.info.yml

```
name: Alternative LinkGenerator
type: module
description: Adds alternative link generation.
core: 8.x

```

Make a file called alternative\_linkgenerator.services.yml

```
services:
  alternative_linkgenerator.link_generator:
    class: Drupal\alternative_linkgenerator\AlternativeLinkGenerator

```

Next is to create the class, add a folder named “src” (following PSR-4 autoloading standards) and within this a file called AlternativeLinkGenerator.php. (This is a 1:1 copy, you need to adapt the things for your)

```
class AlternativeLinkGenerator extends LinkGeneratorInterface {

  /**
   * The url generator.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

  /**
   * The module handler firing the route_link alter hook.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a LinkGenerator instance.
   *
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The url generator.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   */
  public function __construct(UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_handler, RendererInterface $renderer) {
    $this->urlGenerator = $url_generator;
    $this->moduleHandler = $module_handler;
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public function generateFromLink(Link $link) {
    return $this->generate($link->getText(), $link->getUrl());
  }

  /**
   * {@inheritdoc}
   *
   * For anonymous users, the "active" class will be calculated on the server,
   * because most sites serve each anonymous user the same cached page anyway.
   * For authenticated users, the "active" class will be calculated on the
   * client (through JavaScript), only data- attributes are added to links to
   * prevent breaking the render cache. The JavaScript is added in
   * system_page_attachments().
   *
   * @see system_page_attachments()
   */
  public function generate($text, Url $url) {
    // Performance: avoid Url::toString() needing to retrieve the URL generator
    // service from the container.
    $url->setUrlGenerator($this->urlGenerator);

    if (is_array($text)) {
      $text = $this->renderer->render($text);
    }

    // Start building a structured representation of our link to be altered later.
    $variables = array(
      'text' => $text,
      'url' => $url,
      'options' => $url->getOptions(),
    );

    // Merge in default options.
    $variables['options'] += array(
      'attributes' => array(),
      'query' => array(),
      'language' => NULL,
      'set_active_class' => FALSE,
      'absolute' => FALSE,
    );

    // Add a hreflang attribute if we know the language of this link's url and
    // hreflang has not already been set.
    if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {
      $variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();
    }

    // Ensure that query values are strings.
    array_walk($variables['options']['query'], function(&$value) {
      if ($value instanceof MarkupInterface) {
        $value = (string) $value;
      }
    });

    // Set the "active" class if the 'set_active_class' option is not empty.
    if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {
      // Add a "data-drupal-link-query" attribute to let the
      // drupal.active-link library know the query in a standardized manner.
      if (!empty($variables['options']['query'])) {
        $query = $variables['options']['query'];
        ksort($query);
        $variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);
      }

      // Add a "data-drupal-link-system-path" attribute to let the
      // drupal.active-link library know the path in a standardized manner.
      if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {
        // @todo System path is deprecated - use the route name and parameters.
        $system_path = $url->getInternalPath();
        // Special case for the front page.
        $variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;
      }
    }

    // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
    // only when a quick strpos() gives suspicion tags are present.
    if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
      $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
    }

    // Allow other modules to modify the structure of the link.
    $this->moduleHandler->alter('link', $variables);

    // Move attributes out of options since generateFromRoute() doesn't need
    // them. Include a placeholder for the href.
    $attributes = array('href' => '') + $variables['options']['attributes'];
    unset($variables['options']['attributes']);
    $url->setOptions($variables['options']);

    // External URLs can not have cacheable metadata.
    if ($url->isExternal()) {
      $generated_link = new GeneratedLink();
      $attributes['href'] = $url->toString(FALSE);
    }
    else {
      $generated_url = $url->toString(TRUE);
      $generated_link = GeneratedLink::createFromObject($generated_url);
      // The result of the URL generator is a plain-text URL to use as the href
      // attribute, and it is escaped by \Drupal\Core\Template\Attribute.
      $attributes['href'] = $generated_url->getGeneratedUrl();
    }

    if (!SafeMarkup::isSafe($variables['text'])) {
      $variables['text'] = Html::escape($variables['text']);
    }
    $attributes = new Attribute($attributes);
    // This is safe because Attribute does escaping and $variables['text'] is
    // either rendered or escaped.
    return $generated_link->setGeneratedLink('<a' . $attributes . '>' . $variables['text'] . '</a>');
  }

}

```

Edit services.yml (normally at sites/default/services.yml in your Drupal 8 codebase) and add the following:

```
  services:
    link_generator:
      alias: alternative_linkgenerator.link_generator

```

props goes here
> 4 votes

# Answer
try this code:

```
{% if links -%}
  {%- if heading -%}
    {%- if heading.level -%}
  <{{ heading.level }}{{ heading.attributes }}>{{ heading.text }}</{{ heading.level }}>
{%- else -%}
  <h2{{ heading.attributes }}>{{ heading.text }}</h2>
   {%- endif -%}
  {%- endif -%}
  <ul{{ attributes }}>
{%- for item in links -%}
  <li{{ item.attributes }}>
        {%- if item.link -%}

    <!--{{ item.link }} this line must stay -->

    <a href="{{ item.link['#url'] }}"
      {{ item.attributes.addClass(classes) }}
      {{ item.attributes.setAttribute('title', item.text ) }}
      {{ item.attributes.setAttribute('lang', item.link['#options'].language.id ) }}
      {{ item.attributes.setAttribute('aria-label', item.text ) }}>
        <img alt="{{ item.link['#title'] }}" src="/themes/subtheme/img/flag_{{ item.link['#options'].language.id }}.jpg" class="align-center">
    </a>

    {%- elseif item.text_attributes -%}
      <span{{ item.text_attributes }}>{{ item.text }}</span>
    {%- else -%}
      {{ item.text }}
    {%- endif -%}
  </li>
{%- endfor -%}

```

{%- endif %}

or this one (it comes from: https://github.com/liip/bund\_drupal\_starterkit\_theme/blob/master/templates/navigation/links--language-block.html.twig):

```
{% if links and links|length > 1 -%}
  <ul>
    {%- for item in links -%}
      <li>
        {%- if item.link -%}

      <!--{{ item.link }} to do: remove this line without breaking the urls -->

      {% if item.link['#options'].language.id == current_language %}
        {% set classes = ['active'] %}
      {% else %}
        {% set classes = [''] %}
      {% endif %}
      {% set url = path(item.link['#url'].routeName, item.link['#url'].routeParameters, item.link['#url'].options) %}

    {%- else -%}
      {% set classes = ['disabled'] %}
      {% set url = '#' %}
    {%- endif -%}

    <a href="{{ url }}"
      {{ item.attributes.addClass(classes) }}
      {{ item.attributes.setAttribute('title', item.text ) }}
      {{ item.attributes.setAttribute('lang', item.link['#options'].language.id ) }}
      {{ item.attributes.setAttribute('aria-label', item.text ) }}>
        {{ item.link['#options'].language.id | upper }}
    </a>
  </li>
{%- endfor -%}
  </ul>
{%- endif %}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Entity Validator failing Integer for not being integer
I have a custom entity with an integer field with the following baseFieldDefinition:

```
    $fields['permission_level'] = BaseFieldDefinition::create('integer')
    ->setLabel(t("Permission Level"))
    ->setDescription(t("Sets amount of permissions owner has"))
     ->addConstraint('Range', ['min' => 0])
    ->setDefaultValue(0)
    ->setDisplayOptions('form', [
      'type' => 'number'
    ]);

```

because of the `->addConstraint('Range', ['min' => 0])`, drupal throws an error anytime I try to create an entity through either the `drupal generate:entity:content` generated boilerplate form or json:api post requests.

I have used Xdebug to narrow the issue to the constraint validator range. Something is passing a FieldListItem object instead of an integer to this constraint validator causing it to fail because its not an integer. The weird thing is that inside the FieldListItem object is the integer I input.

Why is drupal passing a FieldListItem object instead of an Integer?

# Answer
You can add constraints to entities, fields or properties. You get then an entity, field object (FieldItemList) or a value to validate. So if you want to check the field value use FieldConfigInterface::addPropertyConstraints:

```
->addPropertyConstraints('value', ['Range'=> ['min' => 0]])

```
> 0 votes

---
Tags: entities, forms
---


# Question
Title: Entering views result to field through rules
When I create a new OG, I would like the user with the least number of OG subscriptions automatically to be added to this group. So I created a views block where I count and least the user with the least number of OG subscriptions. Under actions, there is an option named `subscribe user to group`. Is there a way for me to use the views result in data selector of this action? Otherwise, how would you tackle this issue.

# Answer
> 0 votes
I created a sql query through the Views Rules module and it did the trick.

---
Tags: 7, views, rules, organic-groups
---


# Question
Title: How do you import a database through lando?
I am trying to setup a site within lando and need to import the database. How do you import a database through lando?

# Answer
`lando db-import <path to sql or sql.gz or .zip file here>` will do that for you.

`db-import` will drop all tables before performing the import. it has a `--no-wipe` flag that can be used if you *don't* want to drop tables first.

More information in the documentation: https://docs.lando.dev/guides/db-import.html
> 7 votes

# Answer
We need to run the following two commands to import database (to an existing site)

```
lando drush sql-drop
lando db-import <dbname>.gz

```
> 0 votes

---
Tags: 8
---


title: Last modified date in menu link

text:
# Question
Title: Last modified date in menu link
I have a book with some child pages and I'd like to show the last modified date of each corresponding node near them in their menu tree links, or a red badge near the nodes updated during eg. the last 3 days... How to pass the changed\_date of nodes to menu links?

Thank you

# Answer
> 0 votes
## Hook insert/update

The Book module update the book menu title during node insert/update.

You can implement hook\_node\_insert and hook\_node\_update to update the title in place.

```
/**
 * Implements hook_node_insert().
 */
function my_custom_module_node_insert($node) {
  if (!empty($node->book['bid'])) {
    $node->title = $node->title . format_date($node->changed, 'custom', 'M j, Y');
    _book_update_outline($node);
  }
}

/**
 * Implements hook_node_update().
 */
function my_custom_module_node_update($node) {
  if (!empty($node->book['bid'])) {
    $node->title = $node->title . format_date($node->changed, 'custom', 'M j, Y');
    _book_update_outline($node);
  }
}

```

## Using preprocess

You can do that by override **template\_preprocess\_book\_navigation** which contain a call for **book\_children** function. The aim of override is to provide custom version of book\_children function which add the node date to the title before calling the render method.

```
/**
 * Processes variables for book-navigation.tpl.php.
 *
 * Override theme_preprocess_book_navigation
 */
function my_custom_module_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];
  if ($book_link['mlid']) {
    $variables['tree'] = custom_book_children($book_link);
  }
}

/**
 * Formats the menu links for the child pages of the current page.
 *
 * A custom version of book_children to add date suffix to link title.
 */
function custom_book_children($book_link) {
  $flat = book_get_flat_menu($book_link);

  $children = array();

  if ($book_link['has_children']) {
    // Walk through the array until we find the current page.
    do {
      $link = array_shift($flat);
    }
    while ($link && ($link['mlid'] != $book_link['mlid']));
    // Continue though the array and collect the links whose parent is this page.
    while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
      // Get node object.
      $node = menu_get_object('node', 1, $link['link_path']);
      // Add date to link title.
      $link['title'] = $link['title'] . ' - ' . format_date($node->changed, 'custom', 'M j, Y');
      $data['link'] = $link;
      $data['below'] = '';
      $children[] = $data;
    }
  }

  if ($children) {
    $elements = menu_tree_output($children);
    return drupal_render($elements);
  }
  return '';
}

```

---
Tags: 7, navigation
---


# Question
Title: Rule to send an e-mail with the URL of an uploaded attachment after node change
I have a Drupal 7 site with a custom node type with a custom attachment field. After a (kind of this custom) node has been published, I got an e-mail with the help of **Rules module**. I would like to set up an another rule, which sends me an another e-mail, when somebody edits this node and uploads an attachment. Inside the mail, I want to see the full url to the uploaded file.

After a several test, I'm not able to insert the full path to the uploaded file. The \[node:field-attachment:file\] doesn't work at all. I'm able to insert (manually) the url where this file resides, but after I can not insert the file name (so even the filename would be enough for me).

So with the **\[node:field-attachment:file\]** I got an error: \*Fatal error: Call to a member function value() on a non-object in /home/xxx/sites/all/modules/entity/entity\_token.tokens.inc on line 297.\*

Which is exactly this:

```
/**
 * Gets the token replacement by correctly obeying the options.
 */
function _entity_token_get_token($wrapper, $options) {

   if ($wrapper->value() === NULL) {
// Do not provide a replacement if there is no value.
return NULL;
}

```

With the **\[node:field-attachment\]**, I'm getting the e-mail, but it contains this: *You can download the file from here: Property 0*

Which token should I use to get the url (or the filename) of the actually uploaded file when I edit the node?

# Answer
> 0 votes
You can use these to get file name and file url respectively (Drupal 7.67 Entity API 1.9):

```
[node:field-document:0:file]
[node:field-document:0:file:url]

```

---
Tags: 7, files, rules, tokens
---


# Question
Title: Can I add and edit a custom entity from the same URL?
I am creating a custom entity called user\_profile. Each logged in user will have a user profile. I want to be able to add and edit the user\_profile entity from the same URL.

The example module provided at

Creating a Content Entity Type in Drupal 8

shows adding and editing with the same form but from different URLs.

I want to be able to create the profile when the profile does not exist and edit the profile when the profile does exist from the same URL like /user/3/my-profile

# Answer
You can create a controller in its simplest form.

In my\_module.routing.yml :

```
my_module.profile_controller_profile:
  path: '/user/{user}/my-profile'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProfileController::profile'
    _title: 'Profile'
  requirements:
    _permission: 'edit profile'
    user: \d+

```

In ProfileController.php :

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\my_module\Entity\Profile;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ProfileController.
 */
class ProfileController extends ControllerBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ProfileController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    EntityFormBuilderInterface $entity_form_builder
  ) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFormBuilder = $entity_form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('entity.form_builder')
    );
  }

  /**
   * @param \Drupal\user\Entity\User $user
   *
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function profile(User $user) {
    $profiles = $this->entityTypeManager->getStorage('profile')->loadByProperties(
      ['user_id' => $user->id()]
    );
    if ($profiles) {
      $profile = array_pop($profiles);
      $action = 'edit';
    } else {
      $profile = Profile::create([
        'user_id' => $user->id(),
      ]);
      $action = 'add';
    }
    return $this->entityFormBuilder->getForm($profile, $action);
  }

}

```

You can choose to redirect after submitting the form, etc.
> 2 votes

# Answer
That's simple. In your form's build() function check for an existing entity for that user. If there is one, prefill the fields (set #default\_value). Maybe add the existing entity-id as hidden field (if any).

In your form's submit() check again for an existing entity (for security reasons) or use the hidden entity-id. Then decide in your code if you create an new entity or modify the existing one.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to define frontend theme (non-admin) for a given node tab route?
In my custom module I want to define a new tab associated with nodes. I have my own custom route file with the required definitions and a Links file to make sure the new route will be displayed as a node tab.

Everything works as planned, except that... The content of my custom page is wrapped in admin theme, not the website frontend theme.

I have found other threads where people ask the opposite question: 'how to enforce admin theme'? In those situations, it looks like that by setting '**\_admin\_route: TRUE**' on the route file will do the trick. More on this here:

How to set admin theme for a route?

I thought I would be able to achieve what I want by setting '**\_admin\_route: FALSE**', but it doesn't work. Frontend theme doesn't show, admin theme still kicks in.

This is my modulename.route.yml file:

```
modulename.node.custom_tab:
  path: '/node/{node}/custom-tab'
  defaults:
    _title: 'Custom tab Content'
    _controller: '\Drupal\bti\Controller\MyTabController::pageContent'
  options:
    _node_operation_route: TRUE
    _admin_route: FALSE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'access content'
    _custom_access: '\Drupal\bti\Controller\MyTabController::access'

```

And this is my modulename.links.task.yml file:

```
entity.node.custom_tab:
  route_name: modulename.node.custom_tab
  base_route: entity.node.canonical
  title: 'Custom tab'
  weight: 50
  options:
    attributes:
      class:
        - 'my-custom-class'

```

So, to sum up: how can I make the new custom page in a node tab be displayed with theme defined for the frontend, not the admin theme? Thank you!

**Edit 1**

---

Is it possible that what I am looking for is the attribute '\_theme' inside 'options'? It is marked as TODO here: https://www.drupal.org/docs/8/api/routing-system/structure-of-routes.

# Answer
> 2 votes
The `_node_operation_route` option respect the **Use the administration theme when editing or creating content**, if you want to explicitly disable admin theme for this node-related page don't use `_node_operation_route`

The `_node_operation_route` option overrides `_admin_route` https://api.drupal.org/api/drupal/core%21modules%21node%21src%21EventSubscriber%21NodeAdminRouteSubscriber.php/function/NodeAdminRouteSubscriber%3A%3AalterRoutes/8.8.x

---
Tags: routes, navigation
---


# Question
Title: How to display a table with results when a batch is finished
I could setup a nice batch, everything is working well.

But when the batch is finished, I would like to display a beautiful table with the computed results.

I could do it with the drupal\_set\_message (see below) function, but it is not good enough. \[if mandatory, I accept to be redirected to a new page... but how can I pass the result in this case?\]

```
function my_batch_finished_callback($success, $results, $operations) {
    if ($success) {
        $header=[t("col1"),t("col2")];
        drupal_set_message( theme('table', ['header' => $header, 'rows' => $results]));
    }
    else {
        // An error occurred.
        ...
    }
}

```

# Answer
> 2 votes
You need to store your results somewhere to be able to display them. If they are only required temporarily, the Drupal cache may be an appropriate place to use.

You'll need a key to identify the cache item and make it unique to the batch. As batch callbacks are not passed the internal batch ID, which would be the ideal choice, you'll need to generate one, for which you can use the uniqid() function.

So your batch finished callback will be something like:

```
function mymodule_batch_finished($success, $results, $operations) {
   if ($success) {
     $key = uniqid();
     cache_set('mymodule_batch_results:' . $key, $results, 'cache',time() + 86400); // keep for 1 day
     drupal_goto('mymodule/batch-results/' . $key);
   }
   ...
}

```

In the callback function for the redirected page you can extract the key from the path and read the data from the cache.

```
function mymodule_menu() {
  $items['mymodule/batch-results/%'] = [
     //...
     'page callback' => 'mymodule_display_results',
     'page arguments' => [2],
     //...
  ];
}

function mymodule_display_results($key) {
   $data = cache_get('mymodule_batch_results:' . $key);
   if ($data) {
     //...
   }
}

```

---
Tags: 7, batch-operations
---


# Question
Title: Need multiple url paths for single node without redirecting
I have the requirement on our Drupal 7 site where if we have a single node we need to be able to have multiple url paths to reach that node.

For instance lets say we have a node with id 1234 Currently we can create an alias for it: example.com/my-custom-alias

and I can go to example.com/admin/config/search/path/add and add a second url for this node with id 1234: example.com/differenturl/my-custom-alias

but when I try to go to: example.com/my-custom-alias

the browser redirects the page to: example.com/differenturl/my-custom-alias

What I need is for both urls to resolve to the the same node and for the url to not change (or be redirected).

This is because we use Google Analytics and we need to know from which part of our example.com site our node/1234 is being accessed from.

Currently the only thing that Google Analytics will track is: example.com/differenturl/my-custom-alias

and won't track: example.com/my-custom-alias

Does anyone know how I can achieve this?

# Answer
> 1 votes
Decided to solve the issue by adding URL query parameter to designate where the particular page was coming from as per suggestion of leymannx and Rick Harinton.

Thanks for all your help!

---
Tags: 7, path-aliases
---


# Question
Title: Inside TWIG Template, how to determine if a paraph is empty or not
I have a paragraph called "Square cta" that I'm using like an old field collection. It has 2 fields in it - a text field (field\_cta\_text), and an Image (field\_square\_cta\_image).

I have a content type called "Show Page" in which I will upload an image and put in the cta text for.

I then have a view that shows all of the show pages and I reference the square\_cta in my template - node--view--seasons.html.twig - like so

```
<a href="{{ url }}">{{ content.field_square_cta }}</a>

```

This works great for displaying the image inside the field\_square\_cta for the show and it acting as a link back to the Show Page node it's in.

Where I am having trouble, is not all shows have the field\_square\_cta populated. For those show pages, I want to just display the of the node instead. I have been unable to figure out how to write my if logic to determine if the field\_square\_cta is undefined.

Here is what I was trying to do:

```
{%  if content.field_square_cta %}
  <a href="{{ url }}">{{ content.field_square_cta }}</a>
{%  else %}
  <h1><a class="title" href="{{ url }}">{{ label }}</a></h1>
{% endif %}

```

The conditional is always going with the if, never the else, even when I don't have any data inside the content.field\_square\_cta. I have been unable to determine the proper syntax for checking if that is empty or not.

Any help would be greatly appreciated.

# Answer
> 2 votes
This works if you know a field in the paragraph must be set for it to be considered "non-empty". Look at the entity the first item points to and check it's a required field.

```
{% if node.field_square_cta.0.entity.field_required.value %}
  {# Print the wrapping element, iterate through the paragraphs, do some stuff #}
{% endif %}

```

# Answer
> 1 votes
Better use the node object to check whether the field is not empty.

```
{% if not node.field_square_cta.isempty %}

```

# Answer
> 0 votes
I had to go look at the fields inside the paragraph to determine if they were empty or not, as the paragraph always returned an empty array. This is the code I used.

```
{% if content.field_square_cta.0['#paragraph'].field_square_cta_image.target_id %}

```

# Answer
> 0 votes
It's better to simply check the array length.

```
{% if node.field_square_cta.value|length > 0 %}

```

---
Tags: theming, paragraphs
---


# Question
Title: How to check if entity's property has a value
How can I check if entity's property has a value? I don't think this is the "drupal way" to check it like this

```
$page_optimization->title->value() !== ''

```

Is there any method, something like $page\_optimization-\>title-\>hasValue() etc.

# Answer
> 2 votes
You can use entity metadata wrapper to check if fields are empty.

For example, you can check to see if a textfield is empty with the following. First create the wrapper:

```
// You need the entity type and entity id.
$type = 'node'; $nid = 123;
$wrapper = entity_metadata_wrapper($type, $nid);

```

Then check to see if your text field is empty.

```
$value = $wrapper->field_my_text->value();
if (isset($value)) {
   // Entity has a non-null value for field_my_text, but it might be 0 or empty string.
} if (!empty($value)) {
   // Entity has a value for field_my_text, and it is not 0, empty string, etc.
}

```

For more examples see this excellent blog post - death to field arrays!

# Answer
> 2 votes
If you look at the entity module, specifically the EntityMetadataWrapper class, there is no method of checking whether or not something has a value. If a value returns empty you are essentially checking whether or not the value exists by getting an empty value.

For example a single value uses the EntityValueWrapper and only has one method and that is to return the value. The EntityMetadataWrapper class has few public methods and none that returns whether or not a value is set. If you wanted to extend one of the classes you could probably build your own method.

```
/**
 * Wraps a single value.
 */
class EntityValueWrapper extends EntityMetadataWrapper {

  /**
   * Overrides EntityMetadataWrapper#value().
   * Sanitizes or decode textual data if necessary.
   */
  public function value(array $options = array()) {
    $data = parent::value();
    if ($this->type == 'text' && isset($data)) {
      $info = $this->info + array('sanitized' => FALSE, 'sanitize' => 'check_plain');
      $options += array('sanitize' => FALSE, 'decode' => FALSE);
      if ($options['sanitize'] && !$info['sanitized']) {
        return call_user_func($info['sanitize'], $data);
      }
      elseif ($options['decode'] && $info['sanitized']) {
        return decode_entities(strip_tags($data));
      }
    }
    return $data;
  }
}

```

# Answer
> 1 votes
Another option is to use isset:

```
if (isset($page_optimization->title) && $title = $page_optimization->title->value()) {
  // $page_optimization->title has value
  drupal_set_message($title);
}

```

that avoids a fatal error of referencing a non-existent entity wrapper property.

# Answer
> 1 votes
You can use \__isset() function like

```
$page_optimization->__isset('title');

```

You can get more info here Checking for existence for a field on an an entity\_metadata\_wrapper php overloading

# Answer
> 1 votes
For those who land on this for **Drupal 8**, the way to do this is as follows

$entity-\>get('field\_name')-\>isEmpty()

See - https://stackoverflow.com/questions/34869575/how-do-you-check-if-a-field-is-empty-in-drupal-8

This comes from the

Complex Data Interface extended by FieldItemInterface (Drupal API Doc Links)

---
Tags: entities
---


title: What's the quivalent of node_access()?

text:
# Question
Title: What's the quivalent of node_access()?
I need to test if a given user (in my case, the currently logged-in user) has access to a given node for one of the existing operations.

In Drupal 7, I could use the following code.

```
if (node_access('view', $node, $account)) {
  // User is allowed to see the node.
}

```

What is the equivalent code for Drupal 8?

I will be running this code from inside a \_custom\_access check for a specific route I am setting for my custom module.

Thank you!

# Answer
You want Node::access():

```
if ($node->access('view', \Drupal::currentUser())) {
  // User is allowed to view the node.
}

```
> 3 votes

---
Tags: nodes, authentication-authorization
---


# Question
Title: How to prevent certain users from adding (for example, a Node) to bookmarks with Flag Module
Flag Module \>\>\> https://www.drupal.org/project/flag

How to disable/prevent some Users (NOT Roles) from adding (for example a Node) to bookmarks? Maybe showing a message after clicking on the Boomark button (You are not authorized to make this choice or something like that).

# Answer
I assume you use Drupal 8:

Flag action handled by `\Drupal\flag\Controller\ActionLinkController::flag` so i think you should override this to check on your user and prevent to flag bookmarks nodes:

1. Override *ActionLinkController* controller using *RouteSubscriber* like the following:
Add the following to **YOUR\_MODULE\_NAME.services.yml**

```

services:
  YOUR_MODULE_NAME.route_subscriber:
    class: Drupal\YOUR_MODULE_NAME\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

Create **YOUR\_MODULE\_NAME/src/Routing/RouteSubscriber.php**

```
<?php
namespace Drupal\YOUR_MODULE_NAME\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change the route associated with /flag/flag/{flag}/{entity_id}.
    if ($route = $collection->get('flag.action_link_flag')) {
      $route->setDefault('_controller', '\Drupal\YOUR_MODULE_NAME\Controller\MyCustomActionLinkController::flag');
    }
  }

}

```
2. Create your new Controller **YOUR\_MODULE\_NAME/src/Controller/MyCustomActionLinkController.php** like the following:

```

namespace Drupal\YOUR_MODULE_NAME\Controller;

use Drupal\Component\Utility\Html;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\EntityInterface;
use Drupal\flag\Ajax\ActionLinkFlashCommand;
use Drupal\flag\Controller\ActionLinkController;
use Drupal\flag\FlagInterface;

class MyCustomActionLinkController extends ActionLinkController {

  /**
   * Performs a flagging when called via a route.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param int $entity_id
   *   The flaggable entity ID.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|null
   *   The response object, only if successful.
   *
   * @see \Drupal\flag\Plugin\Reload
   */
  public function flag(FlagInterface $flag, $entity_id) {
    /* @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $this->flagService->getFlaggableById($flag, $entity_id);
    $uid = \Drupal::currentUser()->id();
    // Do your check here i just test with the user admin.
    if ($uid == 1) {
      // Change the message you want to show
      $flag->setFlagMessage("Sorry you don't have right to bookmark this");
      return $this->generateResponse($flag, $entity, $flag->getMessage('flag'));
    }
    else {
      try {
        $this->flagService->flag($flag, $entity);
      } catch (\LogicException $e) {
        // Fail silently so we return to the entity, which will show an updated
        // link for the existing state of the flag.
      }
      return $this->generateResponse($flag, $entity, $flag->getMessage('flag'));
    }
  }

  /**
   * Generates a response after the flag has been updated.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   * @param string $message
   *   (optional) The message to flash.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The response object.
   */
  private function generateResponse(FlagInterface $flag, EntityInterface $entity, $message) {
    // Create a new AJAX response.
    $response = new AjaxResponse();

    // Get the link type plugin.
    $link_type = $flag->getLinkTypePlugin();

    // Generate the link render array.
    $link = $link_type->getAsFlagLink($flag, $entity);

    // Generate a CSS selector to use in a JQuery Replace command.
    $selector = '.js-flag-' . Html::cleanCssIdentifier($flag->id()) . '-' . $entity->id();

    // Create a new JQuery Replace command to update the link display.
    $replace = new ReplaceCommand($selector, $this->renderer->renderPlain($link));
    $response->addCommand($replace);

    // Push a message pulsing command onto the stack.
    $pulse = new ActionLinkFlashCommand($selector, $message);
    $response->addCommand($pulse);

    return $response;
  }
}

```

**Notes:**

1. You may need to do the same the route `flag.action_link_flag_nojs`.
2. I reimplement the method **generateResponse** because it has a private visibility.
> 1 votes

# Answer
Here is a possible implementation:

* Create some role, say *Bookmarks allowed*, which by default you assign to all your users. And make sure to limit access to your Bookmarks (button) to only those users who have been authorized for this *Bookmarks allowed* role.
* Use the Flag module, to implement a flag to flag users, with a label like, say, *Deny bookmarks*.
* Implement some logic, eg using the Rules module (or some custom module if you prefer), so that when a user gets flagged with the *Deny bookmarks* flag, authorization for this *Bookmarks allowed* role is removed.
* Finally, flag all those "some users" with this flag.
> 0 votes

---
Tags: flags
---


# Question
Title: Token Content Access blocks access for author too
I use the Token Content Access module to hide member created nodes from public view and allow them to share private links with private links (URL tokens). My problem is when a user restricts access to individual nodes using URL tokens, he cannot access them without the token either!

# Answer
I briefly looked at the module. I think you will need to make some serious code changes, I could not find an easy tweak.
> 0 votes

---
Tags: 7
---


title: Personal Contact Form Link

text:
# Question
Title: Personal Contact Form Link
I am using Drupal panopoly. For a node type, I am able to display the content of the node and some profile information about the author. I used Contexts for this. However now, I want to display the link to author's personal contact form. The link to the personal contact form shows up on the View profile page. I need to add a direct link to the Contact Form from the node display page. How do I do this?

# Answer
> 2 votes
You can use the Drupal core Contact module to do exactly that.

**EDIT**: In conjuction with Menu Tokens, you will be able to add a menu entry that pulls in the current user id. Add this to your path when creating a menu link:

```
user/[user:uid]/contact

```

You'll need to enable "Use tokens" and select "User from context" in the Methods for Users dropdown. See screenshot:

# Answer
> 1 votes
I found that I was looking at this the wrong way to create a personal user contact form.

I am pretty sure what you described your requirement is a form that users can send each other messages from.

Try this https://www.drupal.org/project/privatemsg

# Answer
> 0 votes
The answers with the menu token doesn't work because you get your ID with user/\[user:uid\]/contact but you need the user:uid of the user you want send a message. Best is use Privatemsg work great

---
Tags: forms, users, emails
---


# Question
Title: How do I make a form field go back invisble after I uncheck a radio button?
I'm currently building a form where the goal is that the administrator will have to choose between 3 radio buttons. If one click on any of the radios, a specific field shows up (There are 3 fields set as "invisible"). My issue is that, I have no problem making these fields show up, but they don't disappear if I select something else.

Here is my code:

```
function walk_handler_form_alter (&$form, FormStateInterface &$form_state, $form_id)
{
  $form['field_prestation_walk']['#states'] = [
  'visible' => [
    ':input[name="field_prestation_type"][value="walk"]' => [
        'checked' => true
      ]
    ]
  ];
}

```

So, as I said earlier, this code makes my forms show when I click on their related radios. However, if I click on another radio, they don't disappear.

I had a lot of troubles to find some documentation about that (well, I found some, but the examples given wheren't thorough enough for me). Also, I tried to add an `invisible` after the `visible` one, with the exact condition except that 'checked' was set to false, but it didn't work.

Should I use plain Javascript / jQuery for this, or am I just it the wrong way?

Thanks in advance

# Answer
> 3 votes
Hello try this ...

```
$form['field_prestation_walk']['#states'] = [
  'visible' => [
    ':input[name="field_prestation_type"]' => [
        'value' => 'walk'
      ],
    ]
  ];

```

---
Tags: 8, forms, hooks
---


# Question
Title: Get argument from current URL in twig to generate a link with that argument
I'm trying to get an argument from search page URL so that I can pass that argument to a link. For example I have this URL for a search results page: `http://domain.com/site-search?search_api_fulltext=foo` And on that page I want to have a link that goes to: `http://domain.com/other-search?search_api_fulltext=foo`

I've tried `{{ url('<current>') }}` but that only returns the domain and path, but not the arguments. I've been trying stuff like `{{ app.request.requestUri }}` but that returns nothing.

FWIW, I'm trying to include these links in a custom block that appears on the search results page.

# Answer
> -1 votes
well if you are making a custom block then you are probably doing something like this ....

```
 $build = [];
 $build['#theme'] = 'your_template',
 return $build;

```

and then in you hook\_theme().

```
 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
    ],
  ];
 }

```

you don't need to pre prossess the block at all just make sure the block is not being cached aka add this to your block plugin.

see How to prevent a block from being cached?

```
public function getCacheMaxAge() {
  return 0;
}

```

then in your block function :

```
 $search_query = \Drupal::request()->get('search_api_fulltext');
 $build = [];
 $build['#theme'] = 'your_template',
 $build['#search_query'] =  $search_query,
 return $build;
....

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
     'variables' => [
       'search_query' => NULL,
     ],
    ],
  ];
 }

```

then in your twig template

```
{% if search_query %}
  do what you want here {{search_query}}
{% endif%}

```

---
Tags: 8, theming, uri
---


title: Drush cache-rebuild breaking menus

text:
# Question
Title: Drush cache-rebuild breaking menus
We have had an issue with an expanding menu on a drupal 8 website that stops working when the command

```
drush cache-rebuild

```

is used.

MORE INFO ON ERROR:

When triggered, the error causes menus set to expand some sub-menu portion when active to stop expanding. That is to say the menu stops expanding at all, just stays in the inactive state.

The menus where this occurred were generated with the core menu module.

Logging into the site and using the clear all found in admin-\>config-\>performance-\>"clear all caches" fixes the issue.

Can anyone suggest an alternative drush/command line command we can use or how we can fix this problem?

```
drush clear-cache

```

does not seem to fix the issue.

I also tried executing as apache:

```
sudo -u www-data drush cache-rebuild

```

this also broke my menus.

What exactly is the difference between the UI cache clear and the drush one?

MORE INFO

Ok after some digging - and please correct me if I am wrong here - it seems that when Drush rebuilds all caches it invokes:

```
drupal_rebuild(ClassLoader $class_loader, Request $request)

```

which is found in `utility.inc`, see drush github repo, while the admin command in Drupal calls:

```
drupal_flush_all_caches()

```

found in `common.inc`, see drupal docs.

I have always been under the impression drush either called the same cache function as the internal performance button or at least they had the same behaviour, but they seem not to - at least in regards to my issue with the menu.

Can anyone suggest a way to have drush - or some other tool - invoke `drupal_flush_all_caches()`?

A further question, is the behaviour I am observing intended or should drush cache-rebuild work the same as `drupal_flush_all_caches()`?

MORE INFO AGAIN

Further experiments lead me to believe that it is specifically the clearing of the views cache that is causing some expanding menus to break.

```
drush cache-clear views

```

Will also trigger the behaviour. Again, clearing with the `drupal_flush_all_caches()` via the performance admin page fixes the issue.

# Answer
> 2 votes
EDIT: I take it back. The problem has started again in drush 8.1.8 when `Drush cr` is used in a script - we have it in a back up script to reduce the size of the DB before pilling a copy of it - the application of the `is-Active` tag is getting broken on menu elements and any styling - say turning on or off visibility to expand the menu - seems to to totally break.

Manually clearing the cache through the UI fixes the issue but is not ideal

Drush 8.1.8 seems to have fixed the problem. I have looked through the change log though and cannot see what got changed in regards to the cache-rebuild that would fix the problem but it seems to have gone away so...

# Answer
> 1 votes
The following snippet works for me on Drupal 8.7

```
drush ev '\Drupal::service("router.builder")->rebuild();'

```

---
Tags: 8, drush, navigation
---


# Question
Title: Custom Content Entity Bundles - How to override class methods?
I created a custom content entity type and a bundle of this entity type. The custom content entity is presented as PHP class; the entity bundle is defined in a configuration file.

I created the Entity class on my own, programmatically; the entity bundle was created via the Drupal UI.

Now I am wondering why Drupal is creating a configuration file instead of a subclass. Do you know if it is possible to override class methods from the base entity for the specific entity bundle?

# Answer
> Do you know if it is possible to override class methods from the base entity for the specific entity bundle?

Yes, this is possible. In code you can only override globally, but a class instance is always bundle specific. This is the only required field when creating a content entity with bundles. So the bundle is always set and you can use it in a condition in the overridden method and defer to the parent method for other bundles.

For example if you had a getTitle() method you could modify the title for a specific bundle:

```
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    if ($this->bundle() == 'foo') {
      return 'bar';
    }

    return parent::getTitle();
  }

```
> 1 votes

---
Tags: 8, entities
---