# Question
Title: How to use negative number as argument value in a drush command?
I'm trying to create a drush command that need negative and positive numbers as argument, all works fine with the positive numbers, but once I tried to use the negative number I get this error:

```
[error]  Unknown option: --1.  See `drush help mw-reorder` for available options. To suppress this error, add the option --strict=0.

```

Is like there is no way to use a negative value because drush think that this is an option.

I looked inside the drush code but I didn't found anything.

Maybe the solution is use a special option in the command to says that the argument will be consider as a negative value or I'm missing something here?

# Answer
> 1 votes
At the end I added a new option named --minus for the drush command.

```
function modules_weight_drush_command() {
  $items['mw-reorder'] = [
    'description' => dt('Configures the module weight.'),
    'arguments' => [
      'module' => dt('The module machine name'),
      'weight' => dt('The module weight'),
    ],
    'options' => [
      'force' => [
        'description' => dt('If the option is present the core modules weight will be canged even if the option to allow it is disabled.'),
      ],
      'minus' => [
        'description' => dt('If the option is present the weight will be consider as a negative value. Read https://drupal.stackexchange.com/q/246298/28275 for more information.'),
      ],
    ],
    'aliases' => ['mw-r'],
    'examples' => [
      'mw-reorder node_revision_delete' => dt('Show the node_revision_delete module weight.'),
      'mw-reorder onlyone -5 --minus' => dt('Set the onlyone module weight to -5.'),
      'mw-reorder no_autocomplete 15' => dt("Set the no_autocomplete module weight to 15."),
      'mw-reorder views 10 --force' => dt("Force to set the views module weight to 15, even if the core module reorder option is disabled."),
    ],
  ];

 return $items;
}

```

And this is how will works:

```
function drush_modules_weight_mw_reorder() {
  // Getting the minus option.
  $minus = drush_get_option('minus');
  // Applying the minus option.
  $weight = $minus ? -1 * $args[1] : $args[1];
  // Setting the new weight.
  module_set_weight($args[0], $weight);
  // Printing the message.
  $message = dt('The module weight for @module_name was updated to @weight.', ['@module_name' => $args[0], '@weight' => $weight]);
  drush_log($message, 'success');
}

```

If you want to see all the code take a look inside the issue Allow to use negative values with the drush mw-reorder command

# Answer
> 2 votes
It looks like it is not possible since the '-' is always picked up as an option being passed to the drush command. I'd suggest evaluating why you need a negative value and if it could be handled with an absolute value and/or some other creative way of indicating a negative value.

If this is not an option, I found this work around in several different articles/blogs:

`php -r "print json_encode("-1");" | drush vset --format=json some_var_name - --y`

The drush command docs also suggest a technique using arrays for passing a complex data structure to the command: https://drushcommands.com/drush-7x/core/variable-set/ (See the last example). This would let you pass in almost anything you wanted.

# Answer
> 1 votes
Set up your module to accept a named parameter such as 'weight=5' or 'weight=-5' rather than a stand-alone numeric parameter.

It may work as a stand alone parameter entered as -'-5' or, if drush respects the common convention of '--' indicating end of flags, -- -5.

# Answer
> 0 votes
I have another less than ideal solution, I'm doing it as a drush sqlc command (I'm changing the variable table here):

`drush sqlq "update variable set value='s:3:\"-10\";' where name='uc_pane_delivery_weight'";`

---
Tags: drush
---


title: How do I implement Download Count?

text:
# Question
Title: How do I implement Download Count?
I am trying to sort my view of documents by "most downloaded". I see that there are only a few modules, Download\_Count being one. There is no documentation on how to implement this.

I have installed it and can't see any way to actually use it. Or is there a newer module at this point?

I have spent days of research and can't come up with anything. Any pointers?

# Answer
> 0 votes
For **download count** you will have to enable one of the provided blocks after installing

> four blocks: top downloaded files, top downloaded users, top downloaders, and top nodes of file downloads.

**File download count** might also be a good candidate. The links to the downloads have to created manually (using a module) or with the use of views if they are to be counted. A link has to look like this `file/[file:fid]/download`

In the simplest case you can create a view that lists all the files to be counted and using `file:fid` field and then rewrite that field to create a link that looks like this`<a href="file/[file:fid]/download">download</a>`

or if above don't work for you you might want to give ajax download count ac chance

---
Tags: 7, views, files
---


title: How do I import a feed in a node?

text:
# Question
Title: How do I import a feed in a node?
I was looking for a solution to import RSS Feeds as nodes. We need to make modifications and add more fields to the content. This would have been easy in Drupal 7 with Feeds Importer, but it doesn't appear that there is a viable alternative for Drupal 8.

What would be the best way to import a feed directly to a node?

# Answer
> 2 votes
The solution is described in:

https://ohthehugemanatee.org/blog/2017/06/07/stop-waiting-for-feeds-module-how-to-import-remote-feeds-in-drupal-8/

1) Download and enable migrate\_plus and migrate\_tools modules. You should be doing this with composer, but I won’t judge. Just get them into your codebase and enable them. Migrate Plus provides plugins for core Migrate, so you can parse remote XML, JSON, CSV, or even arbitrary spreadsheet data. Migrate Tools gives us drush commands for running migrations.

2) Write your Migration configuration in text, and paste it into the configuration import admin page (admin/config/development/configuration/single/import), or import it another way. I’ve included a starter YAML just below, you should be able to copypasta, change a few values, and be done in time for tea.

3) Add a line to your system cron to run drush migrate -y my\_rss\_importer at whatever interval you like.

Below is a YAML file which you should adjust:

```
id: my_rss_importer
label: 'Import my RSS feed'
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  urls: 'https://example.com/feed.rss'
  data_parser_plugin: simple_xml

  item_selector: /rss/channel/item
  fields:
    -
      name: guid
      label: GUID
      selector: guid
    -
      name: title
      label: Title
      selector: title
    -
      name: pub_date
      label: 'Publication date'
      selector: pubDate
    -
      name: link
      label: 'Origin link'
      selector: link
    -
      name: summary
      label: Summary
      selector: 'itunes:summary'
    -
      name: image
      label: Image
      selector: 'itunes:image[''href'']'

  ids:
    guid:
      type: string

destination:
  plugin: 'entity:node'

process:
  title: title
  field_remote_url: link
  body: summary
  created:
    plugin: format_date
    from_format: 'D, d M Y H:i:s O'
    to_format: 'U'
    source: pub_date
  status:
    plugin: default_value
    default_value: 1
  type:
    plugin: default_value
    default_value: podcast_episode

```

---
Tags: nodes, 8, feeds, importing-exporting
---


# Question
Title: Programmatically get exposed filters from view
A little bit of context:

I am running a headless Drupal 8 with React in the front-end. All the data gets exposed through various endpoints.

Now i am trying to render a view in react, there was no problem in obtaining the data. But when i tried to get the exposed filters i ran into a problem (the filters are based on taxonomy terms). I expected to get the filter values like this:

```
value: {5:"Value one", 6:"Value two", 49:"Value three", 50: "Value four"}

```

Except i got the filter values like this:

```
value: {5:5, 6:6, 49:49, 50:50}

```

So it feels like instead of get the key and value i only get the keys... I am wondering if i am doing something wrong or there is another way of obtaining the exposed filter values.

The following code i am using to obtain the filters

```
$this->$view // ViewExecutable
$filters = [];
foreach ($this->view->filter as $filter) {
  if($filter->isExposed()) {
    $filters[] = $filter->options;
  }
}

```

# Answer
I think everything is fine. You have to load the taxonomy term names manually like:

`\Drupal\taxonomy\Entity\TaxonomyTerm::load($ids)`

Or maybe you can do a custom query to load only the taxonomy term titles without any field data (because that is what you need).
> 1 votes

---
Tags: 8, views
---


title: Form submit is not firing on large form

text:
# Question
Title: Form submit is not firing on large form
I have an old D6 site. I created a form with hook\_form with very many fields (197 rows * 6 columns = 1182 fields). It works good and form submit works properly.

But when I add a new, 7th column to the form and the fields number becomes 1379 the form submit is not firing.

I do not see any errors or warnings, php memoty limit is set to 256M and post max size too. But submit handler simple does not fire.

What can be a cause?

# Answer
Increase max\_input\_vars in your PHP environment as Clive suggested in the comment.

Another indication of this problem is the form validate handler won't trigger either. Unless you have E\_WARNING set in the php.ini error\_reporting setting the form will silently fail and run the form hook again.
> 1 votes

---
Tags: forms, 6
---


# Question
Title: Append query parameter to module's javascript based on custom field on page
I am new to Drupal development.

I am currently working on maintaining a Drupal module that was developed by a past colleague.

What I want to do is have an available field where a user can enter in an integer which corresponds to a JS query parameter that will be added to one of the module's script upon page load.

I am wondering if it is possible to add a custom field type that users can add through the Drupal UI to their content (nodes), and then check for the existence of this field and append it to the script?

I have found this tutorial helpful in adding custom fields through my module. However, it doesn't provide any links to documentation that specifies what values I can/should put on dependencies, module, along with other parameters. Also after quite a bit of Google searching, and a bit of combing through Drupal docs, I ended up with nothing.

Further, I believe that I am more or less on the right track in using the `hook_page_attachments_alter` function to check against fields and conditionally load JS scripts. Although, I don't believe that the `$page` array passed through this hook supplies node fields.

Currently the module is loading the custom JS like so:

```
  function my_module_page_attachments_alter(&$page) {

    $page['#attached']['library'][] = 'my_module/script';

  }

```

Obviously it is loading it through libraries, which would make appending a custom query string parameter difficult. Maybe there is a better way?

# Answer
> 3 votes
You probably want to approach this through `hook_ENTITY_TYPE_view()`. It's easy enough to get the current node in the page attachments hook, but as you only need to take action when a node is being viewed, using the more specific hook seems appropriate.

A basic example:

```
function my_module_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full' && $entity->getType() == 'foo' && $entity->hasField('field_bar')) {
    if ( ($val = $entity->field_bar->value) ) {
      $build['#attached']['library'][] = 'my_module/script';
      $build['#attached']['drupalSettings']['my_module']['script']['bar'] = $val;
    }
  }
}

```

The settings you add to the `#attached` array will be available in JS after a change to your libraries yml file to add a dependency:

```
script:
  js:
    ...
  dependencies:
    ...
    - core/drupalSettings

```

