# Question
Title: How to use entity autocomplete for "user" target_type with specific roles?
I have created a form field with user autocomplete as below.

```
$form['user_list'] = [
      '#title' => ('Select User'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#required' => TRUE,
      '#selection_settings' => [
        'include_anonymous' => FALSE,
        'roles' => ['sales'],
      ],
    ];

```

I used "#selection\_settings" with roles specific, but this is not working. I want to filter user with "sales" only.

# Answer
> 5 votes
The selection settings array is passed to the plugin options, which in this case is `Drupal\user\Plugin\EntityReferenceSelection\UserSelection`.

In that class, you can see that the relevant array key is `$options['filter']['role']`, which is an array.

Therefore, the correct code here is:

```
$form['user_list'] = [
  '#title' => ('Select User'),
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#required' => TRUE,
  '#selection_settings' => [
    'include_anonymous' => FALSE,
    'filter' => [
      'role' => ['sales'],
    ],
  ],
];

```

---
Tags: 8, users
---


# Question
Title: Tokens keep 'disappearing', drush rr fixes the website for a time, sometimes hours sometimes seconds
As title suggests my problem is missing tokens, at random intervals tokens will just cease to work on the site in question which makes any webform entries that are emailed out to a client appear empty. It also gets rid of all metatags from pages.

Metatag shows this while broken:

Then if I catch it in a good mood after running drush rr:

I am unable to see any errors in the database logs, no warnings/notices around the time of this happening either. Haven't got Entity Tokens enabled. The behaviour seems entirely random. I have read en earlier question with similar problems being caused by Node Export, I do not have this installed either.

Latest Drupal Core, latest Metatag, latest Webform versions. Infact everything is latest version as I ran a bunch of updates hoping that would fix the ongoing issue.

The URL Alias Patterns page is also empty, regardless of whether I have run drush rr and appeased the bug.

SimpleTest run on Token results in 0 fails 0 exceptions and a few debug messages that don't seem relevant.

Webform seems to be the culprit here, as it happens more often when I'm submitting webforms, though I'm not sure if it is. Version 4.1 of Webform.

Any help/ideas greatly appreciated

# Answer
> 0 votes
We've run into this problem as well on a shared hosting production environment, as well as our staging environment. The first on PHP 5.5.9 with Zend OPcache v7.0.3, the latter with PHP 7.0.22 with Zend OPcache v7.0.22. In both environments some site un-deterministically "forgets" tokens. I debugged this down to function\_exists() in the implementation of the hook system of Drupal. It seemed PHP just forget that modules implement the hook\_info() functions.

A restart of PHP (PHP-FPM in these cases) fixes the problems, so my best guess is that the Zend OPcache is responsible for this erratic behavior. Note that the fact that environments are shared will probably increase the odds of this bug to surface.

---
Tags: webforms, tokens, meta-tags
---


# Question
Title: Different groups of radio buttons with the same name
I need to create several groups of radio buttons, grouped by a concept (collapsible) but the radio buttons must have the same name so that the form only sends one selected option among all the groups

```
Group 1
() Radio 1
() Radio 2
() Radio 3
Group 2
() Radio 4
() Radio 5
Group 3
() Radio 6
() Radio 7

```

I am developing a shipping method of commerce\_shipping This form is for choose a shipping service details, therefore I only generate a part of the form of the checkout page in the function that defines the details of the service, using the commerce\_shipping API. I test to set the #name property for all radio buttons but I lose the form tree, and I need to keep it so that another function can receive the data. Being inside commerce\_shipping I do not have absolute control either.

The question is: **What Form API elements should I use?**

I tested

```
$form['group_1']  = array (
  '#type' => 'fieldset',
  '#title' => t('Group 1:'),
  '#container' => TRUE,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);
$form['group_1']['radios'][] = array (
  '#title' =>  'Radio 1',
  '#type'=>'radio',
  '#return_value' => '1',
);

```

But ther resulting radio button name is group\_1\]\[radios\]\[0\] and the next is group\_1\]\[radios\]\[1\], as the name is different then they are not part of the same selection

# Answer
> 0 votes
Every group is a fieldset

```
  $form['pickup_group']['term_'.$tid] = array (
    '#type' => 'fieldset',
    '#title' => $pickupWrapper->field_taxonomy->name->value(),
    '#container' => TRUE,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

```

Every radio

```
  $form['pickup_group']['term_'.$tid]['shipping_pickup_point'][] = array (
    '#title' =>  drupal_render($renderable_node),
    '#type'=>'radio',
    '#return_value' => $pickupWrapper->getIdentifier(),
    '#parents' => array('commerce_shipping','service_details','shipping_pickup_point'),
  );

```

I solved adding the array of parents and itself in #parents on every radio, I don't like so much because I don't have control about this parents. My code doesn't generate this parents it comes from the commerce\_shipping API. But works...

---
Tags: forms, commerce
---


title: How to identify a paragraph?

text:
# Question
Title: How to identify a paragraph?
Is there a way to identify a paragraph in Drupal 8. Like is there a function to get the type as paragraph in code level?

I need to get it from a form alter function. My requirement is to get all the paragraphs in a form. Or identify the paragraph fields.

# Answer
You probably should look at the paragraphs module code, it does a lot of this.

That said, the basic process would probably be:

* Identify the form fields that are entity\_reference\_revision fields.
* Check that the field is limited to paragraph types (can just check 1st one).
* If it is an update form, get the referenced entities from the field.
* You will then need some recursive code to walk the paragraph tree to get sub paragraphs.

This will require using a lot of the field definition classes to get the information needed.
> 1 votes

---
Tags: 8, paragraphs
---


# Question
Title: How do I render a block programmatically with the standard template?
I'm using the following code to render a set of blocks programmatically:

```
$region_content = [];
$block_manager = \Drupal::service('plugin.manager.block');
$blocks = $this->getBlocks();
foreach ($blocks[$region_name] as $key=>$block_config) {
  $instance = $block_manager->createInstance($block_config['plugin_id'], $block_config['config']);
  $region_content[] = [
    $instance->build();
  ];
}

```

The contents of $block\_config\['config'\] look like this:

```
[
  'provider' => 'search',
  'admin_label' => '',
  'label' => 'Search form',
  'label_display' => TRUE,
  'third_party_settings' => [
    'block_aria_landmark_roles' => [
      'role' => '',
    ],
  ],
]

```

The resulting $instance object seems to work correctly, and when I render $region\_content I do indeed get the contents of the blocks as expected. But they are not wrapped in the block template. I thought I might have to do something like this:

```
$region_content[] = [
  '#theme' => 'block',
  'contents' => $instance->build(),
];

```

...but that doesn't work at all. How do I take this $instance object and render it using the standard block template? Or am I completely off course here?

# Answer
Yes, you need a render element with #theme = block, but this looks more like this example:

```
$build = [
  '#theme' => 'block',
  '#attributes' => [],
  '#contextual_links' => [
    'block' => [
      'route_parameters' => ['block' => $entity->id()],
    ],
  ],
  '#weight' => $entity->getWeight(),
  '#configuration' => $configuration,
  '#plugin_id' => $plugin_id,
  '#base_plugin_id' => $base_id,
  '#derivative_plugin_id' => $derivative_id,
  '#id' => $entity->id(),
  '#pre_render' => [
    static::class . '::preRender',
  ],
  '#block' => $entity,
];

```

You don't need to build this yourself, better use the view builder (where this code is from):

```
$build = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

```

Where $block is the entity of the configured block:

```
$block = \Drupal::entityTypeManager()->getStorage('block')->load($block_id);

```

To get all configured blocks of a region see How to get block layout programmatically?
> 1 votes

# Answer
If you want to render blocks directly from twig you can use:

**Twig tweak** 8.x-1.9 https://www.drupal.org/project/twig\_tweak

You just need to install it. The block should be configured on "admin/structure/block" page. Example how to use: `
Block:

{{ drupal_block('system_powered_by_block') }}
`

Add this code directly in the twig template file.
> 2 votes

---
Tags: theming, 8, blocks
---


title: Block caching based on time

text:
# Question
Title: Block caching based on time
I have a simple block that is used in the footer of a multiple language website. The text in the block changes based on user language so I using the following render attributes, which seems to work well.

```
$render['#cache'] = [ 'contexts' => ['languages'] ];

```

This block contains an image that is included with the following:

```
if( (date('Y') %2) == 1)
  $markup = '<img src="/themes/THEME/images/footer_odd_year.jpg">';
else
  $markup = '<img src="/themes/THEME/images/footer_even_year.jpg">';

```

One image is used for even numbered years and a second image is used for odd numbered years.

What is the correct way to setup caching base on this image changing once per year?

I have a similar situation with the home page of the website which changes each day. My current plan is to clear all caching levels for the website early each morning just after mid-night. This includes the Drupal caches, memcached and AWS Cloudfront. For pages like the home page, which change daily, I will need to keep max-age short to limit caching in the user's browser.

Is there any better way?

# Answer
> 5 votes
On this time scale, a cache TTL probably isn't the way to go, since the age is counted from creation time without respecting calendar years. You know exactly when the cache *should* expire (midnight on New Years') so instead of giving it a one-year maximum age it may be better to just actively clean it with a cron.

To avoid throwing away the entire cache (which can lead to significant performance degradation on some sites), you can use a cache tag:

```
$render['#cache']['tags'] = ['date:year'];

```

And then, in the annual cron, just invalidate the `date:year` cache tag like this:

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

function custom_cron() {
  $last = \Drupal::state()->get('system.cron_last');
  if (date('Y') !== date('Y', $last)) {
    Cache::invalidateTags(['date:year']);
  }
}