The value will be available in the JS var `drupalSettings.my_module.script.bar`.

---
Tags: 8, nodes
---


# Question
Title: How would I apply a transition to a State Machine field?
I am trying to transition a `state_machine` field on the `User` entity during an event. What I have thus far is:

```
/* @var \Drupal\user\Entity\User $user */
$user = User::load($id);

/* @var \Drupal\Core\Field\FieldItemListInterface $state_field */
$state_field = $user->get('field_screening_status');

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $state_field->get(0);

$transitions = $state->getTransitions();

$state->applyTransition($transitions['mark_needs_screening']);

```

Of course, this does not actually save it to the user. I would actually need to call:

```
$user->set('field_screening_status', 'needs_screening');
$user->save();

```

But, how might I instead use the `state_machine` API to apply the transition to a user field?

# Answer
Here's what I ended up with. Would be curious if the community has a better solution.

```
/* @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser());

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $user->get('field_screening_status')->get(0);

$transitions = $state->getTransitions();

if (array_key_exists('mark_needs_screening', $transitions)) {
  $user->set('field_screening_status', 'needs_screening');
  $user->save();
}

```

UPDATE: Thanks to @lisastreeter in #commerce on drupal.slack.com

```
$user = User::load($id);
$state = $user->get('field_screening_status')->first();
$transition = $state->getWorkflow()->getTransition('mark_needs_screening');

if ($transition) {
  $state->applyTransition($transition);
}

```

Not sure if that `get(0)` change to `first()` really made the difference, but it works now.
> 1 votes

---
Tags: 8
---


# Question
Title: How to render an image at its original size?
There are plenty of examples on the internet on how to render a styled image; for instance this one from web omelette:

```
$render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => 'public://my-image.png',
    // optional parameters
];

```

However I do not want to use an image style. I want to render the original untouched image. So I tried:

```
$render = [
    '#theme' => 'image_style',
    '#style_name' => NULL,
    '#uri' => 'public://my-image.png',
    // optional parameters
];

```

Which did not work. How do I render the original full-size image?

# Answer
You can also use the `#theme` property `image` (which does not appear to be documented anywhere), but gives a valid image tag.

```
$render= [
  '#theme' => 'image',
  '#uri' => $file->getFileUri(),
];

```

Which becomes `<img src="/sites/default/files/image.png" alt="" />` once rendered.
> 4 votes

---
Tags: 8, theming, media
---


# Question
Title: How can I ensure a referenced entity is cached separately per paragraph?
I have a situation where two *Paragraphs* on single page may potentially reference the same entity.

The affected paragraphs have a field to change their colour, and this colour value is passed down to the referenced entity (via hook\_preprocess\_\[entity-type\]) for use in its template.

* Node

+ field\_paragraph

    - Paragraph1

        * field\_colour
            * field\_entity\_reference (*references entity:1234*)
        - Paragraph2

        * field\_colour
            * field\_entity\_reference (*references entity:1234*)

When I update *Paragraph 1* to change its colour, this is currently affecting the colour of *Paragraph 2* (because the entity is cached, including the colour value that is preprocessed into it).

I have tried adding a cacheable dependency (in hook\_preprocess\_\[entity-type\]) to transfer the cache tags for the paragraph to the entity, so that when the paragraph is updated, it invalidates the cache for the entity it is referencing:

```
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($variables, $referring_entity);

```

I have also tried replacing `$variables` in the above with `$variables['elements']` and `$variables['content']`, but either way this does not seem to work as I expected.

Any advice appreciated.

# Answer
> 6 votes
So the easiest option likely is to just disable caching completely for the embedded entities.

In hook\_entity\_view(), unset `$build['cache']['keys']`. They are then still cached as part of the paragraph render cache, but don't have their own cache entry anymore.

To avoid not caching them when they are shown somewhere else, you should use a special view mode when you integrate them in paragraphs and only disable caching for that.

Note that you could also set max-age = 0 but that means "this content must not be cached at all", that information would bubble up to the paragraph and host entity and none of those would be cached anymore. That's not what you want.

Or you could change your approach and apply that color through a class that is set on the paragraph level, without changing the HTML of the embedded entity. Doesn't work for everything, but for a simple color change, that is likely easier to implement.

# Answer
> 1 votes
The accepted answer worked for me, but I'd like to update with another method that also worked in my case and kept the rendered entities cached:

```
function hook_preprocess_paragraph(&$variables) {
  foreach (Element::children($variables['content']['field_your_field']) as $index) {
    $child = &$variables['content']['field_your_field'][$index];

    if (your view switching logic) {
      $child['#view_mode'] = 'your_new_view_mode';

      // Update cache keys
      array_pop($child['#cache']['keys']);
      $child['#cache']['keys'][] = $child['#view_mode'];
    }
  }
}

```

---
Tags: 8, entities, caching
---


# Question
Title: Loose compression for all images directly from Drupal
I need to do image loose-compressing usually done with GIMP/TinyPNG/GPI, but just **inside Drupal**, but also For all images, in a single process or several sporadic processes (say, for each content type).

This could save much time instead of download, compress, reupload, etc.

Is there a way to loose-compress all images in the application so that webpages containing them load faster?

If you don't know such a tool but does know a way to show all nodes that has images, please comment naming such a tool, so it could at least help in the alternative of downloading and manually loosely-compressing each image before re uploading it.

# Answer
You're looking for this but in D8 - https://www.drupal.org/project/imageapi\_optimize. You can still use the tools to do it manually.

PNG - Use https://pngquant.org/ first with these settings `--speed=1 --quality=90-99 --force --ext .png` and then https://github.com/subzey/zopfli-png
JPG - https://github.com/mozilla/mozjpeg and then https://stackoverflow.com/questions/5579183/jpegtran-optimize-without-changing-filename

EDIT: This new D8 project just appeared https://www.drupal.org/project/file\_processor
> 4 votes

# Answer
Drupal core has a setting out of the box that allows you to compress all images on upload. See admin/config/media/image-toolkit.

My image compression plan is to use that setting of 75% for basic compression.

On top of this I'll install the Image effects module and use the "Strip" effect to remove metadata and the and "Interlace" option to make my jpeg's progressive and significantly increase perceived speed.

The Image effects module uses the GD2 image kit that core already uses, so by using it I'm not required to worry about installing any other server tools or rely on a 3rd party API.
> 0 votes

---
Tags: 8, media, performance
---


# Question
Title: View - I need both Parent ID and Child ID at the same time
I’m in need of some help with defining a view.

The gist of it is that I need to know the parent term ID as well as the child term id so that I can separate how the custom template displays the results.

let’s say I have the following as one of many entries in my vocabulary named Category.

Debt Management
---Estate Planning

---Event

---Family Life

If a person selects Debt Management the display is one of two ways.

1) If there are items associated with the term Debt Management, then the template displays data links to each item. After that, the children are displayed, but in a different format, yet similar to the above.

2) If there are no items related to Debt Management, then only its children within their format is displayed.

To do the logic I am building in the template, I need to have the value of the parent TID and the child TID for each record returned to the view.

The path in the view is /taxonomy/term/%, which, after preprocessing for this example comes to /category/debt-management

So far I have the view spitting everything I need properly, except being able to get both parent and child TID. Right now I only get the current displayed item’s TID, which does not allow me to know if it is the parent or not.

I also need to do this with views alone. Not a custom module.

Thanks in advance for your help.

# Answer
> 0 votes
To do rudimentary conditionals with views, you can use two views, and in the first view you select "render a view" on "no results."

Let me break it down a little further for you:

1. Make your "selection" a contextual filter, for default you can select "display a summary" (or something similar to that
2. If the contextual filter has results, display the results.
3. If the contextual filter doesn't have results, choose a "no results" action called "render a view"
4. Create a secondary view that selects all children based on the same contextual filter.

---
Tags: views
---


title: Setting messages from classes in Drupal

text:
# Question
Title: Setting messages from classes in Drupal
How do we set messages now in 8.x? Do we still use drupal\_set\_message? Not a fan of mixing procedural calls within classes if it can be avoided.

# Answer
> 5 votes
Prior to 8.5.x, `drupal_set_message` is the way.

For \>=8.5.0-alpha1, there's a new messenger service, with a note (and example which I won't bother copying):

> The procedural functions drupal\_set\_message() and drupal\_get\_messages() have been deprecated and replaced with a dedicated Messenger service.
>
> You should now inject this service as a dependency for your own services and controllers:

# Answer
> 0 votes
Interesting post by Clive, I didn't know about 8.5 having a new messaging service. That's great.

In the meantime, I add the call in a protected method of the class:

```
protected function sendMessage($message, $type = 'success') {
  drupal_set_message($message, $type);
}

```

While it is still calling a static function from a class, the advantage is that when doing unit tests, this method can be overridden, so that tests are not broken.

---
Tags: 8
---


title: How to anonymise user names and emails?

text:
# Question
Title: How to anonymise user names and emails?
The developer stages need their user names and email address anonymised. I did not find anything googling the subject matter. Maybe somebody developed a Drush extension for this? Any other suggestions are welcome too.

# Answer
> 1 votes
You can use `drush sql-sync` command to sync the database and obscure email addresses and the user passwords during db deployment.

> `--sanitize` Obscure email addresses and reset passwords in the user table post-sync.

Check `drush help sql-sync` for help.

# Answer
> 2 votes
I came up with this:

```
drush sql-query "
  UPDATE users
  SET
    name=CONCAT('User-',uid),
    mail=CONCAT(uid,'@anon.com'),
    init=CONCAT(uid,'old@anon.com')
  WHERE uid > 0;"
drush upwd User-1 --password=SecureAdminPassword

```

# Answer
> 2 votes
You need, `drush sql-sanitize`

```
$ drush sql-sanitize -h
Run sanitization operations on the current database. You can add more sanitization to this command by implementing hook_drush_sql_sync_sanitize().

Examples:
 drush sql-sanitize                        Sanitize database without modifying any passwords.
 --sanitize-password=no
 drush sql-sanitize                        Sanitizes database but exempts two user fields from modification.
 --whitelist-fields=field_biography,field
 _phone_number

Options:
 --db-prefix                               Enable replacement of braces in sanitize queries.
 --db-url                                  A Drupal 6 style database URL. E.g., mysql://root:pass@127.0.0.1/db
 --sanitize-email                          The pattern for test email addresses in the sanitization operation, or "no" to keep email addresses unchanged. May contain replacement patterns %uid, %mail or %name. Example value: user+%uid@localhost
 --sanitize-password                       The password to assign to all accounts in the sanitization operation, or "no" to keep passwords unchanged. Example value: password
 --whitelist-fields                        A comma delimited list of fields exempt from sanitization.

Aliases: sqlsan

```