```

(Note that this solution does the absolute minimum of cache invalidation. If you find that your site performs well even if you completely purge the cache every day, that's fine.)

# Answer
> 2 votes
You can probably this using the D8 cache max-age setting. Basically, you can calculate the time until the next year and use this as the max-age. So each time the block is created set the max-cache to be the time until the next year.

To set the max\_age, use:

```
$render['cache']['max_age']['#default_value'] = $time_until_next_year;

```

---
Tags: 8, blocks, caching
---


title: Include a partial template

text:
# Question
Title: Include a partial template
I'm trying to use Drupal 8, with a custom theme, due big structure differences for my requirements I have a page--front.twig.html and a page.twig.html, I would like to create template parts as used in phrozn oder in a normal Symfony2 project, for example a footer.html.twig and a header.html.twig. These templates are saved under a subdirectory /parts/.

But when I call this templates as normal I just receive a string with the name of the template.

For example:

```
{# in page.html.twig or page--front.html.twig #}
{% include 'parts/footer.html.twig' %}

```

Returns the file name as string:

```
parts/footer.html.twig

```

It's possible to do that with Drupal 8?

# Answer
> 37 votes
You can't do relative paths, all paths must either be from the Drupal root or based on the namespaced path to your 'templates' directory: https://www.drupal.org/node/2143557.

I would avoid "from the Drupal root" and use namespaces, at least until https://www.drupal.org/node/2291449 is resolved.

```
{% include '@mytheme/parts/footer.html.twig' %}

```

> Edit: If you want to pass additional arguments for loop or for checking some vars to your included `twig` template you should write in this way:

```
{% include '@mytheme/includes/form-block.html.twig' with {dog: true} %}

```

Edit: Now that https://www.drupal.org/node/2291449 has been committed you can also do:

```
{% include 'footer.html.twig' %}

```

See https://www.drupal.org/node/2369981 for why you saw the file name as a string instead of a helpful exception.

# Answer
> 22 votes
Use a full path to the theme directory. If you use the namespace you'll have to change it if you bring the code to another site or theme.

This should work:

```
{% include directory ~ '/templates/parts/footer.html.twig' %}

```

# Answer
> 7 votes
Note you can pass variables after the `with` keyword :

```
{# template.html will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}

{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}

```

See Twig documentation http://twig.sensiolabs.org/doc/tags/include.html

# Answer
> 5 votes
It's also possible to use Twig's use of an array to create a fallback when the file doesn't exist.

Eg. If footer.html.twig isn't available, defaultfooter.html.twig would be used.

```
{{ include([
  '@yourthemename/parts/footer.html.twig',
  '@yourthemename/parts/defaultfooter.html.twig'
]) }}

```
Combine this with the use of variables in the filenames and you can include different files depending on some sort of context.

Nb: I'm still trying to work out whether this is best practice or not.

# Answer
> 5 votes
Now that Add Twig template inheritance based on the theme registry, enable adding Twig loaders has been committed, you can also use the following line.

```
{% include 'footer.html.twig' %}

```

# Answer
> 2 votes
For Drupal 8

**Including a twig file in the theme** when you do an `{% include 'FILE_NAME.html.twig' %}` Drupal expects that you FILE will be located in your current Theme Directory. Just put it there and it's going to work.

**Including a twig file in your Module**

If you want to add it in a MODULE, you have to declare it in the THEME Function. In your .module file just add the following:

```
<?php function YOUR_MODULE_NAME_theme($existing, $type, $theme, $path) {
   'FILE_NAME' => [
      'variables' => [
      ],
      'template' => 'FILE_NAME',
    ], ?>

```

Then put your Twig file in YOUR\_MODULE/template/FILE\_NAME.html.twig

---
Tags: 8, theming
---


# Question
Title: 'The alias is already in use' when editing a node that had an alias generated programmatically
I'm currently using an event subscriber to latch onto an event from a module that creates and/or updates nodes. I'm programmatically setting the url alias based on a user inputted field by doing the following

```
$path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

```

It works but when I open the node and attempt to edit it, I get the message

> The alias is already in use

When I try to save it. Is there something I'm missing? Does a field on the actual node have to be edited as well?

I'm also using pathauto if that has any effect.

UPDATE: I just noticed that whenever that aliased is saved it generates 4 entries in the URL alias list.

# Answer
> 1 votes
Turns out whenever you perform this

```
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

```

It generates a new alias every time even if the path alias already exists. I was able to resolve the issue by performing checks to see if the path already exists like so:

```
if (!\Drupal::service('path.alias_storage')->pathHasMatchingAlias('/node/' . $node->id()) && !empty($node->id())) {
    $path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");
}

```

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


# Question
Title: alter Suggestion box for apache solr autosearch
I want to restrict the suggestions for Apache Solr Search with `hook_apachesolr_suggestions_alter(&$suggestions, $env_id)`. I have gone through the code and found the suggestion is prompt from `apachesolr_autocomplete_suggest_word_completion()` called by a menu callback.

How can I override the suggestion block? I do not want to block indexing the words but just to hide them from suggestions.

Is there any hook available? Is `hook_apachesolr_suggesstions_alter(&$suggestions,$env_id)` useful in this case?

I am using `hook_apachesolr_querry_alter(DrupalSolrQueryInterface $query)`; I want to skip the parameters from the query. Is there any way to do this?

# Answer
> 0 votes
I was not able to find any hooks for the same. The alternate solution which I got is to implement hook\_menu alter.

As apachesolr uses hook\_menu() I altered the menu callback function.

# Answer
> 0 votes
Drupal 7's ApacheSolr module provides the following hook:

```
function hook_apachesolr_suggestions_alter(&$suggestions, $env_id)

```

In a custom module, if you implement

```
[my-custom-module-name]_apachesolr_suggestions_alter($suggestions, $env_id)

```

You can alter the suggestions array as follows:

```
function [my-custom-module-name]_apachesolr_suggestions_alter(&$suggestions, $env_id) {
    foreach ($suggestions as $searchTerm) {
        $replacement = $searchTerm->suggestion[0];
        if ($searchTerm = 'test') {
            $replacement = 'testing';
        }
        $suggestions[$searchTerm]->suggestion[0] = $replacement;
    }
}

```

If you inspect the arrays via debugging, you'll see the following before your replacement code runs so you just need to alter what it suggests. In this case it was suggesting 'best' when searching for test, so the code above would replace 'best' with 'testing'. You'll probably want to do some optimization for error testing, but this gets you pretty far.

---
Tags: search, ajax
---


# Question
Title: Modify apachesolr's 'did you mean?' suggestions to provide better alternatives
Has anyone modified the default apachesolr 'did you mean?' suggestions that is returned out of the box with the apachesolr module?

For instance, a search for 'diabetes' currently returns 'did you mean: rates' http://www.health.govt.nz/search/results/diabetes

Is there a way to add some form of control over this, or is the solution simply adding more nodes to the index in the hopes of making it a better spell checker?

# Answer
> 5 votes
I found setting: `<str name="spellcheck.onlyMorePopular">false</str>`

(instead of true) in solrconfig.xml dramatically improved the quality of the spelling suggestions.

# Answer
> 0 votes
I just posted this identical answer here for the question 'alter Suggestion box for apache solr autosearch' but am including at the question seems to be a duplicate:

Drupal 7's ApacheSolr module provides the following hook:

```
function hook_apachesolr_suggestions_alter(&$suggestions, $env_id)

```

In a custom module, if you implement

```
[my-custom-module-name]_apachesolr_suggestions_alter($suggestions, $env_id)

```

You can alter the suggestions array as follows:

```
function [my-custom-module-name]_apachesolr_suggestions_alter(&$suggestions, $env_id) {
    foreach ($suggestions as $searchTerm) {
        $replacement = $searchTerm->suggestion[0];
        if ($searchTerm = 'test') {
            $replacement = 'testing';
        }
        $suggestions[$searchTerm]->suggestion[0] = $replacement;
    }
}

```

If you inspect the arrays via debugging, you'll see the following before your replacement code runs so you just need to alter what it suggests. In this case it was suggesting 'best' when searching for test, so the code above would replace 'best' with 'testing'. You'll probably want to do some optimization for error testing, but this gets you pretty far.

---
Tags: 7, search
---


title: Hide a view if less than N results

text:
# Question
Title: Hide a view if less than N results
I wonder if it's possible to hide a view (as block view) if it has less than X results.

# Answer
It takes a bit to learn the views hooks. Do you know about view template files? If so a quick and dirty way to do it is to check how many rows there are in the highest level view template file the display output. If you have the Devel module installed you can `dpm($variables)` in views-view.tpl.php (you'll probably want to use the display output that is unique to your view).
I can't remember where, but somewhere in `$variables` is a row count; you can add the logic to the template file to not print out `$rows` if it does not meet your criteria.
> 1 votes

# Answer
You could in a template preprocess function easily detect the number of results (rows) that a view has and set the output to an empty string if that is the case.

To get this to work, you might need to do a bit of work in template, as Views always adds some wrapping HTML that you probably don't want if the view is empty.

I would probably be easiest to do in the template\_preprocess\_views\_view() preprocess function. You can consult the views interface to get hints about templates.
> 8 votes

# Answer
Based on the hint googletorp gave, my simple solution is to put this into my template.php:

```
function MY_THEME_NAME_preprocess_views_view(&$vars) {
  if ($vars['display_id'] == 'MY_DISPLAY_ID' && count($vars['view']->result) < 2) {
    $vars['view']->result = NULL;
  }
}

```

In this case I am hiding the view if it has less than two results.

Thanks a lot!
> 8 votes

# Answer
If the reason for this is primarily display-oriented (e.g., you are building a grid and want to force an even/odd number of items) then I suppose adding custom logic at the theme layer is certainly the most logical. The other answers have covered this I think. However, the issue that we found is that some views variables that may need to be changed (e.g., `$view->result = NULL`), cannot safely be altered as part of a preprocess function. It seems that views internal caching may generate some variables in such a way that some combinations of "rendered output" and "query result" cache settings can be incompatible with any of the existing solutions.

One alternative is to alter the results of the executed query itself, which offers control at a much lower level. This might also get around some of the issues with hiding wrapper markup as it simulates an "empty" results set even before the markup is built.

```
/**
 * Implements hook_views_post_execute().
 */
function MYMODULE_views_post_execute(&$view) {
  $view_name = 'myviewname';
  $view_display = 'mydisplay';
  // Don't show the view if there is only one item.
  if ($view->name == $view_name && $view->current_display == $view_display && count($view->result) < 2) {
    $view->result = array();
  }
}

```

This of course can't be implemented in a theme as it's not related to a theme or alter hook, but I think it's still worth noting for people interested in this question.
> 1 votes

# Answer
In some cases it is nicer for this sort of conditional to be put in the view, so that the builder understands what is happening within the edit view context, not in some other module or theme hook.

If you prefer having this logic included on the view edit page then you can do this:

1. Add a Global Text/HTML footer field and make the text format PHP Code
2. Set the admin name of this field to something very clear, e.g. 'Hide this view if less than 5 results', so that future site builders won't be confused (why is my view disappearing!?!?)
3. Modify the below PHP code to suit your needs and use in the field:

> ```
> <?php
> $view = views_get_current_view();
> if ( count($view->result) < 5 ) {
>     $view->result = null;
> }
> ?>
>
> ```
> 0 votes

# Answer
You could also do this using the theme templating:

* Copy `views-view.php` to your theme/templates directory
* make a copy of that file and name it `views-view--view-name--display-name.tpl.php`
* (See Advanced \> Other \> Theme:Information for more detail on what file names to choose and override - you can get more or less specific depending on your needs)
* add `if (count($rows) < $n):` in to your code to manipulate based on the number of results as needed
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I get entity_type and entity_id from any entity page?
Some pages (paths) represent one entity. For example:

* The pages at these paths represent one node entity, entity\_id (nid) is XX:
    + /node/xx
    + /node/xx/delete
    + /node/xx/edit
* The page at this path represents one search server entity (defined by search api module), entity\_id (machine\_name) is 'apache\_solr':
    + /admin/config/search/search\_api/server/apache\_solr

How do you load in the basic data about this entity (id and type) when the hook or function you are in doesn't hand it to you?

The standard way to get the current entity is apparently to use `menu_get_object($entity_type,$position_of_id_in_url)`. This, however, assumes that you are coding for just one entity type: you need to state the entity type programmatically, and, even worse, you the human being need to research and hard code in the url position of entity ids that this entity uses.

The closest I can find so far is getting the underlying system uri for the page (e.g. `substr(request_uri(),strlen($base_path))`), then writing a monsterous switch list based on something like this suggestion, guessing and then hard coding cases for every possible entity you think a site might ever have. But there must be something better than that, right?

While a general solution from core would be best, I'll also accept an answer that depends on common modules like ctools (page manager, contexts, etc), Entity API, Devel, etc.

My immediate need is for edit forms, within `hook_field_widget_form()`, for a widget that can (with appropriate config and modules) be attached to any fieldable entity type. So, while a general solution would be best, I would also accept a narrow answer that only works within this function or in forms (The id and data that is specific to entity type appears to be buried in $form, but keyed in an entity type specific way, so getting it out of $form seems like a chicken and egg problem).

------------ EDIT ------------------

Seems some people have difficulty understanding the simple general problem. Here's an alternate use case (another seperate but related problem I'm facing). Suppose you have a view that lists some entities. This view sits as a block/pane on pages that can represent one entity, such as a node page or a user profile (or both). You've got a hook set up that reads the views data and looks through the results (`foreach $view->result as...`). Let's say it's hook\_views\_pre\_render, which means you just have the $view object. You want to do something (say, remove the row or change some field data) if the view results row has the same entity id and entity type as the page does. You've got the logic down to extract this data from the view results, so all you need is to look up the entity\_type and entity\_id of the page being generated, to make a comparison. That data is in Drupal somewhere. If it wasn't, Drupal couldn't have figured out that it needed to load this view. So how do you get it when it isn't passed to the hook or function you are in?

# Answer
I spotted something that works as this in the module Token Filter (D7 version):

```
  // Attempt to fetch the entity that is being viewed via a backtrace to the
  // field_attach_view($entity_type, $entity) function and parameters §if found.
    $backtrace = debug_backtrace();
    foreach ($backtrace as $caller) {
      if ($caller['function'] == 'field_attach_view') {
        $entity_type = $caller['args'][0];
        $entity = $caller['args'][2];
        // do stuff with entity
        break;
      }
    }

```

Pretty smart - it figures out a function that must have happened before its function is called which will contain $entity\_type and $entity ($entity\_id would also work instead of $entity), and looks back through the backtrace object until it finds it.

Token Filter is a field processing module, so it will know that its function will always have been called after a call to field\_attach\_view(). I'm not if there is a good generic alternative to field\_attach\_view - but the general approach seems to work and a case-specific candidate can always be found for any specific case by dropping some backtrace debug code (formerly broken link fixed) into the point in the code where you need to get the entity, and seeing what's available (then checking logic and testing to make sure it is always present).
> 4 votes

# Answer
In Drupal Core, you cannot do this. The relevant issue to add such functionality is here.

What core itself does is always passing around two arguments:

```
function($entity, $entity_type)

```
> 4 votes

# Answer
The most straightforward way I have found to solve this issue is to implement `hook_entity_load()`.

```
function MODULE_entity_load($entities, $entity_type) {
  foreach ($entities as $entity) {
    $entity->entity_type = $entity_type;
  }
}

```

Then the object returned by `menu_get_object()` will have an entity\_type bound to it.
> 4 votes

# Answer
The following works for me to get entity and entity type by path:

```
/**
 * Get the entity and entity-type by path.
 *
 * @param string $path
 *   The path to the entity page.
 * @return array|boolean
 *   Contains the entity and the entity-type or false if entity or type could
 *   not be determinded.
 */
function custom_module_get_entity_and_entity_type_by_path($path) {
  $item = menu_get_item($_GET['internal_path']);
  if (empty($item['access']) || empty($item['page_arguments'][0]) || empty($item['load_functions'])) {
    return FALSE;
  }

  $entity = $item['page_arguments'][0];

  // Get entity-type.
  $load_function = reset($item['load_functions']);
  $entity_types = entity_get_info();
  dpm($entity_types);
  $entity_type = '';
  foreach ($entity_types as $type => $type_definition) {
    if ($load_function == $type_definition['load hook']) {
      // When the load_function from menu_get_item matches "load hook" of the
      // entity type definition, then the entity_type was found.
      $entity_type = $type;
      break;
    }
  }
  if (!$entity_type) {
    return FALSE;
  }

  return array('entity' => $entity, 'entity_type' => $entity_type);
}

```
> 1 votes

# Answer
may this help?

```
function entity_by_path($path) {
    $router_item = menu_get_item($path);

    $ent_sug_array = array();
    foreach ($router_item['map'] as $key => $value) {
        if(is_object($value) && isset($value->type)) {
           $ent_sug_array[$key] =  $value;
        }
    }

    $ent_sug = false;
    if(count($ent_sug_array) > 1) {
        $lf_sug = false;
        if(isset($router_item['load_functions'])) {
            if(count($router_item['load_functions']) == 1) {
                reset($router_item['load_functions']);
                $lf_sug = key($router_item['load_functions']);
            }
        }
        if($lf_sug !== false) {
            $ent_sug = is_object($router_item['map'][$lg_sug] && isset($router_item['map'][$lg_sug]->type)) ? $router_item['map'][$lg_sug] : $ent_sug;
        }
    } elseif(count($ent_sug_array) == 1) {
        $ent_sug = reset($ent_sug_array);
    }

    if(!empty($ent_sug)) {
        $bundle = $ent_sug->type;
        $ent_type = method_exists($ent_sug, 'entityType') ? $ent_sug->entityType() : false; //eck case
        if(empty($ent_type)) {
            $aclass = get_class($ent_sug);
            if($aclass == 'stdClass') {
                //node, user, core entity case
                if(isset($router_item['load_functions'])) {
                    $lf = reset($router_item['load_functions']);
                    $ei = entity_get_info();
                    foreach ($ei as $key => $value) {
                        if(empty('load hook'))
                            continue;
                        if($lf == $value['load hook']) {
                            $ent_type = $key;
                            break;
                        }
                    }
                }
            }else{
                //custom entity case
                $ent_type = $aclass;
            }
        }

        return array('entity'=>$ent_sug, 'type'=>$ent_type, 'bundle'=>$bundle);
    }

    return false;
}

```
> 0 votes

# Answer
The real answer to this question depends on why you need the data, and at what layer of the API layer cake you're operating.

If you want the entity for a *page,* you can't do that. A given page could have many entities on it. (Every node, comment, taxonomy... are all entities.)

If you're using `hook_field_widget_form()`, then you're implementing a field in the Field API, and your answer is in the documentation: Entity type is `$element['#entity_type']`, and you can't grab the entity ID, since fields implementing the API shouldn't concern themselves with that.

So: Why do you need the entity id?
> -1 votes

---
Tags: 7, entities
---


# Question
Title: How to use Views PHP to code if a view exists and has content then echo...
I have a view displaying a list a menu of all the content for a node. It contains a list of all the fields and views on the page, with the output rewritten as a link eg link to field A . I can do this fine for each field but I also have a view 'teachers' exposed as a block. If the view has content I want to have a link to it in the menu. I'm trying to use Views PHP to code if the view has content, echo '' What function do I call to see if the view exists and has content? I've tried if(views\_get\_view('teachers) == TRUE){ echo "";} but this always returns TRUE even if there is no content for that view for a specific node.

I want to do something similar to

# Answer
> 2 votes
You can look at views\_get\_view\_result() and do something like this:

```
$result=views_get_view_result('teachers');
if (isset($result[0])) {
  // we have results
} else {
  // we don't
}

```

# Answer
> 0 votes
It can be done simpler without querying for a result

```
$view = views_get_view('my_view_name');
if($view) {
  //continue logic..
}

```

---
Tags: views
---


# Question
Title: How to add a custom views filter handler for a specific field?
Currently I have a boolean field `field_private_content`, if that field is set, the content should only be shown to authenticated users, anonymous users may only see the teaser and a login form. So far it's working well, also with views where I added the filter on that field. The filter get's removed automatically by the implementation of `hook_views_pre_view()` in a custom module:

```
function custom_module_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Remove filter on field_private_content != TRUE for authenticated users.
  if ($view->getHandler($view->current_display, 'filter', 'field_private_content') && \Drupal::currentUser()->isAuthenticated()) {
    $view->removeHandler($view->current_display, 'filter', 'field_private_content');
  }
}

```

Although that works very well, the behavior is not obvious from views ui. I would prefer to have a duplicate of the field\_private\_content filter which should have the mentioned behavior by default and could be labeled properly - the original filter should keep it's original behavior.

How can that be achieved?

How to add a custom views filter handler for a specific field?

# Answer
> 13 votes
This require a little effort so I will only put here the main parts and a reference to an article that I used to create a custom Views filter in Drupal 8.

First you need to declare the filter inside the `hook_views_data_alter()` implementation:

```
$data['node_field_data']['nodes_titles'] = array(
  'title' => t('Node titles'),
  'filter' => array(
    'title' => t('Node titles'),
    'help' => t('Specify a list of titles a node can have.'),
    'field' => 'title',
    'id' => 'd8views_node_titles'
  ),
)

```

Since we are filtering on the title column, we are extending on the node\_field\_data table but with the title column as the real field to be used. Additionally, this time we are creating a plugin to handle the filtering identified as `d8views_node_titles`. Now it follows to create this class:

**src/Plugin/views/filter/NodeTitles.php**:

```
    /**
     * @file
     * Definition of Drupal\d8views\Plugin\views\filter\NodeTitles.
     */

    namespace Drupal\d8views\Plugin\views\filter;

    use Drupal\views\Plugin\views\display\DisplayPluginBase;
    use Drupal\views\Plugin\views\filter\InOperator;
    use Drupal\views\ViewExecutable;

    /**
     * Filters by given list of node title options.
     *
     * @ingroup views_filter_handlers
     *
     * @ViewsFilter("d8views_node_titles")
     */
    class NodeTitles extends InOperator {

      /**
       * {@inheritdoc}
       */
      public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->valueTitle = t('Allowed node titles');
        $this->definition['options callback'] = array($this, 'generateOptions');
      }

      /**
       * Override the query so that no filtering takes place if the user doesn't
       * select any options.
       */
      public function query() {
        if (!empty($this->value)) {
          parent::query();
        }
      }

      /**
       * Skip validation if no options have been chosen so we can use it as a
       * non-filter.
       */
      public function validate() {
        if (!empty($this->value)) {
          parent::validate();
        }
      }

      /**
       * Helper function that generates the options.
       * @return array
       */
      public function generateOptions() {
        // Array keys are used to compare with the table field values.
        return array(
          'my title' => 'my title',
          'another title' => 'another title',
        );
      }

    }

```

Inside the plugin, you need to override three methods, as explained in Creating a custom Views filter in Drupal 8. Here is a quote from it:

> Inside `init()`, we specify the title of the set of filter options and the callback that generates the values for options. This callback has to be a callable and in this case we opted for the `generateOptions()` method on this class. The latter just returns an array of options to be presented for the users, the keys of which being used in the query alteration. Alternatively, we could have also directly created the options inside the `init()` method by filling up the `$this->valueOptions` property with our available titles. Using a callback is cleaner though as you can perform various logic in there responsible for delivering the necessary node titles.
>
> The point of overriding the `query()` and `validate()` methods was to prevent a query and validation from happening in case the user created the filter without selecting any title. This way the filter has no effect on the results rather than returning 0 results. It's a simple preference meant to illustrate how you can override various functionality to tailor your plugins to fit your needs.

---
Tags: 8, views
---


title: Node::load() with specific revision ID

text:
# Question
Title: Node::load() with specific revision ID
I want to load the node details for a specific revision. I tried using the following code.

```
use Drupal\node\Entity\Node;
$nid = 1171;
$vid = 9423;
$rev_node = Node::load($nid, $vid, TRUE);

```

I also tried the following code.

```
$rev_node = node_load($nid, $vid);

```

It always loads the latest version, irrespective of the revision ID passed to the method/function call.

Is there a way to load the data for a specific revision?

# Answer
> 10 votes
Try with this code:

```
\Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);