---
Tags: 7, users, drush, staging
---


# Question
Title: Download true file name instead of from drupal version changed filename
i have some file upload fields which works great. the file is stored on public file system and will be able to get downloaded from the users (in a specific node).

the issue is when i update the file (pdf) with a new version in the same month, drupal renames the file and save a new instance instead of updating the file (i know the reasons, avoiding global file conflicts on the page).

the user will download the renamed file which is wrong (e.g. manual\_1.pdf). how can i change the filename into the name that is in its metadata (manual.pdf).

is there any hook, module or settings?

# Answer
> 2 votes
Is all depends on how your loading the file information. As the filename field in the file\_managed table will always be whatever is uploaded. e.g. filename = mypdf.pdf uri = mypdf\_1.pdf

So you can always use the filename value for the real file name. It sounds like whatever you're using to load the file/create the file link isn't using this correct value

# Answer
> 1 votes
> the file is stored on public file system

The problem with using the public file system is that the file is actually served by your web server, not Drupal.

So if you want to manipulate it in any way, you'll have to switch to private. This does add more overhead. Test your configuration with big file sizes to see if they're handled okay.

Your other option is changing the path where the files are stored. You can use a token that includes the date (maybe time? depends how frequently they might be updated) of when the file was uploaded. Most files will end up in different folders and that will solve your issue since files are only renamed if there's a collision in the folder it's writing to.

For a live site with files, there are 3 options I can think of.

Option 1: if there’s a pattern to the files, you could modify the `.htaccess` so those are rewritten to the `index.php`.

Option 2: You can change the public file path to something else. You can then change the private file path to the previous public one. This would mean all current files would now be served as private. You would need to adjust the fields you want so they now write to private.

Option 3: Modify the path of the files you want on the database so they are served from the private path. Then move those files from the public file path to the private file path.

---
Tags: 8, hooks, files
---


title: How do I access the paragraph value?

text:
# Question
Title: How do I access the paragraph value?
In 1 node. I'm using multiple paragraph type & within that I have fields.

```
Paragraph 1 -> field_title, field_time
Paragraph 2 -> field_test

```

How to access Node's Paragraph 2 -\> field\_test value?

# Answer
> 4 votes
Need to add below code in your theme file

**themename.theme**

```
/**
 * Implements hook_preprocess_node().
 */
function theme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  switch ($node->getType()) {
    case 'article':
      $my_paragraph = null;
      foreach ($node->get('field_content') as $paragraph) {
        if ($paragraph->entity->getType() == 'my_paragraph') { // Change to your paragraph type
          $my_paragraph = $paragraph->entity;
        }
      }

      if (!empty($my_paragraph)) {
        $variable['test'] = $my_paragraph->field_test->value;
      }

      break;
  }
}

```

---
Tags: 8
---


# Question
Title: Alter the path of the more link from Views
In Drupal 8 how do I alter the *more* link?

I need to give it a path which is based on a taxonomy id that is based on the current path (where the view is on) which has the taxonomy name in the path.

The current page also has a field which has this taxonomy name as a result. (but changes per page)

--

I'm trying to retrieve the taxonomy ID based on the taxonomy that is placed on the node and give the id to the more link

I am not sure if this is clear. But I have a views page with filters. And the taxonomies are the filters. Certain pages (theme pages) have their own taxonomy directed to it with a views block. The more link of that block links to the views page, I want the link to automatically check the filters of the taxonomy that is being used on these theme pages.

# Answer
> 0 votes
If I have understood your question, I have been needing the same thing. I solved it by means of:

1) add the field 'link to taxonomy term' and exclude it from visualization

2) format the description field as 'clipped version' (I am using right now a Spanish version of Drupal 8, not sure what the English option name is called)

3) rewrite the output for the description field as '{{ description\__format }} {{ view\_taxonomy\_term }}'

That did the trick.

I hope that that's what you had asked, and that someone can take advantage of it.

*EDIT*: After re-reading your question, I realize that what I was trying to solve is different: a taxonomy terms view, which returns a list of terms, the description shortened to 160 chars, with a 'read more' link based in the taxonomy term's custom path (/path instead of /taxonomy/term/2).

Since I haven't been able to find an online answer to that, and given that google drove me to this question while trying to find an answer to mine, I think I could still leave this answer here. However, if the OP or some mod tell me to remove this answer, I gladly will.

---
Tags: views, 8
---


title: Get paragraph id in field template

text:
# Question
Title: Get paragraph id in field template
I have a paragraph template where I print a field, for instance :

```
{{ content.field_products }}

```

In this template, I can get the paragraph id with :

```
paragraph.id()

```

I need to pass this paragraph id in the field template. What is the cleaner and simple way to do this ? I found a solution like this :

```
{{ content.field_products|merge({666:paragraph.id()}) }}

```

and then I get the value in field template like this :

```
{% set paragraphId = items[items|length-1].content %}

```

But this is dirty and generate a warning "Message d'erreurUser error: "4" is an invalid render array key in Drupal\Core\Render\Element::children() (line 99 of core/lib/Drupal/Core/Render/Element.php)." that I can understand giving that it's a dirty hack and drupal try to render my "666" array.

I'm probably gonna get the array with "666" key I added in a preprocess\_field(), create a new variable for the field template et delete this diabolic hack from $variables to remove the warning due to a tentative to render this fake array, but I guess there is a better way to do ? I want simply to pass a variable from a template to its child...

thanks !

# Answer
The clean solution is template preprocessing: In `yourtheme.theme` create something like

```
function yourtheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  $parentEntity = $element['#object'];
  //might be useful for if-clause: $variables['field_name'] and $variables['field_type']
  if ($parentEntity && $parentEntity->getEntityTypeId() == 'paragraph' ) {
    //whatever logic you need goes here, e.g. something like
    //$variables['attributes']['data-from-parent-paragraph'] = $parentEntity->getYourStuff();
  }
}

```
> 4 votes

---
Tags: 8, paragraphs
---


# Question
Title: White screen error when migrating between servers
I wish to migrate my site from one shared hosting server to another. Both servers are with the same company (Heart Internet). I moved the files to the new server, set up a new database on the server, replaced the old settings.php with the contents of default.settings.php to get a default draupal installation up and running.

Trying to migrate the database using either the backup and migrate module or importing the database via phpMyAdmin I get a white screen error on the site i am migrating to.

I have looked up some possible causes and based on what I have read I have:

* Disabled Devel modules
* Disabled Clean URLS

I found this helpful page on troubleshooting white screen on death in drupal which recommends adding code to the index.php to get information on the problem.

Following the instructions given there gave me the following error description:

Fatal error: Call to undefined function \_date\_api\_element\_info() in /home/sites/MY\_DOMAINNAME.co.uk/public\_html/sites/all/modules/date/date\_api/date\_api.module on line 2298

Based on this I assumed that the date module was causing the problem I disabled the date module on the original site and rolled the new site back to the basic Drupal install and imported the most recent databased backup. However I am still getting the same error message.

Both servers are set to execute scripts as PHP 5.3

I can appreciate that this is not an easily issue to reproduce. I would like suggestions as to sensible next steps to try to stop this error from occurring and complete the site migration successfully.

# Answer
> 1 votes
Issue solved.

I had not disabled all of the date sub-modules (Thanks Molot for making me double check this). I ensured they were all disabled, cleared caches and was then able to export the database and import it on the new server.

I did get some errors on the new install. Running update allowed me to see that workflow needed updating. Updating workflow and ensuring the right sub-modules were installed (You can't run Workflow Node and Workflow Field at the same time) fixed the other errors.

I was then able to re-enable the date module.

# Answer
> 0 votes
I had the same issue and a simple `drush cr` did the trick.

---
Tags: 7, wsod
---


# Question
Title: Drupal 8 what is the ajax event for auto complete dropdown?
Drupal 8, what is the ajax event for auto complete dropdown? i have created form alter, there i am altering my form field that is auto complete field, so now what is the ajax event for this auto complete drop down.

change, select, keyup all are not working for this.

# Answer
> 3 votes
use autocompleteclose event.

```
#ajax' = array(
  'callback' =>'get_user_details',
  'event' => 'autocompleteclose',
);

```

---
Tags: ajax
---


title: Switch a language programatically

text:
# Question
Title: Switch a language programatically
Looking for a way to change between languages on our site, the Drupal 8s LanguageManager doesn't seem to have a straightforward method for this. We cannot use URL-switching, just want to do this through code.

So we want to go from "en" to "fr" for instance. Is there a method like "setCurrentLanguage" available somewhere?

# Answer
> 6 votes
You can change the current language to `$lang_code` with the following code.

```
$lang_code = 'fr';
\Drupal::configFactory()->getEditable('system.site')->set('default_langcode', $lang_code)->save();

```

# Answer
> 12 votes
In a custom module, you should use a custom LanguageNegotiator and assign it to your LanguageManager, using LanguageManager-\>setNegotiator();

1) First, you must define a CustomLanguageNegotiator, which overwrites initializeType() method. That method should return a Language object, which you can externally define using a custom setLanguageCode() method:

```
<?php

namespace Drupal\custom_module\Language;

/**
 * Class responsible for performing language negotiation.
 */
class CustomLanguageNegotiator extends \Drupal\language\LanguageNegotiator {

    var $languageCode = NULL;

    /**
     * {@inheritdoc}
     */
    public function initializeType($type) {
        $language = NULL;
        $method_id = static::METHOD_ID;
        $availableLanguages = $this->languageManager->getLanguages();

        if ($this->languageCode && isset($availableLanguages[$this->languageCode])) {
            $language = $availableLanguages[$this->languageCode];
        }
        else {
            // If no other language was found use the default one.
            $language = $this->languageManager->getDefaultLanguage();
        }

        return array($method_id => $language);
    }

    /**
     * @param string $languageCode
     */
    public function setLanguageCode($languageCode)
    {
        $this->languageCode = $languageCode;
    }

}

```

2) Define your CustomLanguageNegotiator as a service, in your custom module service file, "custom\_module.services.yml":