```

# Answer
> 2 votes
You can use

```
$node = node_load($node_id);
\Drupal::entityManager()->getStorage('node')->revisionIds($node);

```

to get the revision IDs for a node.

You can then load a specific revision of a node with `$rev = node_revision_load($rev_id);`

# Answer
> 1 votes
Actually, `entityManager()` is deprecated in Drupal 8: https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AentityManager/8.5.x, so, instead, you could use `entityTypeManager()`:

```
\Drupal::entityTypeManager()->getStorage('node')->loadRevision($revision_id);

```

---
Tags: 8, entities
---


title: How can I hide a node flag using twig

text:
# Question
Title: How can I hide a node flag using twig
I want to hide the flag on a node if a boolean field is unchecked.

My Code in node.html.twig

```
{% if node.field_registration_status.value == 0 %}

<div class="registration-closed">

    {{ content|without('content.flag_class_registration') }}

  </div>

{% endif %}

{% if node.field_registration_status.value == 1 %}

   <div class="registration-open">

     {{ content }}

   </div>

{% endif %}

```

My CSS classes print as expected when the field is checked or unchecked. However, the Flag is not being removed from the output.

# Answer
The `without()` filter's argument should be just the name of the key itself, which in this case is `flag_class_registration` without the `content.`. Consider - the filter only receives the expression that comes before it, so it's already inside the content array.

```
   {{ content|without('flag_class_registration') }}

```
> 2 votes

---
Tags: theming, flags
---


# Question
Title: After logging off, a user is able to see the pages by pressing back button of the browser
I have a requirement in which the user should not be able to see the books in the site unless he is logged in. And the user is not able to see the content.

The problem is when a user logs in, views a book and its child pages, and logs out; he is still able to view the pages he opened before when he was logged in, by pressing the back button of the browser. He is not able to make any changes though.

This may create problems when users visit the site from a public computer, log off, and go away without closing the browser window.

Is there a module or any setting change I can use to solve this issue?

# Answer
> 7 votes
This is a result of the browser caching the page, there's not a lot you can do about it really.

Some browsers might respond to setting cache control headers like the following:

```
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

```

which might force the browser to re-load the page regardless of it's local cache.

There are apparently some options available to control this in Safari specifically, but I haven't been able to find anything for other browsers. I imagine the same would work for Chrome (being Webkit based), but I can't comment on the the other major browsers.

# Answer
> 1 votes
You can't stop the user from looking at the cache of his own browser. And you should not even try. Breaking the browser's navigation paradigm is not a recommended practice.

Having said that, there are tricks you can use to make it appear as if the back button is disabled. Users can get around those tricks, but you may fool some of the people some of the time.

Here is one page that explains those tricks: http://viralpatel.net/blogs/disable-back-button-browser-javascript/

Searching with Google for "Disable back button" will give you a lot more.

To add js to your site, look up drupal\_add\_js in the API.

# Answer
> 1 votes
Its too late but I came with a perfect solution. I have written a module Back Button Refresh.

**Configuration**

Install the module as regular process then configure Back Button Refresh block visibility settings in Home » Administration » Structure » Blocks

* Search Back Button Refresh block and set it to bottom region of your default theme. If admin theme is different then do the block settings for all of your theme you are using and has user restricted data so that this block must be available on your sensitive pages.
* Set visibility of block to display on all pages.

Any suggestions are most welcome.

# Answer
> 0 votes
You could use this code in a custom module :

```
<?php
/**
 * Implements hook_init().
 */
function MY_MODULE_init() {
  drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}
?>

```

---
Tags: 7, caching, users
---


# Question
Title: Allow users to manage their own mailing list?
I would like to allow each user to manage its own mailing list (import a csv list, add/remove emails). My goal is to allow users to send an email notification to this list when they create a certain content type.

Modules like simplenews, Views\_Send, or mailing\_list don't seem to match my needs as they only allow to create "globals" newsletters associated with a subscription system, not real email list "crud" by user.

Maybe should I use a generic csv data importer, views/bulk and rules to achieve this?

# Answer
> 0 votes
Start with adding a multi-value field to store eMail addresses. Say with a machine name like `field_email_addresses`. Assume the content type you're using for this is "Article" (pick whatever fits).

With the above in place, uou could use the Rules module to achieve your goal. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?". By using the rule included in that answer, you can discover scenarios such as these:

```
Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

```

Here is a simplified version of the rule that only shows the inserted values:

```
{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

If you just add a field with machine name "`field_email_addresses`" to your articles content type you should be able to import this rule in your own site and experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise). That will allow you to eMail relevant parts of the node whenever some eMail Id is added to that field already.

Some suggestions to further improve this solution:

1. Send it to **all** (not just updated) eMail ids mentioned in the `field_email_addresses` field, by creating another rule that is triggered with Rules Event "After saving a new node of content type Article".
2. Also use the Flag module so that if the node is flagged by the node author (and only then), send it to **all** eMail ids mentioned in the `field_email_addresses` field (something that is straight forward to do with another rule).
3. Variation of the previous item (which does not require the Flag module): add an extra (boolean) field to Articles, to indicate something like "Send this node as an eMail now".
4. Replace that `field_email_addresses` field (related to the Article content type) by a similar profile field with similar purpose. So that by combining it with the Views Rules module, you create a Rules loop to eMail all those users when such article is created, flagged, etc.