```
custom_module.language_negotiator:
  class: Drupal\custom_module\Language\CustomLanguageNegotiator
  arguments: ['@language_manager', '@plugin.manager.language_negotiation_method', '@config.factory', '@settings', '@request_stack']
  calls:
    - [initLanguageManager]

```

3) Rebuild your cache and use your CustomLanguageNegotiator like this:

```
$languageManager = \Drupal::languageManager();
$customLanguageNegotiator = \Drupal::service('custom.language_negotiator');
$languageManager->setNegotiator($customLanguageNegotiator);

// Set new language by its langcode
$languageManager->reset(); // Needed to re-run language negotiation
$languageManager->getNegotiator()->setLanguageCode('fr'); // 'en', 'es', 'fr', etc

// Run any code, and its output will be displayed in french
// ...

$languageManager->reset();
$languageManager->getNegotiator()->setLanguageCode('en');

// Run any code, and its output will be displayed in english
// ...

// Do not forget to set language to its initial value
$languageManager->reset();
$languageManager->getNegotiator()->setLanguageCode('XX');

```

# Answer
> 8 votes
Best way is to create a new Language Negotiation plugin, create a new file in a custom module in the folder `src/Plugin/LanguageNegotiation`, to keep with naming convention I called my class LanguageNegotiationXXX, the contents of this file should be:

```
<?php

namespace Drupal\my_module\Plugin\LanguageNegotiation;

use Drupal\language\LanguageNegotiationMethodBase;
use Symfony\Component\HttpFoundation\Request;

/**
 * Custom class for identifying language.
 *
 * @LanguageNegotiation(
 *   id = Drupal\my_module\Plugin\LanguageNegotiation\LanguageNegotiationXXX::METHOD_ID,
 *   weight = -99,
 *   name = @Translation("XXX Language Switching"),
 *   description = @Translation("Language based on XXX."),
 * )
 */
class LanguageNegotiationXXX extends LanguageNegotiationMethodBase {

  /**
   * The language negotiation method id.
   */
  const METHOD_ID = 'language-XXX';

  /**
   * {@inheritdoc}
   */
  public function getLangcode(Request $request = NULL) {
    $langcode = NULL;

    // Custom logic goes here, but should set a langcode such as fr

    return $langcode;
  }

}

```

Enable module or clear caches for this to take effect, go to `admin/config/regional/language/detection` and enable your new detection method.

This worked perfectly for me with all users, all the other methods I tried didn't work with anonymous users.

# Answer
> 1 votes
A little bit or research lead me to the settings under configuration "Languages" then "Detection and selection". Removed the option "URL" and selected "Session". I wanted this solution to be as flexible as possible so I made an action in a controller which did this (along with the applications language switching logic):

```
    $config = \Drupal::config('language.negotiation')->get('session');
    $param = $config['parameter'];
    //Just set it BRUTALLY!
    $_SESSION[$param] = $language;

```

This works like a charm, feels sort of nude to just set the session to notify Drupal but it's allright. My flow was basically, call the controller action with an XMLrequest, once done reload the website and language changed.

---
Tags: 8
---


# Question
Title: How and where to create a prefix key for memcache?
I am up to here in drupal documentation :

> Start at least one instance of memcached on your server. Edit settings.php to make memcache the default cache class, for example: $conf\['cache\_backends'\]\[\] = 'sites/all/modules/contrib/memcache/memcache.inc'; $conf\['cache\_default\_class'\] = 'MemCacheDrupal'; $conf\['memcache\_key\_prefix'\] = 'something\_unique';

Why do I need a memcache key prefix if have only one database? Anyway where and how do I set it?

# Answer
All those settings are added to *settings.php*

usually *sites/default/settings.php*

```
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'k1';
// Use database for cache_form
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

You only need a memcache key prefix if you're using memcache with more than one site on that server. Adding a short key, e.g `$conf['memcache_key_prefix'] = 'k1';` is good practice.
> 6 votes

# Answer
Solution for Drupal 8: (also in settings.php)

`$settings['memcache']['key_prefix'] = 'something_unique';`
> 1 votes

---
Tags: caching
---


# Question
Title: Get array of all entities from entity reference field
On one of my content types I have a taxonomy term reference field that allows for multiple values. Normally if I wanted the term from a field I'd simply do

$node-\>field\_taxonomy\_term-\>entity;

However this doesn't work if there are multiple entities. Normally I would expect getValue() to do the trick but that just gives an array of the ids with target\_id as the key. I sort of have a round about way of getting them with this method

```
    $entity_storage = \Drupal::entityTypeManager()->getStorage('taxonomy');
    $ids = [];
    foreach ($this->field_taxonomy_term->getValue() as $item) {
        $ids[] = $item['target_id'];
    }
    $entities = $entity_storage->loadMultiple($ids);

```

But when getting one is as simple as $node-\>field\_name-\>entity I had a feeling that I'm doing more work than necessary. Is there a simpler way to obtain an array of entities from a field or is what I'm doing the most efficient way to do it?

# Answer
I can't say for sure on that specific field but usually there's the referencedEntities() method you can call

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AreferencedEntities/8.4.x

So something like this perhaps:

$entities = $node-\>field\_taxonomy\_term-\>referencedEntities();
> 6 votes

---
Tags: 8, nodes, entities
---


# Question
Title: How to grep Rules to search for a deprecated function?
I'm removing an obsolete custom module, but I want to make sure it isn't referenced in any rules.

Is there a way for me to search / grep for a function name within all the rules on my site?

# Answer
Consider a rule, actually a rules component, as in this (random) sample (in Rules export format):

```
{ "rules_grant_access_to_a_node" : {
    "LABEL" : "Grant access to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_containing_classified_ad" : { "label" : "Node containing classified ad", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-containing-classified-ad" ],
          "type" : { "value" : { "article" : "article" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "node",
            "id" : [ "node-containing-classified-ad:field-free-format-nr" ]
          },
          "PROVIDE" : { "entity_fetched" : { "fetched_classified_complete" : "Fetched classified complete" } }
        }
      },
      { "drupal_message" : { "message" : "Trying to grant access to node with Id = [fetched-classified-complete:field_free_format_nr]" } },
      { "content_access_action_user_grant" : [] },
      { "redirect" : { "url" : [ "fetched-classified-complete:url" ] } }
    ]
  }
}

```

The above rule (Rules Component) has a Rules Action `content_access_action_user_grant` (= machine name) which is available if (a) you have the Content Access module enabled and (b) the ACL module is enabled also. So ACL is a weak module dependency of the Content Access module.

However, that `content_access_action_user_grant` Rules Action is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that refers to that Rules Action `content_access_action_user_grant` will show a "*... fails the integrity check*").

With the above example (and Rules Action) in mind, execute an SQL query on the Drupal database which looks like so:

```
SELECT id,plugin,name,label
FROM `rules_config`
WHERE `data` LIKE '%content_access_action_user_grant%'

```

The results I get by using this query looks like so:

```
id  plugin   name                             label

216 rule     rules_grant_access_to_a_node     Grant access to a node

```

Obviously, this result with `id=216` matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin.

Replace the machine name of the Rules Action in my example by whatever fits with your "function name" (as in your question), and a similar SQL query should list all "*rules in your site*" (as in your question) that reference your custom module.

**Note**: another approach (if you can afford to do so), is to simply disable your custom module, and then use the Rules UI to find out which Rules / Rules Components show a similar message containing such "*... fails the integrity check*".
> 2 votes

# Answer
The standards documentation recommends that modules use the `@deprecated` tag when deprecating a function/method.

Assuming the author of any given module has followed the guidelines properly, searching for `@deprecated` should get you the correct results.
> -1 votes

---
Tags: 7, rules
---


title: Data selectors for custom fields

text:
# Question
Title: Data selectors for custom fields
I have two node types: Item and Order. I have an entity reference (`field_items`) set up on the Order content type which references Item (1 Order to N Items).

The Item has a field (`field_reservation_status`) which is a drop-down list of strings.

I am trying to set up a rule so that when I allocate an Item to an Order on the Order form, the reservation status on the related Item will be set to "Reserved".

I am doing this with a reacting rule and a rule component as follows.

**Rule component**

Condition: Node is of type "Item"

Action: Set a data value (this should set field\_reservation\_status on the node that the component is actioning to "Reserved")

**Reacting rule**

Event: When a content node is saved

Condition: Node is of type "Order"

Action: Add a variable (this should store field\_items for the current Order node)

Then

Action: Call the rule component

**Questions**

1. In the rules config UI I can't see any "Add Loop" button - is this to be expected in version D8 Alpha 3?
2. What data selector should I use for accessing field\_items on the Order node that has just been saved?
3. What data selector should I use in the rules component to access field\_reservation\_status on the current object from field\_items?
4. How do I set up a loop over the variable that is created in the reacting rule?

No doubt I'll have more questions.

# Answer
> 1. In the rules config UI I can't see any "Add Loop" button - is this to be expected in version D8 Alpha 3?

***yes*** ... as per the issue about Implement Loop UI.

> 2. What data selector should I use for accessing field\_items on the Order node that has just been saved?

I doubt this is possible in the D8-alfa3 release of Rules. Though you may want to retry using the D8-dev release ...

> 3. What data selector should I use in the rules component to access field\_reservation\_status on the current object from field\_items?

Refer to my answer to "2." above ...

> 4. How do I set up a loop over the variable that is created in the reacting rule?

Refer to my answer to "1." above ...

PS: No doubt you'll run into more-of-the-same issues using any of the currently available releases of Rules for D8. However, using the D8-dev release is currently your best bet/alternative.
> 1 votes

---
Tags: 8, rules
---


title: dpm in submit handler not working?

text:
# Question
Title: dpm in submit handler not working?
I have a very interesting problem. I have 2 dev machines (both mac, running XAMPP).

In my project I have a submit handler for a custom entity form.

When I try to dpm() (or kpr, or dsm, ...) the contents of $form or $form\_state, well, nothing really happens (on one machine!)

On the other machine, the dpm (for the exact same project, in the exact same submit handler, for the exact same variable) works perfectly.

I have copied php.ini settings files, checked the php memory limit, ...

Nothing seems different...

When I try to dpm($form\['entities'\]); then it works on both instances. This seems to give me the impression that it works when you narrow down the array...

But when I inspect the array ($form) it only contains approx. 40 items or so... (okay there are arrays in arrays and so on).

No errors on in the php log, apache log, ...

Any suggestions would be very welcome!

Many thanks in advance!

# Answer
> 0 votes
I had a similar problem. In a submit handler, tried to run dsm($form\_state). This caused all submit handlers to not run. If I run $form\_state\['complete form'\] = NULL; before the dsm(), it works. I presume it was too big with the complete form in there.

---
Tags: debugging
---


# Question
Title: Using the same form more than once per page with AJAX callbacks
I have a small email signup form made from extending FormBase that takes an email address and submits it to a mail service. I need to change the submit to AJAX so I can flash a success or error message.

I want to show this form more than once on a page. Once in a CTA near the top of the page, and there is a slightly different styled version in the footer.

When I added `#ajax` to the submit button, only one instance of the form seems to be affected. Here is the whole form:

```
$info = $form_state->getBuildInfo();

$form['#prefix'] = '<section class="hl__single-input-form">';
$form['#suffix'] = '</section>';
$form['#attributes']['class'][] = 'hl__single-input-form__form';

$form['title'] = [
  '#type' => 'label',
  '#for' => 'edit-email-address',
  '#title' => 'Stay in the know',
  '#attributes' => [
    'class' => [
      'hl__label',
      'hl__label--inline',
    ],
  ],
];

if (!empty($info['args'][0]) && $info['args'][0] == "show_tagline") {
  $form['tagline'] = [
    '#markup' => '<div class="hl__single-input-form__helper-text">Sign up for email updates from MySite</div>',
  ];
}

$form['email_address'] = [
  '#type' => 'email',
  '#size' => NULL,
  '#required' => TRUE,
  '#attributes' => [
    'placeholder' => $this->t('Email'),
    'class' => [
      'hl__input',
      'hl__input--inline',
      'js-is-required',
    ],
    'data-twig-suggestion' => 'newsletter_signup_email',
  ],
  '#prefix' => '<div class="hl__single-input-form__input-group">',
];

$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Sign up'),
  '#attributes' => [
    'class' => [
      'hl__button',
      'hl__button--small',
      'hl__button--inline',
    ],
    'data-twig-suggestion' => 'newsletter_signup_submit',
  ],
  '#suffix' => '</div>',
  '#ajax' => [
    'wrapper' => 'hl__single-input-form',
  ]
];

```

The block in the footer that pulls the form just has this build method:

```
  /**
   * {@inheritdoc}
   */
  public function build() {
    return ['form' => $this->formBuilder->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup')];
  }

```

The preprocess for the Paragraph that outputs the form when being themed:

```
$variables['signup_form'] = \Drupal::service('form_builder')->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup', "show_tagline");

```

How can I support having this form on the page more than once, both with the same AJAX action on submit? Also, how can I avoid overwriting the wrong wrapper with an AjaxCommand?

edit: validateForm method:

```
/**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $email_value = $form_state->getValue('email_address');
if (empty($email_value) || !\Drupal::service('email.validator')->isValid($email_value)) {
  $form_state->setError($form['email_address'], $this->t('Please enter a valid email address.'));
}

if (mailchimp_is_subscribed('XXXXXXX', $email_value, TRUE)) {
  $form_state->setError($form['email_address'], $this->t('You are already subscribed to our newsletter.'));
}
  }

```

# Answer
Define a class property for a sub id and append it to the form id:

```
class MyForm extends FormBase {

  public $sub_id = '0';

  public function getFormId() {
    return 'my_form_' . $this->sub_id;
  }

  ...
}

```

You can append this sub id to the wrapper as well, if you want to have different wrappers for each form:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $wrapper = 'ajax-wrapper-' . $this->sub_id;
    // use $wrapper for #ajax and div container in buildForm()
    ...
  }

```

Then set a different sub id for each instance of the form.

For example in a block the first instance:

```
$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\mymodule\Form\MyForm');
$form->sub_id = '1';
$build['form'] = \Drupal::formBuilder()->getForm($form);

```

and the second in preprocess:

```
$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\mymodule\Form\MyForm');
$form->sub_id = '2';
$variables['form'] = \Drupal::formBuilder()->getForm($form);

```
> 1 votes

---
Tags: 8, forms
---


title: getStorage() method returns fatal error

text:
# Question
Title: getStorage() method returns fatal error
I think I am finally coming to the realization that the documentation for D8 is not complete enough to work with or, possibly, that OOP is simply too complex to work with unless you go through all the code of each class you want to use and trace back through everything it uses/implements.

Case in point:

I want to use this public function: public function EntityDefinitionUpdateManager::getChangeSummary

I go here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityDefinitionUpdateManager.php/function/EntityDefinitionUpdateManager%3A%3AgetChangeSummary/8.2.x

I can see its namespace is Drupal\Core\Entity

So I write this code:

```
use Drupal\Core\Entity;
ksm(\Drupal::EntityDefinitionUpdateManager()->getChangeSummary());

```

and woo hoo.. it works. Simple enough!!

Next: public function EntityListBuilder::getStorage

From here: it looks very similar to the previous example: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityListBuilder.php/function/EntityListBuilder%3A%3AgetStorage/8.2.x

Same namespace.

Yet, this code:

```
use Drupal\Core\Entity;
ksm(\Drupal::EntityListBuilder()->getStorage());

```

returns: Fatal error: Call to undefined method Drupal::EntityListBuilder()

any idea why these cannot be implemented in the same fashion? Are there clues on the API doc pages that these will not work the same?

# Answer
> 0 votes
A list builder only makes sense in the context of a particular entity type, you can't get one context-free. As such there's no service and no method in `\Drupal`, hence the error.

List builders come from the entity type manager service:

```
$builder = \Drupal::service('entity_type.manager')->getListBuilder('entity_type');

```

But that's a bit of a roundabout way to get to the storage object when you could just get it from the manager itself:

```
$storage = \Drupal::service('entity_type.manager')->getStorage('entity_type');

```

Incidentally, the `use Drupal\Core\Entity;` line is not applicable to either of your code snippets, you can remove it from both and the results wouldn't change. It almost feels like you're expecting that any class will be available via `\Drupal`, while in reality that class only exists as a static wrapper for the service container. To most people, shortcuts to often-used services.

It sounds like you might benefit from delving a bit more into how the following work:

and maybe for dessert:

# Answer
> 0 votes
Apparently, there are two misunderstandings in the following code shown in the question.

```
use Drupal\Core\Entity;
ksm(\Drupal::EntityDefinitionUpdateManager()->getChangeSummary());

```
1. The `use` statement doesn't require a namespace, but a full qualified class name which includes a namespace (The syntax for the `use` statement has been extended in PHP 7, but still it doesn't allow to write `use Drupal\Core\Entity;` to use all the classes in that namespace.)
2. `\Drupal::EntityDefinitionUpdateManager()` is not saying to Drupal *instantiate the `EntityDefinitionUpdateManager` class you find in the namespace I declared with the previous `use` statement*

`\Drupal` is a simple class that defines static methods. One of those static methods happens to be `\Drupal::entityDefinitionUpdateManager()`, but the `\Drupal` class doesn't have a static method for each of the classes Drupal defines. There isn't any `\Drupal::entityListBuilder()` method, so PHP returns you an error. (Yes, PHP is not case-sensitive, so `\Drupal::entityDefinitionUpdateManager()` and `\Drupal::EntityDefinitionUpdateManager()` call the same method.)

---
Tags: entities
---


# Question
Title: PHP Warning: Unknown: Input variables exceeded 1000 and how to fix
I have been working on a patch for https://www.drupal.org/project/hubspot for the 8.x version. In fact I found a ticket for this same error for the 7.x version (https://www.drupal.org/project/hubspot/issues/2579147

This occurs when the site has more than a few webforms. This module maps webform fields to fields on hubspot.

The problem is when I submit the form, it includes every field in the form which exceeds 1000 input variables, even when the value is `--donotmap--` as you can see below:

That is just a small section of values being sent. I think its sitting around 2000 vars being sent.

Trying to figure out a work around for this, but is it even possible to exclude any fields with the value of `--donotmap--` from submitting? I'm pretty sure that is not possible, but that is all I can think of right now. Any ideas besides increasing the `max_input_vars` setting?

**Note**: "What is the maximum number of elements allowed in a form?" is related, but not a Duplicate. My question is how to exlude inputs from submitting, but I believe setting them to disabled will not submit them.

# Answer
> 0 votes
As for a workaround, you can increase the value of `max_input_vars` variable in your PHP settings.

---
Tags: 8, webforms
---


# Question
Title: How to properly set up Drupal Console on Windows 7
I have been trying to set up Drupal Console for quite some time now on Windows 7; however, there always seems to be some kind of error which I am unable to solve.

I have installed Drupal Console via the **drupal.phar** way which I placed in a directory that is included in the PATH variable and it gets called properly. However, every time I call the console from the command line it gives me the following notice:

```
Notice: Undefined index: commands in phar://C:/_Skripty/drupal/vendor/drupal/console-core/src/Utils/ConfigurationManager.php on line 273

```

The second weird thing is that I want to use it in multiple project and it does actually seem to be working, in a way, in one of the projects but not in the other. For example, I am able to get the list of available commands in one, but running that same command in the other produces the following fatal error in addition to the above mentioned notice.

```
Fatal error: Trait 'Drupal\Console\Command\Shared\ModuleTrait' not found in C:\xampp\htdocs\sam_stroje\modules\metatag\src\Command\GenerateGroupCommand.php on line 32

```

I suspect that this might be caused by some modules not correctly implementing the stuff that has to do something with the console but I'm not 100% sure.

What might be the cause of these problems? Thanks in advance for all replies.

# Answer
This will surely help you debug: https://evolvingweb.ca/drupal-console-windows-devdesktop-troubleshooting

And here is **a guide** explaining how to do it from scratch: https://evolvingweb.ca/blog/installing-drupal-console-windows
> 5 votes

# Answer
I would add this as a comment, but I am missing points.

I have the same first issue that you mention on my installation on Mac OSX El Capitan, so this is not Windows related.

I found that this issue has already been reported and shall be fixed in the next release candidate (RC 10).

A temporary fix is to run `drupal init`.

Reference to the issue queue

As for your second issue, this has also been reported and not fixed yet, maybe you can provide them with some information about your case, as the issue is in "Maintainer needs more information" status. See here.
> 1 votes

# Answer
3 steps to install composer on windows machines

* Run `composer require drupal/console` in your Drupal installation directory
* Add this `;vendor\bin\drupal;` to path in your environment variable
* Run drupal console commands to verify and enjoy.

**To add a path in env-variable**

> Right click on computer properties
>
> > click advanced settings
> >
> > > click Environment Variables
> > >
> > > > edit PATH from system variables list
> > > >
> > > > > Add this `;vendor\bin\drupal;` and save

Restart command prompt
> 0 votes

---
Tags: 8, console
---


# Question
Title: paragraph template suggestion based on parent content type
I have two content type using same paragraph as field , though template code will be according to content type. How can i can have different template names for paragraph template depending on content type.

Current naming convention: `paragraph--paragraph-type.html.twig`

Desired naming convention: `paragraph--parent-content-type--paragraph-type.html.twig`

Another solution will be get the url and pass it as variable in template and use template code according to url passed.

# Answer
> 9 votes
Add a theme name suggestion:

*mytheme.theme:*

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_paragraph_alter(&$suggestions, $variables) {
  $paragraph = $variables['elements']['#paragraph'];
  $parent = $paragraph->getParentEntity();
  if ($parent) {
    $suggestions[] = 'paragraph__' . $parent->bundle() . '__' .  $paragraph->bundle();
  }
}

```

# Answer
> 1 votes
Use different view modes for different node types. On Strcuture \> Paragraphs types, add as many different view modes for your paragraph, as needed by your node types. On Structure \> Content types, change the display mode for the node's paragraphs field to "Rendered entity" and use the cog wheel to select the previously created, corresponding view mode. Now create template files like paragraph--paragraph-type--viewmode-name.html.twig

---
Tags: 8, theming, paragraphs
---


# Question
Title: How do I disable the password recovery link?
How can I disable, in the standard login form, the link for password recovery? I need it for my custom theme.

# Answer
You can use `hook_menu_local_tasks_alter()`.

E.g.

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function MY_MODULE_menu_local_tasks_alter(&$data, $route_name) {
  if($route_name == 'user.login') {
    $data['tabs'][0]['user.pass']['#access'] = FALSE;
  }
}

```

**Note:** Make sure to replace MY\_MODULE with the actual name of your module.
> 3 votes

# Answer
For non-programmers, try No Request New Password module
> 3 votes

---
Tags: 8
---


# Question
Title: Migrating a site with a module that doesn't have a version for latest core version
I'm working on migrating a site from Drupal 7 to Drupal 8. All content and other things are migrated successfully excepts a module (the *Field collection* module) that is available for Drupal 7, but not for Drupal 8.

Please give guidelines if have any experience with it.

# Answer
You simply cannot. If the module has a Drupal 8 version you can use it just after enabling the module. But if it doesn't contain a Drupal 8 version you cannot enable or use with your Drupal 8 site installation. Only thing you can do is find an alternative module for the unsupported module that you have used. Or you can change the unsupported modules codes with supported Drupal 8 syntaxes. But I never encourage to do so. Because

1. It effect authors copyrights.
2. You wouldn't be able to update anymore or if you update your module forcefully all the changes you have done will revert back to the original state.

So think twice before doing a change like that. Hope this helps for your question.
> 0 votes

---
Tags: drush, migrations
---


# Question
Title: How to Display Taxonomy image field on node page
I need to display Taxonomy term image field on the node display page instead of the term name.

Other fields are being printed like below and the $content variable is not printed any where. Any suggestions?

```
$policies = $node->field_policies['und'][0]['safe_value'];

```

# Answer
In your hook\_preprocess\_node load your taxonomy term and get the field image value

```
function hook_preprocess_node(&$variables) {
   $term = $variables['elements']['#node']->get('your_field_taxonomy_term')->getValue();
   if (!empty($term)) {
    $terme = Term::load($term[0]['target_id']);
    $image = $terme->get('your_field_image')->getValue();
    $variables['image'] = $image;
  }
 }

```

in yout twig file print the image variable.

hope this will help.
> 0 votes

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


title: How to load Ajax Site Wide?

text:
# Question
Title: How to load Ajax Site Wide?
I am trying to open a webform in a modal window through following link, which works fine when I am logged in, but when I logout it simply stops working

```
<a class="use-ajax" data-dialog-options="{"width":600}" data-dialog-type="modal" href="/form/call-back">Get a Call Back</a>

```

It seems like we need to load ajax on pages where we want to use this link, so I want to know how can I load ajax sitewide.

# Answer
Implement `hook_page_attachments_alter()` like so:

```
function MODULE_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'drupal.ajax';
}

```

The same hook can be implemented in a theme if that makes more sense.
> 1 votes

---
Tags: 8, theming, ajax
---


# Question
Title: Programmatically set Panelizer View Template on Node
I have panelizer installed so that I can panelize the full content views on a node by node basis on my content types. For example I have a news content type but I have a default panelizer view mode and I have a 'press release' version meant for the news nodes that are considered press releases.

I'm attempting to perform a query on them so I can programmatically set the view modes in bulk instead of having to go through each node and do it manually, but I'm having trouble. The machine names of the views are 'news' and 'press\_release' and I'm attempting to change them like so

```
$node->panelizer->view_mode = 'press_release';
$node->save();

```

But it doesn't seem to have any effect. How would I programmatically change the panelizer view mode on a node?

UPDATE: I used $node-\>panelizer-\>getValue(); and this is what I received.

```
string(4) "news"
array(2) {
  [0]=>
  array(3) {
    ["view_mode"]=>
    string(4) "news"
    ["default"]=>
    string(4) "news"
    ["panels_display"]=>
    array(0) {
    }
  }
  [1]=>
  array(3) {
    ["view_mode"]=>
    string(4) "full"
    ["default"]=>
    string(13) "press_release"
    ["panels_display"]=>
    array(0) {
    }
  }
}

```

It seemed like instead of getting the view\_mode that is set I got every view mode which made me think Iwas on the wrong path.

# Answer
It turned out the output of $node-\>panelizer-\>getValue(); was giving me a clue that I missed.

I had forgotten that there were different panelizer templates for different view modes.

I was able to accomplish what I needed with

```
    $panelizer_arr = $node->panelizer->getValue();
    for ($i = 0; $i < count($panelizer_arr); $i++) {
        if ($panelizer_arr[$i]['view_mode'] == 'full') {
            $panelizer_arr[$i]['default'] = 'test_display';
        }
    }
    $node->panelizer = $panelizer_arr;
    $node->save();

```
> 0 votes

---
Tags: 8, nodes, panels
---


# Question
Title: Link by internal path in *.links.menu.yml not visible in admin menu
Based on the official documentation to create menu links I've tried to use an internal link on the administration menu. But the internal link is only visible for users with administrator rights.

In my `my_module.links.menu.yml` I use the following links for testing:

```
my_module.test_link:
  title: 'TEST LINK internal'
  url: internal:/node/add
  description: 'TEST internal'
  parent: system.admin_content
  weight: 99

my_module.test_link_2:
  title: 'TEST LINK external'
  url: https://www.stackoverflow.com
  description: 'TEST external'
  parent: system.admin_content
  weight: 100

```

Both links are visible for administrators, but an user with editor role does only see the external link.

I activate every permission for the editor role, the link remains invisible.

# Answer
> 2 votes
It seems to be necessary to use a **route\_name** for this. Then you can control permissions and the internal link is visible for the editor role too:

1 – Change **`my_module.links.menu.yml`** to use a **route\_name** instead of the url:

```
my_module.test_link:
  title: 'TEST LINK internal'
  route_name: my_module.test_route
  description: 'TEST internal'
  parent: system.admin_content
  weight: 99

```

2 – Add the route with permission to my routing file **`my_module.routing.yml`**:

```
my_module.test_route:
  path: '/node/add'
  requirements:
    _permission: 'access content'

```

---
Tags: 8, users, navigation
---


# Question
Title: How to process different URL page via Drush?
I'm testing the following Drush 8 command (using `--uri` parameter):

```
drush --uri=https://www.example.com/custom/path ev 'var_dump(current_path());'

```

however when printing `current_path()`, it always returns the same, default page. To clarify, specified page exists.

According to this page, I think it should work this way.

How I can make Drush to parse an URL of my choice?

# Answer
As the article says, the uri parameter just populates the request information. Drush only uses this to find the site settings information. At this point, just like in a web request, the context is the index.php page.

On a web server, the code inside the index.php takes the URI and causes the requested page to be rendered.

Drush does not do this step. So, when you do your ev of the current\_path(), you get the default page.

The article points out that you need to call the menu\_execute\_active\_handler() in D7 to render the page. This take the URI and converts it to the requested page.

If you want information about the page, you will need to embed your print statements in the code for that page.

NOTE: an alternative to trying to do this via Drush is to look at using the devel module (I recommend adding the kint addon as well). This allows you to place debug statements in the code that will print out on the web page, e.g. kint($node). Very useful in determining the structure of data so you can grab the right bit.
> 1 votes

---
Tags: 7, drush
---


# Question
Title: Hook not firing for custom entity -- how to set theme suggestions?
I have an entity whose machine name is orb\_act. This code is not firing in Drupal 8:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_orb_act_alter(array &$suggestions, array $variables) {

  // Add template suggestions based on the current view mode.

  $suggestions[] = 'orb_act';
  $suggestions[] = 'orb_act__' . $variables['elements']['#view_mode'];

}

```

How do I set my template suggestions?

# Answer
> 2 votes
The theme system doesn't know about entity types by default. You need to implement hook\_theme() yourself at the moment. You likely also need a preprocess function to define a few standard things.

The console project generates this when creating a new entity type through it, you could try that to see how it looks. Otherwise look at what node module does in node\_theme() and template\_preprocess\_node().

---
Tags: 8, theming
---


title: Ignore cache in preprocess function

text:
# Question
Title: Ignore cache in preprocess function
I have a content type 'homepage' containing one node which is used a the homepage. This node has a multivalue image field, and I need to randomly select one of those images to show on the homepage on every site visit. I have written the logic for this in the `THEME_preprocess_node` function in my `THEME.theme` file. This is working fine, but the site in question is still in development mode with most caching deactivated. I'm worried that once the site goes live and the caching is activated, it will serve the homepage from cache and therefore always show the same image until the cached version of the page expires.

Is that the case, or are the preprocess functions evaluated on every page visit even when the cache is active? If not, how can I circumvent this to get a random image every time?

This is the code I have written for this:

```
  $imgages = $node->get('field_frontpage_header_image');
  $random = $imgs->get(rand(0, $imgages->count() - 1))->getValue();
  $img = File::load($random['target_id']);
  $variables['random_header_image'] = ImageStyle::load('frontpage_header')->buildUrl($img->getFileUri());

```