The above are just some basic solutions to implement what you're looking for. To further improve it (eg: combine it with importing a CSV list) should really be a different question.

---
Tags: 7, emails
---


title: Trying understand the feed importer

text:
# Question
Title: Trying understand the feed importer
I inherited this website that has this product feed importer for my commerce store the products load correct but the category hierarchy\_category is not being assigned in the content display field. I am trying to under "Search Taxonomy terms by: There are three selects. my csv feed has Hierarchy\_Category column that is map product category. My Hierarchy\_Category are numbers but the search is set to term name. Do I need to change to Term ID

# Answer
If you have term name in your product sheet then keep it as term name otherwise change it to the tid if you have term-id. (Make sure that you entered exact term name which is stored in database).

Feeds module automatically detects it.
> 0 votes

---
Tags: commerce, importing-exporting
---


# Question
Title: URL for authenticated user edit own webform submission
I have checked the "authenticated user" option in "content"\>"nameOfMyWebform"\>"Webform"(tab)\>"Form settings"\>"Submission access"\>"Roles that can submit this webform".

My problem is that I don't know the link (URL) to access to the edit submission page like an authenticated user. I don't know if it is configurable and I have tried with many URL...

# Answer
I have solved with the Permissions per Webform module and the URL /node/nid/submission/sid/edit
> 0 votes

# Answer
BTW, there is a brand new "Redirect to login when access denied to submission" setting which does exactly what it says it does in the latest dev release. (/admin/structure/webform/manage/contact/settings/submissions)
> 0 votes

---
Tags: webforms, users, redirection
---


# Question
Title: Get Field Collection Array From Field Collection ID
I'm using the following code to return array of **all** field collection IDs for a node's field collection. How do I use these IDs to get an array of the values of the fields **within** the field collection?

```
case 'field_collected_dates':
$fid = field_get_items('node', $node, $key, $node->language);
$return[ $key_clean ] =  $fid;
break;

```

# Answer
> -1 votes
this is how you can get values from field collection

```
if(isset($node->field_field_collection['und'])) {
  foreach($node->field_field_collection['und'] as $field){
    $colection_node = entity_load('field_collection_item', array($field['value']));
    $name_from_collection = $colection_node[$field['value']]->field_field_name['und'][0]['value'];
  }
}

```

now you can understand how to get value from field collection try to fix this in your code

THANKS

---
Tags: 7, entities
---


title: Pass argument to buidlform?

text:
# Question
Title: Pass argument to buidlform?
So i have a simple form that extends the FormBase and when i call the form i pass it an argument, depending on what the user selects within the form itself i rebuild the form and i need to pass a new argument to the buildForm, how do i do this?

```
class MyForm extends FormBase {
    public function buildForm(array $form, FormStateInterface $form_state, $frv = null) {
      ...
    }
    public function validateForm(array $form, FormStateInterface $form_state) {
        ...
        if (true) {
            $form_state->setRebuild();
            $frv = 'some new string';
            // somehow pass this new $frv to the buildForm ???
        }
    }
}

```

# Answer
> 1 votes
$form\_state-\>set() will help do this,

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

  if($form_state->get('variable')){
    //do your logic
  }
}

public function validateForm(array $form, FormStateInterface $form_state) {
    ...
    $form_state->set('variable', 2);//any value

    if($form_state->get('variable')){
      $form_state->setRebuild(TRUE);
    }
}

```

---
Tags: forms
---


# Question
Title: Several same product with a customizable field
I need a customizable field for a product in Drupal 8 drupal-commerce. I succeeded to add such field through an order item type. But if I want to add several same products on cart, this field stand uniq for all the products.

How can I have a line in cart by same product with the specific value of the customizable field for each one (I'd like to avoid the creation of a product variation by specific value. This specific value is customizable and so not in a finite set) ?

Thank you very much for your help.

# Answer
I think I found how to answer to my need :-)

The configuration is done throught the product settings (Commerce\>products then select the product to configure and click to edit)

In "Manage display" tab, edit the configuration of the "Variations" Field which is in Format "Add to cart form". Uncheck box "Combine order items containing the same product variation."

Hope it helps !!
> 1 votes

---
Tags: commerce
---


# Question
Title: How to create a page category of products in Commerce 2?
Usually in commerce 1 did: Display-products (node), in which field "Catalog" of taxonomy-term. Create a displays. Go to the term page and see all products! Great!

In commerce 2 tried to do but failed, probably because product is not a node, and the view for taxonomy, only works on him and no teaser.

Tell me, how do organized easy catalog on commerce2?

Preferably without the panels and search\_api. Thank you.

# Answer
> 1 votes
Unfortunately, this is an issue with Drupal core itself and the Views module.

As you mentioned right now the taxonomy term views in core has `Content: has taxonomy term ID` which only work with nodes.

It should be `Entity: has taxonomy term ID` so it can handle other entities such as Drupal Commerce products

There's an issue in Drupal core/views here that you can read about it, for the time being there's a module that will help you out with this situation.

**Commerce: Product taxonomy filter**

> The Module extends Taxonomy module from Drupal core and provides a new contextual filter "Product has taxonomy term ID (with depth)".

*Note that the contexual filter has to know your entity reference machine name*

---
Tags: 8, commerce
---


# Question
Title: Are all updates (revisions) to a user recorded in the logs?
A user was created just over a week ago and at some point was given a particular role by an administrator. Will this update (the role given, the date/time of the update and the admin who made it) have been recorded by default in the database somewhere? I don't have any special user modules installed on the site e.g. User Revisions. When I tested just now by giving roles to a user and then looking in "recent log messages" (filtered to "user"), my update didn't show there, so I'm guessing the answer's no, but if there is a way to retrieve this info it would be helpful.

# Answer
> 0 votes
Unfortunately not: Changes to a user are not logged (even though newly created users are), and the user entity does not support revisions in core (as of Drupal 8.4.2).

You could add an extra submission function with `hook_form_user_form_alter()` that creates a log message.

---
Tags: users
---


# Question
Title: How would I print out the first instance of a paragraph bundle in a node template?
I have a node type `article` with a paragraph field `field_sections` with the available bundles `section_image` and `section_text`. In my `node.html.twig` file I'd like to render out the first instance of any `section_image` bundles that may have been added. Any ideas on how to achieve this? Not sure if twig logic is correct way to go about this or if I should have a function in my .theme file that does the logic and returns a variable to do this that I could use in the twig file.

# Answer
**TWIG**

In twig you can check for the paragraph bundle in the items loop of a field template and only print the first item found:

*field--node--field-paragraph--content-type.html.twig*

```
  <div{{ attributes }}>
    {% for item in items if item.content['#paragraph'].bundle == 'paragraph_type' %}
      {% if loop.index == 1 %}
        <div{{ item.attributes }}>{{ item.content }}</div>
      {% endif %}
    {% endfor %}
  </div>

```

And then print this field in the node template:

```
{{ content.field_paragraph }}

```

**UI**

For a UI solution you need a field formatter like Paragraphs summary formatter, which in the moment only exists in a sandbox version, see https://www.drupal.org/project/paragraphs\_summary/issues/2803859#comment-11804075
> 0 votes

# Answer
Thank you @4k4!

Very interesting.. Another solution I discovered here using the Paragraph's issue queue:

https://www.drupal.org/project/paragraphs/issues/2925077

Code dump of final solution:

https://gist.github.com/krisrobinson/2e45bd817d562c3c6bc0f377e079da89
> 0 votes

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


title: Drupal Commerce 2 deployment

text:
# Question
Title: Drupal Commerce 2 deployment
I'm developing a store on Drupal 8 with Drupal Commerce 2.1. I'm doing it locally using docker4drupal Docker containers.

I just want to be sure that all my Commerce settings including categories, products and variations will be transferred to the external server during deployment.

Do I need special modules or methods for this except copying the files, database etc?

# Answer
> 1 votes
I don't think you *need* special modules or methods. **Just copying the files and exporting/importing the database *is enough***. A module like Backup and Migrate can help you on that task but is not a must.

Anyway and as an extra information there are some optional but good practices (tools):

* **Drush**: Apart that it can help you on some tasks (clearing cache, enabling modules, etc) it also can help you make a database dump using a command like `drush sql-dump > file.sql`, then you transfer the database to your server and you can import the database with a command like `drush sql-cli < file.sql`. If you are using Drupal 8.4.\* just make sure to use drush 8.1.12 or higher. Drush can also help you syncronize the local dev site with the production site and even clone the site (more advanced).
* **Git** repository: It will help you track custom files and even the configuration using a sync directory. The good thing about this is that you actually don't "transfer" the files, but commit/checkout, it can help you on your development workflow. Some people commit also the drupal or vendor files, other people (like me) just commit the custom files (modules and themes) and commit the composer files (see next).
* **Composer**. The good thing about this is that you just transfer the composer.json and composer.lock file and then on the production server just run the command `composer install --no-dev` and it will download all the drupal/vendor files including contrib, modules, themes, libs, etc that you specified in the composer.json file (so you're actually not transfering the files). Specifically for commerce, the project base of drupal commerce can be a good starting point. Just customize it as you want.
* **Config Split module**. It will helps on spliting your configuration so you can have modules that are enabled only locally on your dev environment but not enabled on the production server (like explained here), so in combination with *composer* you can have downloaded and enabled the *devel* module locally but not in the production server (as an example).

This answer is not intended to give you a *how to* on the tools mentioned, but to let you know some tools that exists and can help you in the process of developing drupal sites in general, if them sounds new to you and you are interested in any topics, please look their documentation sites and look around the internet as there are plenty of information, tutorials and videos that will help you consolidate your own workflow.

---
Tags: 8, commerce
---


# Question
Title: Get current language of Drupal 8 in javascript?
How can I get the language code or name from the Drupal javascript object in a js script ??

I know I can get language using this in php:

> $language = \Drupal::languageManager()-\>getCurrentLanguage()-\>getId();

But I need to have the language in my scripts.

All i got so far is the Drupal Jquery variable

> Var d = Drupal;

Which when printed looks like this.

```
{behaviors: {…}, locale: {…}, throwError: ƒ, attachBehaviors: ƒ, detachBehaviors: ƒ, …}
Ajax:ƒ (base, element, element_settings)
AjaxCommands:ƒ ()
AjaxError:ƒ (xmlhttp, uri, customMessage)
ProgressBar:ƒ (id, updateCallback, method, errorCallback)
Views:{parseQueryString: ƒ, parseViewArgs: ƒ, pathPortion: ƒ, getPath: ƒ}
ajax:ƒ (settings)
attachBehaviors:ƒ (context, settings)
behaviors:{autologout: {…}, drupalDisplace: {…}, responsiveImageAJAX: {…}, AJAX: {…}, activeLinks: {…}, …}
checkPlain:ƒ (str)
debounce:ƒ (func, wait, immediate)
detachBehaviors:ƒ (context, settings, trigger)
dialog:ƒ (element, options)
displace:ƒ displace(broadcast)
encodePath:ƒ (item)
formatPlural:ƒ (count, singular, plural, args, options)
formatString:ƒ (str, args)
history:{fetchTimestamps: ƒ, getLastRead: ƒ, markAsRead: ƒ, needsServerCheck: ƒ}
locale:{}
stringReplace:ƒ (str, args, keys)
t:ƒ (str, args, options)
theme:ƒ (func)
throwError:ƒ (error)
url:ƒ (path)
views:{instances: {…}, ajaxView: ƒ}
__proto__:Object