I then use `{{ random_header_image }}` in the twig template. Maybe I can change this variable to a render array with a cache setting of `max-age => 0`? Not sure if this works in preprocess functions though ...

Thanks!

# Answer
If it's a limited set of pictures that you have then I would just write a custom formatter that displays for example an image tag with a data attribute that has your list of image paths (maybe with the first image already set as non-JS fallback maybe). then you just need small bit of JS that picks one of those randomly and sets it as the actual src attribute. Your page is fully cacheable then and while it might still be a noticeable delay until the image shows up, that can even happen with static image links on slower connections.

And it will certainly be *much* faster than an ajax request.

The placeholder approach might also work and Drupal supports that kind of out of the box with dynamic page cache, doesn't need a reverse proxy or so for that. but you would have to disable the internal page cache then on that page. See http://www.qed42.com/blog/lazy-builders-drupal8 for an example on that.

The way that works with Dynamic Page cache is that the whole page with the placeholders is cached, and then calls the defined lazy builders which returns the actual content for the current request. You would want to use a similar approach as with JS, prepare all image urls for example already as arguments and then just pick one from that array and render it.
> 2 votes

---
Tags: 8, caching
---


# Question
Title: How to add redirect section to node edit on Drupal 8?
On Drupal7 using Redirect module there was a section on node/nodeid/edit view where we could add a "Redirect" section. This was helpful because it allowed redirects to be created from the node/nodeid/edit view.

In Drupal8 that option is not available. How do you replicate the redirect section on the node/nodeid/edit view?

# Answer
> 1 votes
That's not a Drupal 7 feature but one from the redirect module. It partially exists in Drupal 8 as well but only lists the existing redirects, there is an issue open to add the ability to create a new redirect

---
Tags: 8, redirection
---


# Question
Title: programmatically change link URL in view
I have a view that shows all of a particular user's content (content the user has created on the site). This works fine, but I need to link the results (title field) to the pages where the content is displayed - not to the original node of the created content.

Since the content types may be different, I guess I need to set the URL's programmatically.

For example one content type is "projects" projects are displayed at site.com/projects/!arg

Another content type is "photos" photos are displayed at site.com/photos/!arg.

How do I write a conditional that will set the URL's correctly?

# Answer
I don't recommend to use views php module,

# Menu item with callback:

The idea here is to override all the links of the titles in your view with one link which pass an argument to custom menu callback, then in the callback, you write your PHP code which does the routing.

to implement this solution you need to do the following:

1- Override the link in the view

2- Create callback using hook\_menu():

```

/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['my-routing/%node'] = array(
    'title' => 'Custom callback',
    'page callback' => 'my_custom_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

3- Create your custom callback to do the routing:

```

function my_custom_callback($node) {
  switch ($node->type) {
    case 'product' :
      drupal_goto('project/' . $node->nid);
      break;
    case 'post' :
      drupal_goto('blog/' . $node->nid);
      break;
  }
}

```
> 1 votes

# Answer
You will need to add several fields to the view and then "exclude from display" so you can use them as tokens: Node type, node id, and node user id.

Then you can change the title field of the node to "output as link" and use the above tokens (views will tell you what they are but assuming they are \[node\_type\] \[nid\] and \[uid\]) you would construct the link like: `[node_type]/[nid]/[uid]`

That works unless you need extra logic to determine the path (if tokens don't match up directly to url arguments). In that case you need the Views Php module, which will allow you to inject php code into the field.
> 0 votes

# Answer
Here is how I got this to work. The code may not be the most elegant due to inexperience, but it does work.

I added node type, node id and author user id fields to the view and set them to exclude from view. Then using a global php field (provided by the "views php" module) I used the following code:

```
if ($row->type == "single_house_room_photo") {
  print  '<a href="/rooms-houses/' . $row->title . '/' . $row->nid . '/' . $row->uid . '">  ' . $row->title . ' </a>';
} elseif ($row->type == "add_a_product") {
 print  '<a href="/products/' . $row->title . '/' . $row->nid . '">  ' . $row->title . ' </a>';
} else {
 print '<a href="/rooms-houses/' . $row->title . '/' . $row->nid . '/' . $row->uid . '">  ' . $row->title . ' </a>';
}

```
> -1 votes

---
Tags: views
---


# Question
Title: How to safely delete relation entity endpoint revisions (field_revision_endpoints)
I would like to safely clean duplicate field revision data. This field\_revision\_(field\_name) data not associated with nodes, but the relation entities.

I'm using the relation module. I'm bumping up against the problem outlined here: https://www.drupal.org/node/1530164

I have a lot of relations on my site linking different entities. My field\_revision\_endpoints table is growing quite large. The issue mentions as a work around, he uses a sql script to clear out the old revisions. I did some googling on info for deleting revisions, but I'll I have come up with is results relating to deleting node revisions.

Is it safe to simply delete rows out of field\_revision\_endpoints?

# Answer
> 0 votes
The answer is no. I eventually had to circle back to this question and come up with a solution myself. The `relation_revision` table contains the relation + revision ids that match up to the `field_revision_endpoints` rows. Simply deleting rows from `relation_revision` would orphan the revision field data in `field_revision_endpoint`.

After poking around the relations issue queue, I found this patch which adds support for the Entity API's revision deletion mechanism.

Instead of patching the relations module, I used `hook_entity_info_alter` to register my own `'revision deletion callback'` on the relation entity, which I based on the above patch and `node_revision_delete()`. I can now use the Entity API's `entity_revision_delete()` to cleanly remove the excess revisions in batches.

---
Tags: 7, entities
---


# Question
Title: hook_form_alter() to put multiple radios in a table
I have a content type that has a series of multi-value select fields. That I need users to select in relation to a value pulled from another node.

The best way to present this is to have a table that looks like this:

I've got the 'bones' of a hook\_form\_alter, and I can almost present what I need. However, I cannot seem to get my checkboxes/radios to appear in the grid. I am this far...

My form\_alter function looks like:

```
function hnbuilder_form_node_scheme_of_work_form_alter(&$form, FormStateInterface &$form_state, &$form_id){
/** check whether we passed a node reference into the form via ID in the url **/
if ($_GET['id']){
    $nid = $_GET['id'];
    /** if we didn't pass it in, we are editing the node **/
}else{
    $current_url = Url::fromRoute('<current>');
    $path = $current_url->getInternalPath();
    $path_args = explode('/', $path);
    $thisnid = $path_args[1];
    $thisnode = \Drupal\node\Entity\Node::load($thisnid);
    $nid = $thisnode->get('field_related_unit')->target_id;
}
/** Load the referenced node */
$node = \Drupal\node\Entity\Node::load($nid);

/** get the learning outcomes from the referenced node
    and put them into an array **/
$lo = array(
    0=>"",
    1=>"LO1 ".$node->field_lo1->value,
    2=>"LO2 ".$node->field_lo2->value,
    3=>"LO3 ".$node->field_lo3->value,
    4=>"LO4 ".$node->field_lo4->value
);

/** create table headers **//
$header = array(
    0 => 'Learning Outcome',
    1 => 'Assignment 1',
    2 => 'Assignment 2',
    3 => 'Assignment 3',
    4 => 'Assignment 4'
);

/** an array of the checkbox/radio options from our content type
    each field has 4 options
*/

$ffld = array(
    1=>$form['field_lo1_sow']['widget']['#options'],
    2=>$form['field_lo2_sow']['widget']['#options'],
    3=>$form['field_lo3_sow']['widget']['#options'],
    4=>$form['field_lo4_sow']['widget']['#options']
);

/** create a new array of options for the table
    */

$options = array(
    1=>array($lo[1],$ffld[1][1],$ffld[1][2],$ffld[1][3],$ffld[1][4]),
    2=>array($lo[2],$ffld[2][1],$ffld[2][2],$ffld[2][3],$ffld[2][4]),
    3=>array($lo[3],$ffld[3][1],$ffld[3][2],$ffld[3][3],$ffld[3][4]),
    4=>array($lo[4],$ffld[4][1],$ffld[4][2],$ffld[4][3],$ffld[4][4])
);

/** build the tableselect **/
$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#js_select' => FALSE
    );

return $form;