```

# Answer
> 5 votes
You can add whatever you want to the `javascript` via your `THEMENAME.theme`:

```
function THEMENAME_preprocess_page(array &$variables) {
    $variables['#attached']['drupalSettings']['language'] = $language;
}

```

After that, you can call it in `javascript`:

```
console.log(drupalSettings.language);

```

**Edit**

You need to enable `drupalSettings` as a dependency in your `THEMENAME.libraries.yml`:

```
frontend:
  dependencies:
    - core/drupalSettings

```

# Answer
> 36 votes
In pages with the core/drupalSettings library included, it seems to be pretty reliably available through the path:

```
var langCode = drupalSettings.path.currentLanguage;

```

---
Tags: 8, javascript
---


# Question
Title: Error when creating taxonomy term programmatically
I'm trying to create a term programmatically:

```
$term = Term::create([
  'vid' => 'vocabulary_mane',
  'name' => 'term_name',
]);

$term->save();

```

---

I can see my term in my overview page in the back-end:

---

But when I click on modify, I will receive an error page:

---

In the journal this is the log:

---

What is wrong?

# Answer
i found the solution.

the problem was with uppercase/lowercase **vid** value.

If your vocabulary starts with an uppercase letter ex: **'Animal'**, thr vid value will starts with a lowercase letter ex: **'animal'** otherwise you will have an error

This was my problem, hope it will you help.
> 0 votes

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


# Question
Title: How to troubleshoot my VBO operation which freezes at 50% every time?
I have written custom code that creates a new action for Views Bulk Operations (VBO). I am trying to run the action and it gets stuck at "Prepared 46748 out of 46766". If I run the same action with 25 or 100 records it works perfectly.

Code has been changed but not that directly impacts this process. I do not know what code causes the regression and too many changes have been made to go back one commit at a time.

There is nothing Watchdog related to this process.

A little more on the custom action. The custom action adds the `nid` for each node to a queue to be processed fully over many cron jobs. I think the issue stems from the fact that every time a node is prepared by VBO it does a node save but I do not know what is happening to be sure.

I am looking for advice on how to troubleshoot this scenario and find a solution.

# Answer
Try to (temporary) increase the available memory with like 10 or 25%, and see if you get past that nr of 46748 (possibly even past 46766). If it doesn't help, it won't hurt ...

BTW, even though this question is not about using Rules in combination with VBO, you might want to also watch the video about "More details about VBO settings" (especially what is explained between (about `04:00` and `05:00`). It provides some extra hints / tips to process like 100.000 nodes at once, which is quite a challenge to get to work (memory requirements, etc).
> 0 votes

---
Tags: views, actions, queue
---


# Question
Title: How to transmit parameters to Rules Component upon using Rules Scheduler programmatically?
Now I'm trying to create a Rules Scheduler task programmatically.

I've created a Rules Action with parameters and callback, also I've created a Rules Component with this Rules Action.

But upon trying to create the Rules Scheduler task programmatically I can't transmit it parameters for the Rules Component.

I'm using code, found here.

```
$now = new DateTime();
    $component = 'yrv_invitation_coupon_test_rule';
    $task_id = $now->getTimestamp();

    rules_action('schedule', ['component' => $component])
        ->executeByArgs([
            'date' => $now->getTimestamp()+10,
            'identifier' => $task_id,
            'param_uid' => 10,
            'param_rid' => 5,
        ]);

```

It works, but with default parameters.That is, executed Action in the Component can't get param "uid" with value = 10 and param "rid" with value = 5.

Could ou clarify me, how can I assign parameters ?

Here's my Action

```
$actions['yrv_invitation_coupon_user_remove_role'] = [
        'label' => t('Remove a role assigned upon activation an invitation coupon'),
        'group' => t('System'),
        'base' => 'yrv_invitation_coupon_remove_role_callback',
        'parameter' => [
            'uid' => [
                'type' => 'integer',
                'label' => t('User ID'),
                'default value' => 1,
            ],
            'rid' => [
                'type' => 'integer',
                'label' => t('Role ID'),
                'default value' => 1,
            ]
        ],
    ];

```

And here's my Rule Component

```
$rule = rule();
    $rule->label = 'YRV Invitation coupon test Rule';
    $rule->class = 'Rule';
    $rule->action('yrv_invitation_coupon_user_remove_role', ['uid' => 1, 'rid' => 1]);
    $rule->active = TRUE;

    $configs['yrv_invitation_coupon_test_rule'] = $rule;

```

# Answer
> 0 votes
Fortunately, I managed to find the solution.

Namely, a Rule component should be created such way.

```
function yrv_invitation_coupon_default_rules_configuration()
{
    $configs = [];

    $rule = rule([
        'uid' => [
            'type' => 'integer',
            'label' => t('User ID'),
        ],
        'rid' => [
            'type' => 'integer',
            'label' => t('Role ID'),
        ],
    ]);
    $rule->label = 'YRV Invitation coupon test Rule';
    $rule->class = 'Rule';
    $rule->action('yrv_invitation_coupon_user_remove_role', []);
    $rule->active = TRUE;

    $configs['yrv_invitation_coupon_test_rule'] = $rule;

    return $configs;
}

```

---
Tags: 7, rules
---


# Question
Title: Use Views to wrap large passages of text into 32700 character chunks
I am using Views to create an XML feed. The body portion of the xml is wrapped in specialized `<text>` tags. I need to break up this body text into chunks of 32700 characters each and wrap them each in `<text>` tags.

I know I can easily trim the body to 32700 characters in Views, but I then need to display the overflow text in another block of `<text>`.

# Answer
In your view, if you click `Theme: Information` under `Advanced`, you'll get a lot of tpl.php file names that you can use.

For this view called `Output Test`, we can see the below under information for the field `Body`.

```
Field Content: Body (ID: body): views-view-field.tpl.php,
views-view-field--body.tpl.php,
views-view-field--output-test.tpl.php,
views-view-field--output-test--body.tpl.php,
views-view-field--page.tpl.php, views-view-field--page--body.tpl.php

```

We can see the first one is called `views-view-field.tpl.php` and that is the file we can find in our `modules/views/theme` folder. We have to copy that to anywhere in our theme folder and then rename it to the most relevant tpl.php listed in our view's Information.

For this example, that's `views-view-field--output-test--body.tpl.php`

At this point, after copying the file to your theme folder and renaming it appropriately, you can clear cache so Drupal will know to look for it. Seriously, do this. It's infuriating working on something when Drupal doesn't even know to look for your work.

This file has `<?php print $output; ?>` as what we would usually print in our view. A basic example of outputting every 32700 characters between `<text></text>` tags is below.

```
<?php
    $split = str_split($output, 32700);
    $joined = implode('</text><text>', $split);
    print '<text>'. $joined . '</text>';
?>