```

}

I think I have several issues, and I'm hoping someone can help:

1. I'm not sure that 'tableselect' is the right thing to be using, as it seems this only supports single selection (based on the table row).
2. I'm unsure how to display the existing checkbox/radios as actual field items. I'm stuck getting their values.

Is there a way to achieve this? If so, I'd really appreciate some pointers.

# Answer
> 2 votes
I think you can define a wrapper element as type `table`. The core user permissions form does this, and I think is similar to what you're trying to build:

```
 $form['permissions'] = [
  '#type' => 'table',
  '#header' => [
    $this->t('Permission'),
  ],
  '#id' => 'permissions',
  '#attributes' => [
    'class' => [
      'permissions',
      'js-permissions',
    ],
  ],
  '#sticky' => TRUE,
];
foreach ($role_names as $name) {
  $form['permissions']['#header'][] = [
    'data' => $name,
    'class' => [
      'checkbox',
    ],
  ];

```

In your case, I think you'd define something like `$form['sow']` as a `'#type' => 'table'` which will be a wrapper element that all the checkbox (or radios) appear under.

Then loop through your fields (these will be similar to how the user permission form loops through each permission, creating a row).

```
foreach ($fields as $low) {
  $form['sow'][$low]['description'] = [
    '#type' => 'item',
    '#title' => $low['title'],
    '#description' => ...,
  ];

  // Now loop through each assignment. This will be similar
  // to how the user permission form loops through each role
  // for each permission.
  foreach ($assignments as $assignment) {
    $form['sow'][$low][$assignment] = [
      '#type' => 'checkbox', // Or 'radio', depending on the need.
      // Other form element details here too.
    ];
  }

```

Then, for each assignment (these will behave similar to each role in the user permission form)

---
Tags: 8, forms
---


# Question
Title: viewswith multiple taxonomy fields with the same vocabulary, filters should show just selected terms
I have a content type with two taxonomy fields using the same vocabulary, I need a view with two exposed filters that, when both set to the same term, show just the nodes with that term in both taxonomy fields.

The current result is that when I use two "Content: Has taxonomy term (exposed)" filters and I select the first one to "term 1", I get all the nodes with "term 1" in the two taxonomy fields. When I select in the second filter to "term 1" onother time, I get the same set of results as before. What I would like to achieve is the following: when selecting "Term 1" in both the exposed filters I'd like to have just the nodes that have "term 1" in both the taxonomy fields.

How can I get this result?

Thanks

# Answer
> 0 votes
One way to do this would be to use a hook\_query\_alter() in a custom module. In your view you would set a tag in the query options ("same\_terms" in this example).

Then check if your exposed filter values are the same (you may need to change **tid** and **tid\_1** depending on your identifiers).

Finally you'd join the field tables which by itself would limit the result set to only nodes that have the same term in both fields. You would need to swap **field\_tags** and **field\_tag\_2** with your field names.

```
use Drupal\Core\Database\Query\AlterableInterface;

/**
 * Implements hook_query_alter().
 */
function YOURMODULE_query_alter(AlterableInterface $query) {
  // make sure you're only altering the right query.
  if ($query->hasTag('same_terms')) {
    $view = views_get_current_view();
    // If the exposed filter values are the same.
    if ($view->exposed_data['tid'] === $view->exposed_data['tid_1']) {
      $query->join('node__field_tags', 'field_1', 'field_1.entity_id = node_field_data.nid AND field_1.field_tags_target_id = taxonomy_index_value_0.tid');
      $query->join('node__field_tag_2', 'field_2', 'field_2.entity_id = node_field_data.nid AND field_2.field_tag_2_target_id = taxonomy_index_value_0.tid');
    }
  }
}

```

Alternatively if the filters don't need to be interchangeable, you could make the first one Content: Has taxonomy term and the second one filter the second taxonomy field specifically, which should almost accomplish the same thing. The downside here is that if only the second filter had a value it wouldn't filter on any term, only the second term.

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


# Question
Title: How do I set a custom input format for a field?
After using Drupal 7 for years, I am now handed a Drupal 8 site to do some editing. I have created a custom input format (*Plain HTML*), and I want to print this field with this input format in a custom template. How can I achieve this?

With `{{ content.field_mapka_markery }}`, it prints plain text. There is no choice to select my newly created input format in the *Manage display* settings. Why is that? In Drupal 7 there is always a new formatter, but not so in Drupal 8.

I also tried `{{ content.field_mapka_markery|raw }}` or `.value`. `|raw` doesn't work at all, and `.value` does the same as without it.

# Answer
> 0 votes
The plain text format filters the text before storing, as far as I know. You need to store it as a formatted string. Then you can apply any filters you like.

# Answer
> 0 votes
Managed to create a new field with "Text - Formatted - Long" as default, which allowed me to set up my custom text format. Why is that not possible for plain text field I am not sure.

---
Tags: 8, entities
---


# Question
Title: how to unit test an http client service with DI in drupal 8?
I have a service the consumes data from an external source. I would like to unit test the service and I am not sure how to get the test set up. To start with I would like to just test 1 method. Here is my service:

```
<?php

namespace Drupal\data_provider;

use Drupal\data_provider\Security\DataProviderCrypt;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\ClientInterface;
use Drupal\Core\Cache\CacheBackendInterface;

/**
 * DataProviderServic.
 *
 * @ingroup data_provider
 *
 * @group data_provider
 */
class DataProviderService {

  public $baseUri;

  protected $username;

  protected $password;

  /**
   * The HTTP client to fetch the feed data with.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * The cache.default cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

  /**
   * Constructs a database object.
   *
   * @param \GuzzleHttp\ClientInterface $http_client
   *   The Guzzle HTTP client.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   The cache object associated with the default bin.
   */
  public function __construct(ClientInterface $http_client, CacheBackendInterface $cache_backend) {
    $this->httpClient = $http_client;
    $this->cacheBackend = $cache_backend;
    $this->baseUri = \Drupal::config('data_provider.settings')->get('base_uri');
    $this->username = \Drupal::config('data_provider.settings')
      ->get('username');
    $this->password = \Drupal::config('data_provider.settings')
      ->get('password');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Forms that require a Drupal service or a custom service should access
    // the service using dependency injection.
    // @link https://www.drupal.org/node/2203931.
    // Those services are passed in the $container through the static create
    // method.
    return new static(
      $container->get('http_client'),
      $container->get('cache.default')
    );
  }

  /**
   * Create a formatted request based on options provided
   *
   * @param $url
   *   Requested URl.
   * @param array $options
   *  Query parameter options.
   * @param bool $reset
   *   Rest the cache.
   *
   * @return bool|string
   */
  public function doRequest($url, $options = array(), $reset = FALSE) {
    // request from api
    return $content;
  }

  /**
   * Return the data from the API in json format.
   *
   * @return bool|mixed
   */
  public function getSubscriptions() {
    // do_request and from the api and return info
    return $subscriptions;
  }

}

```

and here is my test:

```
<?php

namespace Drupal\data_provider\Tests\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\data_provider\DataProviderService;

/**
 * DataProviderServic unit test.
 *
 * @ingroup data_provider
 *
 * @group data_provider
 */
class DataProviderServiceTest extends UnitTestCase {

  /**
   * Very simple test of DataProviderService::getSubscriptions().
   * @todo write dataprovider tests.
   */
  public function testGetSubscriptions() {
    $dp = new DataProviderService();
    $subs = $dp->getSubscriptions();
    $this->assertEquals(TRUE, TRUE);
  }

}

```

when I run the tests I get these errors:

```
PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Testing
E

Time: 42.35 seconds, Memory: 610.25MB

There was 1 error:

1) Drupal\data_provider\Tests\Unit\DataProviderServiceTest::testGetSubscriptions
Argument 1 passed to Drupal\data_provider\DataProviderService::__construct() must be an instance of GuzzleHttp\ClientInterface, none given, called in /var/www/drupal8/docroot/modules/custom/data_provider/tests/src/Unit/DataProviderServiceTest.php on line 22 and defined

/var/www/drupal8/docroot/vendor/symfony/phpunit-bridge/DeprecationErrorHandler.php:73
/var/www/drupal8/docroot/modules/custom/data_provider/src/DataProviderService.php:63
/var/www/drupal8/docroot/modules/custom/data_provider/tests/src/Unit/DataProviderServiceTest.php:22

```

I believe the issue has to do with DI and how to properly do it. So my questions:
1. How do I start with testing methods on the service?
2. Should my unit tests make actual api requests or mock them?

# Answer
> 9 votes
You are on the right track!

Your tests should also never depend on calling out to external services. You should build a list of responses and scenarios you expect from the external service and ensure your tests are using your deterministic source data every time.

In your test you need to either provide instances of your dependencies or mocked versions of them through the constructor. PHPUnit ships with a few ways to mock dependencies, prophecy is a popular option (used below). It allows you to create mocks in the same fashion you expect them to be used in your code. Here is an example of creating a mock HTTP client with a response:

```
use GuzzleHttp\ClientInterface;
use Prophecy\Argument;
use GuzzleHttp\Psr7\Response;

$client  = $this->prophesize(ClientInterface::class);
// When the request method is called on the HTTP client, with "GET", a specific
// URL of our choosing and any third argument, make sure the following response
// is sent.
$client->request('GET', 'http://example.com/api-endpoint', Argument::any())->will(function () {
  return new Response(200, [], '[{"valid api response"}]');
});

$dp = new DataProviderService($client->reveal());

```

You can create a folder called "fixtures" and start creating files containing responses from your API. Start imagining scenarios where your API starts misbehaving, maybe sending some malformed JSON, create a test case and see how your code responds. A few

Note: this is just a starting point. You will need to handle the cache dependency and eliminate your calls to the "\Drupal" static methods in order to unit test your class. Click through to each method on the \Drupal class to see how you might inject it as a dependency. For example `\Drupal::config` is defined as:

```
  public static function config($name) {
    return static::getContainer()->get('config.factory')->get($name);
  }

```

So you might inject your settings as `$container->get('config.factory')->get('data_provider.settings')`.

Getting this stuff setup will always be a bit of a learning curve, but the stuff you'll pick up along the way will be invaluable, keep persisting!

I presented this session at DrupalCon Vienna which might have some useful information on testing in general: https://www.youtube.com/watch?v=MquqAplUXFY

---
Tags: 8, testing, dependency-injection, symfony-services
---


title: How do I import taxonomy terms

text:
# Question
Title: How do I import taxonomy terms
This is almost 6000 rows of taxonomy terms ranging over 8 columns that i'd like to import from csv. I would like to use it for facet search.

The CSV is located here (google\_product\_category).

The format is like:

```
# Google_Product_Taxonomy_Version: 2015-02-19
1 - Animals & Pet Supplies
3237 - Animals & Pet Supplies > Live Animals
2 - Animals & Pet Supplies > Pet Supplies
3 - Animals & Pet Supplies > Pet Supplies > Bird Supplies
7385 - Animals & Pet Supplies > Pet Supplies > Bird Supplies > Bird Cage Accessories

```

# Answer
As popular Drupal 7 modules like Taxonomy CSV import/export and Taxonomy Manager are not ported to Drupal 8, I recommend a very simple but functional module called term\_csv\_tree\_import.

After installing, go to `/csv-tree-import` and paste your taxonomies into the form. It assigns parent values from right to left, empty intermediate elements are allowed. You have to convert your CSV into the following format:

```
"element","subelement","subsubelement"

```
> 2 votes

# Answer
At the time of this writing, the options on drupal.org are:

I'd evaluate based on the method you're most comfortable with, the issues in the queues and the number of sites using each module.
> 2 votes

# Answer
You can also refer to the following module:

https://www.drupal.org/project/hti

However, CSV file needs to be formatted a bit differently. You would find a sample screenshot there.
> 0 votes

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


# Question
Title: How to attach external library in twig file with parameters?
I have below code to share on LINE messenger

```
<div class="line-it-button" data-lang="en" data-type="share-b" data-url="{{ current_path }}" style="display: none;"></div>
<script src="https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js" async="async" defer="defer"></script>

```

How to include JS using attach\_library?

```
{{ attach_library('https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js') }}

```

How to attach **async="async"** **defer="defer"** ?

Tried using

```
{{ attach_library('https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js', { 'async' : 'async', 'defer' : 'defer'}) }}

```

But not working :(

# Answer
In your **theme.libraries.yml** file add below lines

```
theme.social:
  js:
    'https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js' : { external: true, defer: true, async: true }

```

In your twig file

```
{{ attach_library('theme.social') }}

```

Clear cache & it works :)
> 2 votes

---
Tags: 8, theming
---