```

What the above does is split your output, re-implode and finally add the outer tags.

I have no idea of the exact output of your XML feed so you need to look up the appropriate PHP from here. If the text is already wrapped in tags because of the view, just `print $joined;` or something.

Hope that helps.
> 0 votes

---
Tags: views
---


title: Can't find where to edit content

text:
# Question
Title: Can't find where to edit content
I've recently inherited an Drupal 8 website. www.berkslibraries.org At the bottom of the site in the footer there is the word Contact and under it a link to Hours & Locations, email address, and a phone number. I have searched through Drupal and can't find where that information in stored to change it. It's not in the content section or in the custom blocks. I was hoping someone might have some advice on where I can possibly look to change that info.

Thanks,

# Answer
Judging from the lack of block or menu HTML wrappers around this section, it looks like this is embedded in the site's page template. You will not be able to edit this from the GUI. Instead, look in the theme directory, templates subdirectory for the files that need to be edited.
> 0 votes

# Answer
When you log in as admin. just hover your cursor over the words and you can do a quick edit. You might have tried create content. If you just click content, all content created will populate.
> 0 votes

---
Tags: 8, nodes, emails
---


# Question
Title: View sorting issue related to Content Translation
I have used **Content Translation** module to translate nodes in zh-hant.

They are extracted at the View block using **Content: Translation language (= Interface text language selected for page)** filter and sorted by **Content: Weight (asc)**, which is a bunch of integers.

The nodes are placed in a correct order in en(the original language) but not in zh-hant. In my case, they are placed with weight order 3, 1, 2.

Is it a bug of the module or I have done something wrong?

# Answer
Set the Weight translatable at **\[Configuration \> Regional and language\]** can solve the problem although it makes no sense at all.
> 0 votes

---
Tags: views, transliteration
---


# Question
Title: Having fatal error when rendering search block in page.html.twig
I'm using Bootstrap theme on Drupal 8. How can I print the default search block form in page.html.twig?

Nov 22,17 @9am **Update my question for @No Sssweat and @Ramdas Gaikar**

I have tired this before my post. I’m not sure is it because the bootstrap theme. I do receive an error message when using this method

> "The website encountered an unexpected error. Please try again later."

In MYTHEME.theme

```
function MYTHEMENAME_preprocess_page(&$variables) {

    $block = \Drupal\block\Entity\Block::load('search-block-form');
    $block_content = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
    $variables['CUSTOMENAME'] = $block_content;
}

```

In page.html.twig

```
{{ CUSTOMENAME }}

```

**Update error message @ 10:30am in Nov 22**

Shortened error:

> Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given, called in /Users/useraccount/Sites/devdesktop/test-drupal-8/themes/testtheme/testtheme.theme on line 23

Full message with stack trace:

```
Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given, called in /Users/useraccount/Sites/devdesktop/test-drupal-8/themes/testtheme/testtheme.theme on line 23 and defined in Drupal\block\BlockViewBuilder->view() (line 70 of /Users/useraccount/Sites/devdesktop/test-drupal-8/core/modules/block/src/BlockViewBuilder.php) #0 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/includes/bootstrap.inc(566): _drupal_error_handler_real(4096, 'Argument 1 pass...', '/Users/useraccount/Si...', 70, Array) #1 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/modules/block/src/BlockViewBuilder.php(70): _drupal_error_handler(4096, 'Argument 1 pass...', '/Users/useraccount/Si...', 70, Array) #2 /Users/useraccount/Sites/devdesktop/test-drupal-8/themes/testtheme/testtheme.theme(23): Drupal\block\BlockViewBuilder->view(NULL) #3 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Theme/ThemeManager.php(287): testtheme_preprocess_page(Array, 'page', Array) #4 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('page', Array) #5 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false) #6 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Template/TwigExtension.php(490): Drupal\Core\Render\Renderer->render(Array) #7 /Users/useraccount/Sites/devdesktop/test-drupal-8/sites/default/files/php/twig/5a0f2c582d265_html.html.twig_1tSCfq69xi0uPcf7-7MUaQqQN/xi3VbzQaML3prijWzrpd_WRrzwIGH4jFi_SeWD3krj8.php(108): Drupal\Core\Template\TwigExtension->escapeFilter(Object(Drupal\Core\Template\TwigEnvironment), Array, 'html', NULL, true) #8 /Users/useraccount/Sites/devdesktop/test-drupal-8/vendor/twig/twig/lib/Twig/Template.php(432): __TwigTemplate_37eb0decd5b0d9ff7b62920677f1e56389764cee16a2b3161919a7109301c109->doDisplay(Array, Array) #9 /Users/useraccount/Sites/devdesktop/test-drupal-8/vendor/twig/twig/lib/Twig/Template.php(403): Twig_Template->displayWithErrorHandling(Array, Array) #10 /Users/useraccount/Sites/devdesktop/test-drupal-8/vendor/twig/twig/lib/Twig/Template.php(411): Twig_Template->display(Array) #11 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/themes/engines/twig/twig.engine(64): Twig_Template->render(Array) #12 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Theme/ThemeManager.php(384): twig_render_template('themes/testtheme/tem...', Array) #13 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('html', Array) #14 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false) #15 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(147): Drupal\Core\Render\Renderer->render(Array) #16 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/Renderer.php(576): Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() #17 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(148): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #18 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/EventSubscriber/MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch)) #19 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(108): Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher)) #20 /Users/useraccount/Sites/devdesktop/test-drupal-8/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent)) #21 /Users/useraccount/Sites/devdesktop/test-drupal-8/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #22 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #23 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #24 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #25 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true) #26 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #27 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #28 /Users/useraccount/Sites/devdesktop/test-drupal-8/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #29 /Users/useraccount/Sites/devdesktop/test-drupal-8/core/lib/Drupal/Core/DrupalKernel.php(657): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #30 /Users/useraccount/Sites/devdesktop/test-drupal-8/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request)) #31 {main}.

```

# Answer
To render contributor module block's

```
function theme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('search-block-form');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
  $variables['youblockname'] = $block_content;
}

```

and in your theme file just use

```
{{ youblockname }}

```

and rebuild the cache.

Similar to this question
> 0 votes

---
Tags: theming, 8, blocks, search, bootstrap-theme
---


title: libraries-override not working

text:
# Question
Title: libraries-override not working
I'm trying to figure out how I can remove the default css libraries of Drupal 8 on the theme I'm working on. I tried using `libraries-override:` to remove a specific `CSS` but it doesn't seem to be working. The css file is still showing. As you can see the align.module.css is still showing on Google Network Tab. I'm not sure if the method I'm using is deprecated or incorrect

```
name: Barebones
description: Drupal light
type: theme
core: 8.x

base theme: stable

libraries-override:
  system/base:
    css:
      component:
        /core/modules/system/css/components/align.module.css: false

```

```
libraries-override:
  system/base: false

```

# Answer
> 2 votes
You can override a library using the filename as key.

```
libraries-override:
  system/base:
    css:
      component:
        css/components/align.module.css: false

```

But if your asset was already overwritten by another module (e.g. classy theme overriding a core system asset), you have to use the full path instead, example:

```
libraries-override:
  system/base:
    css:
      component:
        /core/themes/stable/css/system/components/ajax-progress.module.css: false

```

Also see this issue.

---
Tags: theming, 8
---


title: Delete nodes using Rules and VBO

text:
# Question
Title: Delete nodes using Rules and VBO
Rues and VBO are not working as expected to delete nodes. Can someone tell me what I'm missing? Thank you.

What I have:

1. A View with VBO field which successfully selects all nodes of a certain type based on how long ago they were created. (The Preview shows all the desired nodes.)
2. A Rules Action set which:

A. Load a list of entity objects from a VBO View. Obviously the chosen View is the View from step 1 above.

B. Loop through the list of entity objects.

C. Deletes each list item using "Delete entity".

3. A Rule which runs on cron and has for its only action the above Action Set (and no conditions).

However, it's not working. I run cron via drush and none of the nodes are deleted.

I have cleared all caches, recreated each part of the process from scratch (i.e. not cloning anything)... but it's still not working.

I have also created a Page display in the View (because the Rules Action set uses the Master display) and I can successfully manually delete the nodes with VBO - it's just not working when used in a Rule/Action Set.

However, the site is already deleting User entities with an identical Views/VBO/Rules/Cron setup.

Has anyone come across this or have any idea what might be wrong? Thanks.

# Answer
Here is an "*educated*" guess:

1. Your site is configured so that anonymous users are NOT allowed (= do not have the permission) to delete nodes.
2. Cron (always) runs with user anonymous.

Up to you to confirm if bullet "1." applies, but rest assured that bullet "2." is true (in any Drupal 7 site). So if "1." indeed applies, the answer to your question (= "What am I missing") is that to get this to work you need to grant delete of nodes to anonymous users. I bet it is not going to be what you *want* to do (I wouldn't ...), but trust me, *that* is what you're missing.

And BTW, it must be that the userid you used to "*successfully manually delete the nodes with VBO*" does have the required permission.

To verify if my guess makes sense: (temporary) grant access to the VBO view to anonymous users, logout from your site, and repeat your manual attempt to delete the nodes with that VBO view again (as anonymous user). I bet it will fail with some sort of permission issue. Turn on Rules debugging (within Rules sessings) to get more details about that via the Rules logging messages shown near the top of your screen).
> 2 votes

---
Tags: 7, rules, views
---


# Question
Title: How do you get the tid from a taxonomy term page?
I've got a component on a taxonomy term page and need to use the TID in it's preprocess function.

How do I actually get the tid to save as a variable?

# Answer
You can use `menu_get_object()`:

```
$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  $tid = $term->tid;
}

```
> 1 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: hook_node_access() returning NODE_ACCESS_DENY is ignored
I am trying to block the current user from performing any action (view, update, delete) on a node. The user should only be able to view, update, delete the node being displayed if he is the owner of the node, or the owner of the node is a subuser of his (I am using the *Subuser* module).

The function below returns the correct value for the various tests I performed, but when the function returns NODE\_ACCESS\_DENY, the access isn't denied. The user can still see the node.

Is there something I am missing?

```
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if (is_object($node)) {
    if ($node->type == 'my_content_type') {
      // Determine the current uid and, if the user doesn't have the right role, deny the access
      if (is_array($account->roles) && in_array('vip', $account->roles)) {
        $current_uid  = $account->uid;
      } elseif ( is_array($account->roles) &&
                !in_array('administrator', $account->roles)) {
        return NODE_ACCESS_DENY;
      } else {
        return NODE_ACCESS_ALLOW;
      }

      // Determine the node owner.
      $node_owner = $node->uid;

      // If the node owner is the same as the current user, allow to view the node
      if ($current_uid == $node_owner) {
        return NODE_ACCESS_ALLOW;
      }

      // If not, check if the node owner is a subuser of the current vip user
      $node_owner_profile = user_load($node_owner);
      if (isset($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'])) {
        if ($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'] == $current_uid) {
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      } else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

```

# Answer
> 0 votes
There is an error in the code you are showing: A variable is initialized inside a `if()` control block, but it is used outside that block.
`$current_uid` is initialized from the following code.

```
if (is_array($account->roles) && in_array('vip', $account->roles)) {
  $current_uid  = $account->uid;
}

```

It is then used from the following code.

```
// If the node owner is the same as the current user, allow to view the node
if ($current_uid == $node_owner) {
  return NODE_ACCESS_ALLOW;
}

```

That code only works if the account object passed to the hook has the *vip* role, or if the node has been created from the anonymous user (whose ID is 0). Differently, `$current_uid` will be set to `NULL`.

Also, the code I shown in the second snippet does not do what the comment says: It allows the logged-in user to view, edit, update, and delete the node; it does not just allow the logged-in user to view the node.
The only operation that code is not allowing is creating a node of that content type, since in that case Drupal would pass the content type string in `$node` and the code is checking `$node` is an object.

To achieve what the comment is describing, the correct code is the following one.

```
if ($current_uid == $node_owner && $op == 'view') {
  return NODE_ACCESS_ALLOW;
}

```

I would rather use the following code.

```
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if (is_object($node)) {
    if ($type == 'my_content_type') {
      $current_uid = $account->uid;
      $node_owner = $node->uid;
      if (is_array($account->roles)) {
        if (!in_array('vip', $account->roles) && !in_array('administrator', $account->roles)) {
          return NODE_ACCESS_DENY;
        }
        elseif (in_array('administrator', $account->roles)) {
          return NODE_ACCESS_ALLOW;
        }
      }
      else {
        return NODE_ACCESS_IGNORE;
      }

      if ($current_uid == $node_owner && $op == 'view') {
        return NODE_ACCESS_ALLOW;
      }

      $node_owner_profile = user_load($node_owner);
      if (isset($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'])) {
        if ($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'] == $current_uid) {
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      } else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

```

Keep in mind that, when the logged-in user has the *bypass node access* permission, `hook_node_access()` implementations are not invoked. `hook_node_access()` implementations are also not invoked for page listing nodes, for example RSS feeds, or the default front page whose path is *node*.
Testing whether the value returned by a `hook_node_access()` implementation is respected by using an account with *bypass node access* permission or accessing the default front page does not have the expected result, especially in the case the expected result is that the operation is not allowed.

Instead of checking the roles of the user account, I would rather check if the user has a specific permission. `hook_node_access()` implementations are allowed to use `user_permission()`.

# Answer
> 0 votes
My final solution is in fact a workaround. I have adapted the code as necessary and used it in template\_preprocess\_node The code is adding a new variable to the $variables array - called $access\_allowed.

In node--content-type.tpl.php, I check that variable. If TRUE, I display the node. Otherwise, I redirect to the 403 page.

I know it's not as elegant as the solution using hook\_node\_access, but, for now, it works for me. If anyone finds a better solution, it would be great!

Thanks

---
Tags: 7, nodes
---


title: Pass views filter from URL

text:
# Question
Title: Pass views filter from URL
How do you pass a filter value by url in drupal 8?

On my website I have a view with a select to filter the results. This result is based on taxonomy term.

I have 4 options, All, badkamerrenovatie, elektriciteit and verwarming.

How can I set the filter by url so that I directly have a filtered list if people click on a link related to the taxonomy term. For example if people are on page elektriciteit and click trough to realisatie they see the filtered list and don't have to choose from the select.

# Answer
This can be done using Contextual Filters under Advanced Settings of View Edit Page. You can add URL parameters as filters in it. This link will help you in detail

Thanks
> 0 votes

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


# Question
Title: using hook_form_FORM_ID_alter with #states
I am trying to use checkboxes to display inline entity form elements only when the boxes are checked. However, my code doesn't seem to be working. It will hide the element, but when I toggle the checkbox, it won't display what was hidden.

Here is my code:

```
function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und'] = array(
        '#states' => array(
            'visible' => array(
                ':input[name="field_affiliation_type[und][#options]"]' => array('value' => 'Nonprofit'),
            ),
        ),
    );
}

```

Here is a screenshot of the field\_your\_nonprofit\_connections field:

And here is one for the field\_affiliation\_type field:

Based on what I have been reading in this related question (When using hook\_form\_alter to modify a content type's node add / edit form, where do I put the #states property?), I have now realized that my form is not even including the #states element at all.

* How do I add the #states element into an already existing form via hook\_form\_alter?
* And, how do I get the checkbox field to toggle the visibility?

# Answer
> 1 votes
Okay, I figured it out. Here is what I ended up with:

```
    function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und']['#states'] = array(
        'visible' => array(
            ':input[name="field_affiliation_type[und][Nonprofit]"]' => array('checked' => TRUE),
        ),
    );
}

```

This code got the element to toggle appropriately. Whew! I'm glad I finally solved it. Hopefully this question and answer will help someone else. It looks like the main thing I did wrong was having the incorrect ":input\[name." The way I finally figured it out was by looking in the HTML itself via the element inspector. I should have tried that a long time ago.

Interestingly, the #states element never did show up in my dpm($form) output. I'm not sure why that is the case, but, apparently it doesn't need to show up there, because it is working fine without it.

# Answer
> 0 votes
```
/**
* Implements hook_form_node_form_alter().
*/
function YOURMODULE_form_node_form_alter(&$form, $form_state) {
  if($form['#form_id'] == 'page_node_form') {
  //field to hide unless it's a testimonial
  $form['field_function']['#states'] = array(
    'visible' => array(
      ':input[name="field_testimonial[und][0]"]' => array('checked' =>
    TRUE),
    );
  }
}

```

---
Tags: 7, entities, javascript
---


# Question
Title: D7: Empty image upload field when adding a translation
By default when you add a translation your fields get pre-filled with the content of the original language. Is there a way to stop this behaviour for specific fields, in this case an image field. Both the node and field are set to translatable. The image field still needs to be translatable, but the original content should not get copied into the translation.

Reasoning for this is because on our project we have a `master language` which will provide default content if no localised content is found. So if we upload an image in the master language `en` and no image is uploaded for `nl` we use the image of the `en` language.

But by default the image is copied into the translation, so if the image needs to be updated for the `master language`, you then need to re-visit every translation and change the image here as well.

Practical example. I created a node in the language `English` and uploaded an image for field `field_series_image`. Now when I add a translation for `Dutch` when I hit the `node/{nid}/edit/add/en/nl` page I would like to have an empty image field and not pre-filled with the values from the source language `en`.

I have tried setting and unsetting a lot of values but none of them seemed to work. I tried to do this in the form\_alter hook like this:

```
my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'my_custom_node_form_id') {
    if (strpos($form['#action'], '/edit/add/') > 0) {
      // Logic went here.
    }
  }
}

```

Things I have tried:

* Unsetting the field in the `$form_state['build_info']['args']` array
* Unsetting the default value in the `$form` array
* Unsetting the field in the `$form['#entity']` array.
* Setting the default value to 0 (`$form['field_series_image']['nl'][0]['#default_value'] = 0`)

None of them seemed to work, maybe because the image field is a widget?

**TLDNR;** When adding a translation (so being on `node/{nid}/edit/add/en/nl`) I want to empty a image field using *some hook*. So the field is empty on the page and not saved using the values from the original node.

# Answer
> 0 votes
Figured it out after spending about a whole day of trying in the wrong hook.

Turns out you need the `hook_field_widget_form_alter` for this.

```
/**
 * Implements hook_field_widget_form_alter();
 */
function my_module_field_widget_form_alter(&$element, &$form_state, &$context) {
  $field_name = isset($element[0]['#field_name']) ? $element[0]['#field_name'] : NULL;
  if ($field_name === 'field_series_image') {
    if (strpos($form_state['complete form']['#action'], '/edit/add/') > 0) {
      // Works for single image fields (product display).
      $element[0]['#default_value']['fid'] = 0;

      // In case we have more images uploaded, unset all.
      for ($index = $element['#file_upload_delta']; $index > 0; $index--) {
        unset($element[$index]);
      }

      // Also reset the upload delta to 0.
      $element['#file_upload_delta'] = 0;
    }
  }
}

```

Code above suits our needs.

---
Tags: entities, media, i18n-l10n
---


# Question
Title: Modal form - cant set error message, and no message for required field
In a modal form, i've got e email field that is required.

* when the field is wrong, a error message is well displayed
* when the field is empty, $form\_state-\>hasAnyErrors() is true but there is no error message
* when i whant to set the error message in the form validation function, it's stay empty !

**in BuildForm :**

```
  $form['email'] = array(
            '#type' => 'email',
            '#required' => true,
            '#attributes' => [
                'placeholder' => t('Your email'),
                "data-nluid" => $nluid
            ],
        );
$form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => t('Suscribe'),
                '#ajax' => [
                    'callback' => '::submitModalFormAjax',
                    'wrapper' => 'newsletter_add_modal',
                    'event' => 'click'
                ]
            ];

```

**in validateForm**

```
 public function validateForm(array &$form, FormStateInterface $form_state) {
        $emailValue = $form_state->getValue("email");
        if (!\Drupal::service('email.validator')->isValid($emailValue) || trim($emailValue) == "") {

         $form_state->setErrorByName('email', "Email is required and must be valid");
         //binding form_state->getError($form['email']) show empty string
        }
    }

```

**in submitModalFormAjax**

```
 // If there are any form errors, re-display the form.
        if ($form_state->hasAnyErrors()) {
            $response->addCommand(new ReplaceCommand('#newsletter_add_modal', $form));
        } else {
 // else, exec success behavior

```

What am I doing wrong?

# Answer
I know i'm a bit late but the problem is that the email field is required. Required fields may not be empty, otherwise it will throw an error.

If you wish to show an error message you need a form element to catch these messages.

```
 $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

```
> 3 votes

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