# Question
Title: Get Plugin Definition methods using dependency injection
It is my first time defining a custom Plugin Type. I think that this might be a comming thing in Drupal but I was not able to find any documentation anywhere.

I want to get Plugin definition methods from controller.

I use this code to get plugin definitions:

```
$type = \Drupal::service('plugin.manager.task');
$plugin_definitions = $type->getDefinitions();

```

And that gives me an array of all definitions with Plugin id, class and name.

What I want is to get methods from the definition class.

I don't know if I should create a service for every Plugin definition, but that doesn't seem to be a good idea.

Does Drupal Core have any tools to do this?

Hope that you understand.

# Answer
> 2 votes
Create an instance and then use a method on the plugin instance, for example to execute the task, if you have such a method in the plugin class:

```
$task = \Drupal::service('plugin.manager.task')->createInstance('my_task');

$task->execute();

```

---
Tags: plugins, dependency-injection
---


# Question
Title: How to make XML sitemap to work after transfer from localhost?
My XML sitemap module was installed and enabled long time ago when I just started to make my website on WAMP/ localhost.....

Now the site is live and on real host and domain; but sitemap is still on:

`http://localhost/zen/sitemap.xml` with 1050 links....

```
Error loading stylesheet: An unknown error has occurred (805303f4)http://localhost/zen/sitemap.xsl

```

And I don't see any option to change it's path....

What should I do?

Can I somehow correct it's path or I have to reinstall?

If I reinstall, what happens with all settings?

# Answer
Did you define `base_url` in settings.php file? Try to set your current website address for `base_url`, then clear cache and run cron to generate sitemap. If this doesn't work, backup your database and run SQL query as:

```
UPDATE variable SET value='s:99:"http://example.com";' WHERE name='xmlsitemap_base_url';

```

Where the 99 is the length of your domain (including the http and all) and example.com is your domain.
> 1 votes

# Answer
You can change the path here admin/config/search/xmlsitemap/settings -\> Advanced settings
> 0 votes

# Answer
In my experience you can simply solve that by running the cron once.

When doing that via Drush you need to append the `--uri` option. As during cron runs – which is when the sitemap gets regenerated – the `$base_url` is not available. Appending `--uri` makes the `$base_url` available again.

```
drush cron --uri=http://example.com

```

I guess when triggering the cron from the admin UI the `$base_url` gets retrieved from the form.
> 0 votes

---
Tags: xml-sitemap
---


# Question
Title: Migrate content from drupal8 to drupal8 programmatically with Node::load and Node::create
Basicly I want to migrate content from one drupal8 instance to another. they are mostly identical with some small changes.

first step is to migrate the content type via `drush gen module` module and drupal-console `drupal config:export:content:type`

then i export the content type via script:

```
<?PHP
define('DRUPAL_DIR', __DIR__ . "/web");

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

use Drupal\node\Entity\Node;
use Drupal\Component\Serialization;
$serializer = \Drupal::service('serializer');

echo "Node Export Starting... \n\n";

// Nodes
$node_ids = \Drupal::entityQuery('node')->condition('type', 'content-type')->execute();
echo count($node_ids);
$single_nodes =  \Drupal\node\Entity\Node::loadMultiple($node_ids);
$data = $serializer->serialize($single_nodes, 'json');
file_put_contents('nodes.json', $data);

```

i serialize it and write it into a file.

on the new page I install the exported module to receive all fields for the content type + dependencies and so on.

if I try now to run my importer script i get serveral errors that the (exported) nodes can not be created.

```
 $json = json_decode(file_get_contents(__DIR__ . "/import/nodes.json"));
foreach ($json as $nid => $nodeImport) {
    $node = Node::create($nodeImport);
    $node->save();
}

```

Node::create() doesnt seems to accept whole exported/loaded NodeArrays nor casted arrays like `(array)$nodeImport`

Am I missing something?

# Answer
You might consider using Migrate module for this task. For pulling entities from external database use Drupal 8 migration module.
> 2 votes

---
Tags: 8, nodes, drush, migrations, console
---


# Question
Title: Why does drupal use .yml and not officially recommended .yaml
Per yaml page https://yaml.org/faq.html they recommend .yaml as file extension but I see drupal uses almost exclusively .yml, how so? And does adding .yaml to file extension even work for drupal 8 or will it be skipped?

# Answer
Drupal uses '.yml' because Symfony uses '.yml'

This was discussed in https://www.drupal.org/project/drupal/issues/2091669

I am assuming that '.yaml' would not work, but I haven't tried it. For consistency reasons it is best to stick to '.yml'.

EDIT: Looks like Symfony has started recommending '.yaml' from version 4.0. Can be seen by comparing this page https://symfony.com/doc/4.0/routing.html with the 3.4 version
> 3 votes

# Answer
because drupal 8 based on symfony 2 and .yaml is not recomended in symfony 2 , it's recomended just for version 4 of symfony 4
> -1 votes

---
Tags: 8
---


title: Deleted revisions still listed

text:
# Question
Title: Deleted revisions still listed
I started dev on Drupal 8.6.0 and have since updated to 8.6.3. I have also cleared caches, run updates and cron.

I have set up a content revisions view:

FIELDS
Content revision: Revision create time
Content revision: Revision ID
Content revision: ID

FILTER CRITERIA
Content revision: Published (= Yes)

SORT CRITERIA
Content revision: Revision create time (desc)

CONTEXTUAL FILTERS:
Content revision: ID

So I can get all the revisions for 'this' node. The view is a block, so when I place the block on a node, I get the revision id & date showing as expected.

BUT, there seem to be additional revisions in the view then listed in the revisions tab.

For my test node, I have deleted some of the revisions.
The node's revisions tab lists:
revision id:97 - 21 Nov 2018 \[the current active revision\]
revision id:96 - 16 Nov 2018
revision id:39 - 22 Oct 2018
...

But the view is listing
revision id:97 - 21 Nov 2018
revision id:96 - 16 Nov 2018
revision id:84 - 05 Nov 2018 \<- not listed on the node's revisions tab

If I take a look at the DB, I have the following:

table: node
nid:1; vid: 97;
which matches the current node / vid

table: node\_field\_revision
nid:1; vid: 97; changed: 21 Nov 2018
nid:1; vid: 96; changed: 21 Nov 2018
nid:1; vid: 84; changed: 05 Nov 2018 \<- not listed on the node's revisions tab
...

table: node\_revision
nid:1; vid: 97; time 21 Nov 2018
nid:1; vid: 96; time 16 Nov 2018
nid:1; vid: 84; time 05 Nov 2018 \<- not listed on the node's revisions tab
...

If I go to /node/1/revisions/84/view the revision shows.

How do I either remove these deleted revisions or filter them out of my view?

thank you for your help,

ice70

# Answer
I am using the diff module, pulled that apart to find it is using:

```
if ($revision->hasTranslation($langcode) && $revision->getTranslation($langcode)->isRevisionTranslationAffected())

```

modified my view to use the filter:

Content revision: Revision translation affected (= True)

The revisions pulled by the view now match the revisions shown on the node's revisions tab.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How do I use the Password Policy module?
I just installed and configured the Password Policy module, but the constraints like *password length should be minimum 8 characters* is not reflecting when an administrator user adds a new user and creates an one time login password.

The constraints/plugins provided in Drupal 8 by the *Password Policy* module aren't working in any scenario. Can anyone suggest the possible cause or the right way of using this module?

This module also doesn't modify the default recommendations on /admin/people/create.

Recommendations to make your password stronger:

* Make it at least 12 characters
* Add lowercase letters
* Add uppercase letters
* Add punctuation

# Answer
> 0 votes
Please see the reference link below which has information about how to use this module for Drupal 8

https://opensenselabs.com/blog/tech/drupal-password-policy-module

1. There might be other modules like PRLP (Password reset landing page) or other relevant password setting modules that might not be allowing the policy to be enforced.
2. You can check by uninstalling them and see if the created policy is being enforced on the default user form.

# Answer
> 0 votes
Each type of constraint is a sub-module, so in order to add a constraint for character length, for example, you need to:

1. Enable the module password\_policy\_length
2. Add a policy at /admin/config/security/password-policy
3. In #2 you will add individual constraints like password length

The module's README.md file contains pretty good instructions.

# Answer
> 0 votes
In the latest drupal 8 Password Policy recommendation and Password Strength is default functionality and it shows on every password field also it not force you to follow the recommended values.

You can overide the password policy recommendation and force password policy using this module Password Policy Configuration Module

---
Tags: 8, users
---


title: User role update report

text:
# Question
Title: User role update report
Could you let me know how to check how many users converted from one role to another for a specific period of time (for example how many changed roles from user to superuser from 01/09/2017 to 01/02/2018). How to track user role field change?

# Answer
> 2 votes
Drupal doesn't record when a role was changed for a user, at least not out-of-the-box.

A module that can help is the Role Watchdog.

Or if you have a store like Ubercart where you sell access, or have expiry dates for roles you can track role changes through available tools there. But it would be overkill to use a store just to track role changes, unless you already have a store installed.

---
Tags: 7, users
---


# Question
Title: How to check if view result is empty Twig
To check the field I use the following code:

```
{% if content.field_name|render is empty %}

```

How to check on node.twig if `{{ my_cool_view }}` result is empty? Is this generally possible in Drupal 8? Thank you for help.

# Answer
You can use twig\_tweak Module, and use `drupal_view_result` extension like:

```
{% if drupal_view_result('who_s_new', 'block_1') is empty %}

```

For more info look at this module Cheat sheet
> 15 votes

---
Tags: 8, theming
---


# Question
Title: How do I create a folder structure inside a view
I have created a view to get the all images that I have used in the website. But it returns as a bulk list. But I have saved the images according to a folder structure. How do I get the images according to a folder structure in my view.

Below is my view

Currently it returns a bulk list. How do I get the images with the folder structure?

For an example I need to get the /path1/path2/image.jpg inside a folder named path1 which contains a folder named path2.

# Answer
> 0 votes
The feature "Group by field" provides a hierarchy, but you don't have the path components out of the box.

Are you using a module that is controlling the paths that is also integrated with views, maybe File field paths? If you can get a field to display a path component you will be able to group by them, effectively getting a folder structure.

Views tree also helps, if you have the path components.

This comparison list might help: File Uploading and Managing.

If no module provides this already you'll have to create your own Views Field formatter for the file URL link field and use with some hierarchy mentioned above, or create a completely new Views Format for the File Views type that displays results in a hierarchy.

---
Tags: views, 8
---


# Question
Title: How to add an entity reference field value on Behat Test
My Behat test starts like this:

```
@api
Scenario: Testing user
Given users:
    | name | pass | mail    | status | roles  | field_lines_ref |
    | test | test | t@t.com | 1      | Tester | Line Name       |

```

field\_lines\_ref is an entity reference to a node. The user gets created but the Lines Reference field never gets populated. I also tried using the node id but it also didn't work.

One thing to note is that I already have a node created "Line Name" and I have to use that exact node because of logic in place (Based on node id).

# Answer
> 1 votes
If you have an entity reference field, you need to refer to the entity with it's name/title/label field (this applies for taxonomy terms too). Like you did it.

This code will run for your association:

```
/**
 * Entityreference field handler for Drupal 7.
 */
class EntityreferenceHandler extends AbstractHandler {

  /**
   * {@inheritdoc}
   */
  public function expand($values) {
    $entity_type = $this->fieldInfo['settings']['target_type'];
    $entity_info = entity_get_info($entity_type);
    // For users set label to username.
    if ($entity_type == 'user') {
      $entity_info['entity keys']['label'] = 'name';
    }

    $return = array();
    foreach ($values as $value) {
      $target_id = db_select($entity_info['base table'], 't')
        ->fields('t', array($entity_info['entity keys']['id']))
        ->condition('t.' . $entity_info['entity keys']['label'], $value)
        ->execute()->fetchField();
      if ($target_id) {
        $return[$this->language][] = array('target_id' => $target_id);
      }
    }
    return $return;
  }

}

```

Which also means, the first item will be tried to associate with your user, which doesn't mean, that it can be (i.e. for content type restriction). So make sure you have only one entity which named like you want to associate. Also make sure, you don't have ', ' and ' - ' in your value, because those will be converted to multi value, and if ' - ' is present than the ': ' value will be converted to `key: value` pairs. You need to say exactly the entity name which is possible to refer inside that field (but as far as I can see in the code, make sure you don't have space before and/or after the name field's value, because the query above may fail to find your entity). Also check if your field is a real field, (not like the path 'field', which is not a field) you can do it, be executing the `field_info_field_map()` command, and if you find your field machine name there, as a key, you are fine.

If all the above is fulfilled and you already has a node which can be referred by the user's `field_lines_ref` field and the node title is 'Line Name' you should be able to create your user with the reference:

```
Given users:
    | name | pass | mail    | status | roles  | field_lines_ref |
    | test | test | t@t.com | 1      | Tester | Line Name       |

```

From features file or

```
$user_obj = (object) array(
  'name' => 'test',
  'pass' => 'test',
  'mail' => 't@t.com',
  'status' => '1',
  'roles' => 'Tester',
  'field_lines_ref' => 'Line Name',
);
$user = $this->userCreate($user_obj);

```

from context object.

If these doesn't help, you may need to debug your own code (including vendor code), to see where is the problem.

# Answer
> 0 votes
Create a 'Given' function and other supporting functions in your Context.php file along this line...

```
/**
 * @Transform :user
 */
public function castUsernameToUser($user) {
    $user_loaded = user_load_by_name ( $user );
    if (!$user_loaded) {
        throw new \Exception('User was not found: ' . $user);
    }
    return $user_loaded;
}

/**
 * @Transform :field_line
 */
public function castFieldLineToNode($field_line) {
    //load your node using the name
    return $node;
}

/**
 * @Given :user has field line :field_line
 */
public function userHasFieldLine($user, $field_line) {
    $user->set ( 'field_lines_ref', $field_line);
    $user->save ();
}

```

Then after you create the user, add a step to your feature file like:

```
And "test" has field line "Line Name"

```

---
Tags: testing
---


# Question
Title: Changing proxy settings and making them effective
I'm running a Drupal training course at work. For the exercises I've set up an Ubuntu Server VM (with Unity GUI) using VirtualBox. This allows me to port the VM around between my home workstation (with no proxy) and two work locations (each behind different proxies).

Since we work in French, the exercises make extensive use of translations for the various modules installed.

Drupal accesses the Internet from the server in the following different ways:

* drush downloads of modules
* drush pm-updates
* UI verification of module updates
* UI verification of translation updates (using l10n\_update module)
* drush verification of translation updates (also using l10n, but with commands)

Every time I make a change to the VM in one location I have to update the proxy settings in the others, and I'm having great difficulty in working out how to do this. Proxy settings seem to be in three places:

* /etc/wgetrc - this changes the wget proxy settings, and it seems to work fine for drush dl and drush pm-update, but does not get taken into account by the UI or drush translation updates
* in settings.php: here it seems to be possible to set them in either Drupal-7 format, like so:

```
$conf['proxy_server'] = '10.154.61.3';
$conf['proxy_port'] = 3128;

```

or in Drupal-8 format, like so:

```
$settings['http_client_config']['proxy']['http'] = '10.154.61.3:3128';
$settings['http_client_config']['proxy']['https'] = '10.154.61.3:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

```

You can also install a module called http\_proxy, and this puts the settings directly into Drupal variables in the database (in the 'variable' table).

What's been bugging me is getting the proxy configuration changes to work. I get into situations where drush works for downloads and module updates but not for translation updates, and the UI doesn't work at all.

Of course, some of this is due to the imponderables of proxy settings (impossible to know what the settings are, and they change unpredictably - at one point for example I had to use the user agent settings).

But I have some questions I'm hoping someone might be able to answer:

1. What operations exactly do drush dl, pm-update, l10n-update, and the UI equivalents use? Are there differences that might cause one to work and others not?
2. Do both the D7 and the D8 formats in settings.php work?
3. What is the difference between using settings.php and the variables in the database?
4. How do the database variables get updated? Does the fact of changing them in settings.php also update the database?

# Answer
Summary answer to your questions:

*What operations exactly do drush dl, pm-update, l10n-update, and the UI equivalents use? Are there differences that might cause one to work and others not?*

\** drush dl: donwload a module or theme pm-update: update Core l10n-update: update translation \**

*Do both the D7 and the D8 formats in settings.php work?*

**No there are Some differences between D7 and D8**

*What is the difference between using settings.php and the variables in the database?*

**In Drupal 7 there is not any different. The settings store in DB. But in Drupal 8 None on Setting Configuration store in Database So there is no way to change them via DB**

*How do the database variables get updated? Does the fact of changing them in settings.php also update the database?*

**Yes, When you changed a config in settings.php the equivalence variable in database got updated but in Drupal 8 There is no config or variable in DB to store settins.pp configuration.**

**you can get settings in Drupal 8 by `Settings::get(YOUR_CONFING_NAME)`.**
> 0 votes

---
Tags: proxies
---


# Question
Title: Should configuration synchronization be used only between cloned sites?
Can it be used to get configuration from one site to another site which is not a clone.

eg: SiteX is installed using

> composer create-project drupal-composer/drupal-project:8.x-dev SiteX

and also another site SiteY using

> composer create-project drupal-composer/drupal-project:8.x-dev SiteY

I did some changes to SiteX( New content type with few fields). I did **drush cex** to get the configuration and imported in SiteY config/sync folder and did **drush cim**. I did not see the new content type in SiteY. Based on some other articles, i tried

> drush cget system.site uuid in SiteX
>
> drush cset system.site uuid # in SiteY
>
> drush cim # in SiteY

Still no luck. I don't see the new content type.

Does this configuration synchronization, only work in cloned sites ??.

My whole requirement is to export the configuration from one environment is another with out moving content.

Note: We have GIT, local, Test and Prod are the three environments. Currently we are still in local stage. So a full config export is possible for higher environments. DB dump( export and import ) is not possible as content also gets migrated. Please correct me if I am wrong.

# Answer
> 1 votes
Configuration can be used to sync between how many sites you want. All you have to ensure is that they have the same site UUID to be set and all the same dependencies (modules, libraries) in the same version to be existent.

You also could install a site from the copied config from another site.

```
drush si minimal --existing-config

```

---

What you are describing should be a pretty normal deployment circle. Code and config always goes upstream (from local to dev to stage to prod) whereas the database and the content in it always goes downstream (database dump from prod to be imported on stage, dev and local).

During releases and merges you then ensure that a set of certain commands be run to keep everything consistent.

```
git pull
composer install
drush updb
drush cim
drush cron
drush cr

```

@see Order of drush commands for automated deployment?

---
Tags: 8, importing-exporting, configuration
---


# Question
Title: Get prefix and suffix from a Number field
So here is my issue;

I got a price in a Number (decimal) field in a node, I need to process this number in some ways depending on users interactions then send it back (via an ajax request) as an integer, but also formatted with proper currency sign which is stored in the fields prefix/suffix settings.

I should mention that this should also work with translations of the price and its prefix/suffixes.

I get the price now this way;

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load($node_id);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$translated_node = $node->getTranslation($language);
$price = $translated_node->get('field_price')->getValue()[0]['value'];`

```

So now I want to constuct a formated variable with the translated prefix/suffix depending on which language is curretly selected.

# Answer
> 2 votes
After some trial and error and cache problems I found the answer to this myself. Here is how I got the prefix/suffix;

```
$prefix = $translated_node->get('field_price')->getSettings()['prefix'];
$suffix = $translated_node->get('field_price')->getSettings()['suffix'];

```

---
Tags: 8
---


# Question
Title: How to combine two batch operations for views data export into one?
I have been using a custom module that was posted here:

https://www.drupal.org/node/1875456

I slightly modified this module and created two copies of it, as I have two views and planning to add third one but it currently doesn't work properly so let me explain:

dvm\_reports module#1 for Denmark

```
function dvm_reports_views_data_export_batch_alter(&$batch, &$batch_redirect) {
  $view = views_get_view($batch['produkty_denmark_xml']);

  // Add in another operation that will store the file on the server in a location
  // of our choosing.
  $batch['operations'][] = array(
    'dvm_reports_views_data_export_batch_finish', array($batch['eid']),
  );
}

function dvm_reports_views_data_export_batch_finish($eid) {
  $export = views_data_export_get($eid);
  $view = views_data_export_view_retrieve($eid);
  $view->set_display($export->view_display_id);
  $view->display_handler->batched_execution_state = $export;
  $view->display_handler->remove_index();

  // Get path to temp file
  $temp_file = $view->display_handler->outputfile_path();
  file_unmanaged_copy($temp_file, 'public://denmark.xml', FILE_EXISTS_REPLACE);
}

```

It starts to generate the file correctly when I go to domain.com/denmark

dvm\_reports module#2 for Sweden (I copied the denmark module and renamed it from "dvm\_reports" to "dvm\_reports2")

```

function dvm_reports2_views_data_export_batch_alter(&$batch, &$batch_redirect) {
  $view = views_get_view($batch['produkty_json']);

  // Add in another operation that will store the file on the server in a location
  // of our choosing.
  $batch['operations'][] = array(
    'dvm_reports2_views_data_export_batch_finish', array($batch['eid']),
  );
}

function dvm_reports2_views_data_export_batch_finish($eid) {
  $export = views_data_export_get($eid);
  $view = views_data_export_view_retrieve($eid);
  $view->set_display($export->view_display_id);
  $view->display_handler->batched_execution_state = $export;
  $view->display_handler->remove_index();

  // Get path to temp file
  $temp_file = $view->display_handler->outputfile_path();
  file_unmanaged_copy($temp_file, 'public://produkty.json', FILE_EXISTS_REPLACE);
}

```

it starts to generate the file correctly when I go to domain.com/sweden

**Problems:**

I would like to combine those two modules into one but I don't know how to do it.

Please advice if you can

# Answer
> 0 votes
I suppose you should be able to merge them into one module by first checking if the view is available in the batch (stop otherwise) and provide the filename within this check. Code has not been tested though.

```
function dvm_reports_views_data_export_batch_alter(&$batch, &$batch_redirect) {
  // Check for Denmark.
  if ($view = views_get_view($batch['produkty_denmark_xml'])) {
    $filename = 'denmark.xml';
  }
  // Check for Sweden.
  elseif ($view = views_get_view($batch['produkty_json'])) {
     $filename = 'producty.json';
  }
  // Check for Norway.
  // ... Code goes here

  // Leave if nothing was found.
  else return;

  // Proceed if something was found.

  // Add in another operation that will store the file on the server in a location
  // of our choosing.
  $batch['operations'][] = array(
    'dvm_reports_views_data_export_batch_finish', array($batch['eid'], $filename),
  );
}

function dvm_reports_views_data_export_batch_finish($eid, $filename) {
  $export = views_data_export_get($eid);
  $view = views_data_export_view_retrieve($eid);
  $view->set_display($export->view_display_id);
  $view->display_handler->batched_execution_state = $export;
  $view->display_handler->remove_index();

  // Get path to temp file
  $temp_file = $view->display_handler->outputfile_path();
  file_unmanaged_copy($temp_file, 'public://'. $filename, FILE_EXISTS_REPLACE);
}

```

There might however be a bigger problem with your module. I cannot see your hook menu implementation, but if anonymous users are also able to access `domain.com/denmark` they could DDoS your site. Prevent that.

# Answer
> 0 votes
try this:

```
function dvm_reports_views_data_export_batch_alter(&$batch, &$batch_redirect) {
  $view = views_get_view($batch['view_name']);

  drupal_set_message($batch['view_name']);

  // Add in another operation that will store the file on the server in a location
  // of our choosing.
  if($batch['view_name']== "produkty_denmark_xml"){

    $batch['operations'][] = array(
    'dvm_reports_views_data_export_batch_finish', array($batch['eid']),
    );
  }else if($batch['view_name']== "produkty_json"){

    $batch['operations'][] = array(
    'dvm_reports_views_data_export_batch_finish2', array($batch['eid']),
    );
  }
}

function dvm_reports_views_data_export_batch_finish($eid) {
  $export = views_data_export_get($eid);
  $view = views_data_export_view_retrieve($eid);
  $view->set_display($export->view_display_id);
  $view->display_handler->batched_execution_state = $export;
  $view->display_handler->remove_index();

  // Get path to temp file
  $temp_file = $view->display_handler->outputfile_path();
  file_unmanaged_copy($temp_file, 'public://denmark.xml', FILE_EXISTS_REPLACE);
}
function dvm_reports_views_data_export_batch_finish2($eid) {
  $export = views_data_export_get($eid);
  $view = views_data_export_view_retrieve($eid);
  $view->set_display($export->view_display_id);
  $view->display_handler->batched_execution_state = $export;
  $view->display_handler->remove_index();

  // Get path to temp file
  $temp_file = $view->display_handler->outputfile_path();
  file_unmanaged_copy($temp_file, 'public://produkty.json', FILE_EXISTS_REPLACE);
}

```

---
Tags: 7, views
---


title: How to use the Front Page module

text:
# Question
Title: How to use the Front Page module
I am currently trying to make my front page viewable by anonymous users, I am using the Front Page module to do this in Drupal 8, however I am unsure how to use it?

# Answer
> 1 votes
The default front page Drupal uses is a view which lists several pieces of content (nodes). This view is by default visisble for authenticated and anonymous users and you do not require a module for it.

The front page module is only useful if you want to show a different page to users depending on their role. For instance you can configure the front page anonymous user to be `/anon-front` and for authenticated user `/auth-front`. It does not do anything with permissions but simply redirects the user when they click the home link.

In your case it seems that anonymous users are not able to see the default front page. There are two likely reasons for this:

* All your nodes are private and anonymous users are not allowed to view any nodes.
* The views configuration has been altered and the view is only visible for authenticated users.

You do not need to use the front page module (at least not the way the question is currently written), but without further information we cannot help you debug either.

# Answer
> 0 votes
If I recall correctly, you can go to the configuration page, and in the anonymous users section, you can choose 'alias'.

-- edit --

I just installed the D8 version of the module. It's a little different from D7, probably because it's still an alpha version and incomplete.

Go to Admin -\> Configuration -\> Front Page -\> settings

Under "Front page for anonymous user", check 'enable', and enter the path to the page you want anonymous users to see.

I don't know if it will work or not though, since it's an alpha version, it may not be ready for usage.

---
Tags: 8
---


# Question
Title: Handling directory error with submitted patch
1. Drupal 8.x
2. MAC OSX +
3. Vagrant 2.2.0

How can I trace/define a directory error while trying to apply a Drupal.org patch?

I have a patch submitted to a Drupal project module, and while trying to apply the patch locally I get this error:

```
Checking patch src/Form/UserMenuAvatarConfigurationForm.php...
error: src/Form/UserMenuAvatarConfigurationForm.php: already exists in
working directory
Checking patch src/form/UserMenuAvatarConfigurationForm.php...

```

I am applying the patch via cweagans/composer-patches and `composer install` in the Drupal root directory after `vagrant ssh`. (`git apply -v [patchname.patch]` returns the same error)

The patch is trying to do two things, change a directory name from `form` to `Form` (case change), as well as update some code in one of the modules files (src/form/UserMenuAvatarConfigurationForm.php).

Issue link if needed: https://www.drupal.org/project/user\_menu\_avatar/issues/3024739

---

**composer.json**:

```
    {
        "name": "drupal-composer/drupal-project",
        "description": "Project template for Drupal 8 projects with composer",
        "type": "project",
        "license": "GPL-2.0-or-later",
        "authors": [
            {
                "name": "",
                "role": ""
            }
        ],
        "repositories": [
            {
                "type": "composer",
                "url": "https://packages.drupal.org/8"
            }
        ],
        "require": {
            "php": ">=5.6",
            "composer/installers": "^1.2",
            "cweagans/composer-patches": "^1.6",
            "drupal-composer/drupal-scaffold": "^2.5",
            "drupal/console": "^1.0.2",
            "drupal/core": "^8.6.0",
            "drupal/devel": "^1.2",
            "drupal/user_menu_avatar": "^2.0",
            "drush/drush": "^9.0.0",
            "vlucas/phpdotenv": "^2.4",
            "webflo/drupal-finder": "^1.0.0",
            "webmozart/path-util": "^2.3",
            "zaporylie/composer-drupal-optimizations": "^1.0"
        },
        "require-dev": {
            "webflo/drupal-core-require-dev": "^8.6.0"
        },
        "conflict": {
            "drupal/drupal": "*"
        },
        "minimum-stability": "dev",
        "prefer-stable": true,
        "config": {
            "sort-packages": true
        },
        "autoload": {
            "classmap": [
                "scripts/composer/ScriptHandler.php"
            ],
            "files": ["load.environment.php"]
        },
        "scripts": {
            "pre-install-cmd": [
                "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
            ],
            "pre-update-cmd": [
                "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
            ],
            "post-install-cmd": [
                "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
            ],
            "post-update-cmd": [
                "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
            ]
        },
        "extra": {
            "composer-exit-on-patch-failure": true,
            "patches-file": "./composer.patches.json",
            "patchLevel": {
                "drupal/core": "-p2"
            },
            "installer-paths": {
                "web/core": ["type:drupal-core"],
                "web/libraries/{$name}": ["type:drupal-library"],
                "web/modules/contrib/{$name}": ["type:drupal-module"],
                "web/profiles/contrib/{$name}": ["type:drupal-profile"],
                "web/themes/contrib/{$name}": ["type:drupal-theme"],
                "drush/Commands/{$name}": ["type:drupal-drush"]
            },
            "drupal-scaffold": {
                "initial": {
                    ".editorconfig": "../.editorconfig",
                    ".gitattributes": "../.gitattributes"
                }
            }
        }
    }

```

**composer.patches.json**:

```
{
  "patches": {
    "drupal/user_menu_avatar": {
      "Config form page returns WSOD in some instances": "https://www.drupal.org/files/issues/2019-01-09/user_menu_avatar-settings_form-3024739-2.patch"
    }
  }
}

```

---

`composer install --verbose`:

```
    vagrant@vanilla:/var/www/drupal$ composer install --verbose
    Gathering patches from patch file.
    Removing package drupal/user_menu_avatar so that it can be re-installed and re-patched.
      - Removing drupal/user_menu_avatar (2.0.0)
    Deleting web/modules/contrib/user_menu_avatar - deleted
    > pre-install-cmd: DrupalProject\composer\ScriptHandler::checkComposerVersion
    Loading composer repositories with package information
    Installing dependencies (including require-dev) from lock file
    Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.
    Dependency resolution completed in 0.002 seconds
    Analyzed 328 packages to resolve dependencies
    Analyzed 1219 rules to resolve dependencies
    Package operations: 1 install, 0 updates, 0 removals
    Installs: drupal/user_menu_avatar:2.0.0
    Gathering patches from patch file.
    Gathering patches for dependencies. This might take a minute.
    Found 1 patches for drupal/user_menu_avatar.
      - Installing drupal/user_menu_avatar (2.0.0): Loading from cache
     Extracting archive  - Applying patches for drupal/user_menu_avatar
        https://www.drupal.org/files/issues/2019-01-09/user_menu_avatar-settings_form-3024739-2.patch (Config form page returns WSOD in some instances)
    patch '-p1' --no-backup-if-mismatch -d 'web/modules/contrib/user_menu_avatar' < '/tmp/5c5da64c3c199.patch'
    The next patch would create the file src/Form/UserMenuAvatarConfigurationForm.php,
    which already exists!
      Assume -R? [n]

    Apply anyway? [n]

    Skipping patch.

    1 out of 1 hunk ignored

    patching file src/form/UserMenuAvatarConfigurationForm.php

    patch '-p0' --no-backup-if-mismatch -d 'web/modules/contrib/user_menu_avatar' < '/tmp/5c5da64c3c199.patch'
    patching file b/src/Form/UserMenuAvatarConfigurationForm.php

    patching file b/src/form/UserMenuAvatarConfigurationForm.php

    Reversed (or previously applied) patch detected!
      Assume -R? [n]

    Apply anyway? [n]

    Skipping patch.

    1 out of 1 hunk ignored
     -- saving rejects to file b/src/form/UserMenuAvatarConfigurationForm.php.rej

    patch '-p2' --no-backup-if-mismatch -d 'web/modules/contrib/user_menu_avatar' < '/tmp/5c5da64c3c199.patch'
    patching file Form/UserMenuAvatarConfigurationForm.php

    patching file form/UserMenuAvatarConfigurationForm.php

    Reversed (or previously applied) patch detected!
      Assume -R? [n]

    Apply anyway? [n]

    Skipping patch.

    1 out of 1 hunk ignored
     -- saving rejects to file form/UserMenuAvatarConfigurationForm.php.rej

    patch '-p4' --no-backup-if-mismatch -d 'web/modules/contrib/user_menu_avatar' < '/tmp/5c5da64c3c199.patch'
    can't find file to patch at input line 6

    Perhaps you used the wrong -p or --strip option?

    The text leading up to this was:
    --------------------------

    |diff --git a/src/Form/UserMenuAvatarConfigurationForm.php b/src/Form/UserMenuAvatarConfigurationForm.php
    |new file mode 100644
    |index 0000000..19e3434
    |--- /dev/null
    |+++ b/src/Form/UserMenuAvatarConfigurationForm.php
    --------------------------

    File to patch:

    Skip this patch? [y]

    Skipping patch.

    1 out of 1 hunk ignored

    can't find file to patch at input line 219

    Perhaps you used the wrong -p or --strip option?

    The text leading up to this was:
    --------------------------

    |diff --git a/src/form/UserMenuAvatarConfigurationForm.php b/src/form/UserMenuAvatarConfigurationForm.php
    |index c019638..19e3434 100644
    |--- a/src/form/UserMenuAvatarConfigurationForm.php
    |+++ b/src/form/UserMenuAvatarConfigurationForm.php
    --------------------------

    File to patch:

    Skip this patch? [y]

    Skipping patch.

    1 out of 1 hunk ignored

       Could not apply patch! Skipping. The error was: Cannot apply patch https://www.drupal.org/files/issues/2019-01-09/user_menu_avatar-settings_form-3024739-2.patch

      [Exception]
      Cannot apply patch Config form page returns WSOD in some instances (https://www.drupal.org/files/issues/2019-01-09/user_menu_avatar-settings_form-3024739-2.patch)!

```

**Note: I am now doing this work on a brand new machine. New OS, new installs of composer, Drupal, git, etc...*

**Note: I have had success downloading the patch as a file in the Drupal root directory, updating my `composer.patches.json`, and running composer install. Then, I do not get the directory issue. However the directory does not get changed from `form` to `Form`. Though the patch completes and updates the module file contents.*

# Answer
> 1 votes
Don't apply patches like that anymore. Let Composer handle this. I hope you already are managing your site with Composer. Then you need to require `cweagans/composer-patches` first.

```
composer require cweagans/composer-patches

```

And then it's just a new `"patches"` array in your `composer.json` providing patches like so:

```
    "patches": {
        "drupal/user_menu_avatar": {
            "Config form page do not work": "https://www.drupal.org/files/issues/2019-01-09/user_menu_avatar-settings_form-3024739-2.patch"
        },
        "drupal/foobar": {
            "Lorem ipsum dolor sit amet": "https://www.drupal.org/files/issues/2020-02-02/1234567.patch"
        }
    }

```

Finally run `composer install` again, done.

---
Tags: 8, version-control
---


# Question
Title: Theme preprocess for module's template variables using dynamic path
I am doing templating for a module that adds a block in the module's folder so that the template can be there, and it may be overridden in the theme if desired. I want the module to support different "sources" (but only one will be active/used at a time), which may each have a separate template and variable preprocessing. I have hook\_theme() working, and the template works. But the .vars.php file I have contains the preprocess function, and it doesn't get called.

Here is a basic example of what I have:

**/MODULE.module**

```
function MODULE_theme($existing, $type, $theme, $path) {
  $source = '';
  switch ($source) {
    case 'SRC_A':
      $path .= '/sources/SRC_A/theme';
    default:
      $source = 'default';
      $path .= '/theme';
  }

  return array(
    'MODULE_block' => array(
      'path' => $path,
      'variables' => array('data' => array(), 'source' => $source),
      'template' => 'MODULE-block',
    )
  );
}

```

**/MODULE/sources/SRC\_A/theme/MODULE-block.tpl.php**

```
(contains template HTML with references to PHP variables)

```

**/MODULE/sources/SRC\_A/theme/MODULE-block.vars.php**

```
/**
 * Implements template_preprocess_HOOK() for theme_MODULE_block().
 */
function template_preprocess_MODULE_block(&$vars) {
  // Add variables before they get to the template file.
  $vars['some_key'] = 'some_value';
}

```

I originally was trying to modify the `$template` value in hook\_theme() to `MODULE-block--SRC-A`, but I decided that didn't matter, and if only one template is active at once I should just call them all `MODULE-block.tpl.php` regardless of the source, since they are all in different folders.

The template works, and adding a template in my theme will correctly override it. But the .vars.php file with the preprocess function does not seem to do anything unless it is in my actual theme and is `THEME_preprocess_MODULE_block` instead.

I'm still pretty new to this, but I looked at a lot of pages online, and there aren't any similar examples in my code base that have a module-specific .vars.php file that is located in the module's folder rather than in the theme.

I do not know what I am doing wrong. Any ideas?

# Answer
I figured it out. There was already a preprocess function with the name `template_preprocess_MODULE_block` in the module file. Declaring the same function a second time has no effect.
> 0 votes

---
Tags: 7, theming, hooks
---


# Question
Title: Does Entity Autocomplete has database leak?
Lately in one of our prod database the "key\_value" table became 2.4GB large. When I took a closer look I could see that there is around 200 000 records in it, and 90% of them are `entity_autocomplete` collection. Then I searched the entity reference module where does it operate with the `keyValue` service and I found the following:

```
// \Drupal\Core\Entity\Element\EntityAutocomplete:129
   $selection_settings = isset($element['#selection_settings']) ? $element['#selection_settings'] : [];
    $data = serialize($selection_settings) . $element['#target_type'] . $element['#selection_handler'];
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    $key_value_storage = \Drupal::keyValue('entity_autocomplete');
    if (!$key_value_storage->has($selection_settings_key)) {
      $key_value_storage->set($selection_settings_key, $selection_settings);
    }

```

The `$selection_settings` may contain the host entity as well (it's because of the self reference feature). This means based on the code: whenever you have a new entity or the entity updated your `$selection_settings_key` will always be different. Also it's added to the key-value table without expiration date which will end up as a permanent out of date record (after the entity changed / field config anyhow) in your key-value table. Also because it's serializing the whole entity the record itself can be quite big (talking about 10-12 KB).

Is this a bug or am I missing something?

# Answer
> 0 votes
Known bug: https://www.drupal.org/project/drupal/issues/2826826#comment-12376276

> As mentioned in IRC, the problem with adding even just the entity id/UUID to those options is that we create entity * entity reference key value entries.
>
> The key is based on the hash, so an ID/UUID in there results in a different hash for every entity. At the very least, we would need to switch to an expirable key value store, so we can clean them up but it is still a non-trivial overhead that is being added.

https://www.drupal.org/project/drupal/issues/2826826#comment-12644652

Seems to fix it for me:

```
    // Don't serialise the entity, it will be added explicitly afterwards.
if (isset($selection_settings['entity']) && ($selection_settings['entity'] instanceof EntityInterface)) {
  $element['#autocomplete_query_parameters']['host_entity_type'] = $selection_settings['entity']->getEntityTypeId();
  $element['#autocomplete_query_parameters']['host_entity_id'] = $selection_settings['entity']->id();
  unset($selection_settings['entity']);
}

```

---
Tags: 8, entities, forms
---


# Question
Title: How to add country terms and languge field selected language in url?
I need a functionality in which I can select multiple language for a country.

I have added the countries as taxonomy terms and in which I added language as a field, in which SUPPORTED LANGUAGES as multiselect.

I need my url as /term-name/supported-language-1 /term-name/supported-language-2

How to achieve this in Drupal 8?

# Answer
This can be done by **Domain Access** and **Country Path module**.

For Path pattern we need to choose both URL and Country Path Language Handler URL in `admin->Language->Selection and Detection`
> 0 votes

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


title: Error consolidation/annotated-command

text:
# Question
Title: Error consolidation/annotated-command
Trying to install Drush using Composer, i get an error concerning consolidation/annotated-command. What does it mean "locked at 2.0.3" and "requires 2.8.1"?

This is the error:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1

- Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
- Conclusion: remove consolidation/annotated-command 2.0.3
- Conclusion: don't install consolidation/annotated-command 2.0.3
- drush/drush dev-master requires consolidation/annotated-command ^2.8.1 -> satisfiable by consolidation/annotated-command[2.8.1, 2.8.2].
- Can only install one of: consolidation/annotated-command[2.8.1, 2.0.3].
- Can only install one of: consolidation/annotated-command[2.8.2, 2.0.3].
- Installation request for consolidation/annotated-command (locked at 2.0.3) -> satisfiable by consolidation/annotated-command[2.0.3].

Installation failed, reverting ./composer.json to its original content.

```

# Answer
I get this error after changing the minimum version of drush/drush to `~9.0` in my `composer.json` and running `composer update drush/drush` afterwards.

I solved it by just executing `composer require drush/drush:~9.0` which lead to the error message `drush/drush 9.5.x-dev requires symfony/config ^3.4`, so I had to execute `composer require symfony/config:^3.4` before `composer require drush/drush:~9.0` could be finished successful.

Don't know if this is the only way or best practice to solve such a dependency conflict but in short this worked for me:

1. `composer require symfony/config:^3.4`
2. `composer require drush/drush:~9.0`
> 1 votes

---
Tags: drush, composer
---


# Question
Title: How are values passed from the database to the templating system?
I haven't quite figured out how Drupal passes the values from the database or the back-end to the theme variables in the template.

Which function does it use to disperse the variables to the corresponding template?

# Answer
> 1 votes
The function that does the job is `theme_render_template()`, which contains the following code.

```
  // Extract the variables to a local namespace
  extract($variables, EXTR_SKIP);

  // Start output buffering
  ob_start();

  // Include the template file
  include DRUPAL_ROOT . '/' . $template_file;

  // End buffering and return its contents
  return ob_get_clean();

```

The function is called from `theme()`, which uses the following code.

```
// Default render function and extension.
$render_function = 'theme_render_template';
$extension = '.tpl.php';

// The theme engine may use a different extension and a different renderer.
global $theme_engine;
if (isset($theme_engine)) {
  if ($info['type'] != 'module') {
    if (function_exists($theme_engine . '_render_template')) {
      $render_function = $theme_engine . '_render_template';
    }
    $extension_function = $theme_engine . '_extension';
    if (function_exists($extension_function)) {
      $extension = $extension_function();
    }
  }
}

// In some cases, a template implementation may not have had
// template_preprocess() run (for example, if the default implementation is
// a function, but a template overrides that default implementation). In
// these cases, a template should still be able to expect to have access to
// the variables provided by template_preprocess(), so we add them here if
// they don't already exist. We don't want to run template_preprocess()
// twice (it would be inefficient and mess up zebra striping), so we use the
// 'directory' variable to determine if it has already run, which while not
// completely intuitive, is reasonably safe, and allows us to save on the
// overhead of adding some new variable to track that.
if (!isset($variables['directory'])) {
  $default_template_variables = array();
  template_preprocess($default_template_variables, $hook);
  $variables += $default_template_variables;
}

// Render the output using the template file.
$template_file = $info['template'] . $extension;
if (isset($info['path'])) {
  $template_file = $info['path'] . '/' . $template_file;
}
if (variable_get('theme_debug', FALSE)) {
  $output = _theme_render_template_debug($render_function, $template_file, $variables, $extension);
}
else {
  $output = $render_function($template_file, $variables);
}

```

---
Tags: 7
---


# Question
Title: How to display custom fields of taxonomy in field twig
In my content type for Event, I have an entity reference called Speakers which refers to a taxonomy called Team Members. It's set to multiple so I can say which speakers belong to my event. On the event detail page, I want to list the speakers out with all of their fields.

I have a field hook called field-field-speakers.html which lists all of the speakers. I can't seem to get any of the fields within the taxonomy. (ex: item.content.field\_job\_title ). It doesn't display any content.

```
  {% for item in items %}

        <div class="member">

            <div class="name-box">
                <div class="name">

                 {{ item.content }}</div>
                <div class="position">{{ item.content.field_job_title }}</div>

            </div>
        </div>

  {% endfor %}

```

How do I do this? I think the answer might be in a View but not sure how to map it dynamically based on which event I am in.

# Answer
You can use `item.content['#options'].entity.field_job_title.value` to get the value of the `job_title`field value, I don't know if this is the best way to do it.
So your code will be something like:

```
{% for item in items %}

  <div class="member">
    <div class="name-box">
      <div class="name">
        {{ item.content }}</div>
      <div class="position">{{ item.content['#options'].entity.field_job_title.value }}</div>
    </div>
  </div>

{% endfor %}

```
> 0 votes

---
Tags: theming, taxonomy-terms
---


# Question
Title: Change input value on click when there is more than one paragraph
There are two fields on my paragraph.

1. A number field
2. A text field

I want to change the value of the text field when I click on the number field.

Here's my script so far which is only good on the first paragraph because of `field_my_content_paragraph_field[0]`:

```
/**
 * @file
 * Javascript behaviors.
 */

(function ($, Drupal) {

  "use strict";

  /**
   * Handle paragraph fields on the node edit form.
   */
  Drupal.behaviors.myBehavior = {

    attach: function (context) {
      $('input[name="field_my_content_paragraph_field[0][subform][field_my_number_integer_field][0][value]"]', context).on('click', function () {
        var myNumberFieldValue = $('input[name="field_my_content_paragraph_field[0][subform][field_my_number_integer_field][0][value]"]').val();
        var myInputTextFieldValue = $('input[name="field_my_content_paragraph_field[0][subform][field_my_input_text_field][0][value]"]');

        switch (myNumberFieldValue) {
          case '1':
            myInputTextFieldValue.val('A');
            break;
          case '2':
            myInputTextFieldValue.val('B');
            break;
          case '3':
            myInputTextFieldValue.val('C');
            break;
        }
      });
    }
  };

})(jQuery, Drupal);

```

When there is a second paragraph on the node, the field names for the second paragraph are:

```
name="field_my_content_paragraph_field[1][subform][field_my_number_integer_field][0][value]"

name="field_my_content_paragraph_field[1][subform][field_my_input_text_field][0][value]"

```

How can I loop through the paragraphs, (or is it the DOM at this point?) so the text field value of the paragraph I'm in is changed on click?

# Answer
I need to loop through the paragraphs with an `.each()` like so:

```
/**
 * @file
 * Javascript behaviors.
 */

(function ($, Drupal) {

  "use strict";

  /**
   * Handle paragraph fields on the node edit form.
   */
  Drupal.behaviors.myBehavior = {

    attach: function (context) {
      $("input[name$='[subform][field_my_number_integer_field][0][value]']").each(function (i) {

        $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_number_integer_field][0][value]"]', context).on('click', function () {

          var myNumberFieldValue = $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_number_integer_field][0][value]"]').val();
          var myInputTextFieldValue = $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_input_text_field][0][value]"]');

          switch (myNumberFieldValue) {
            case '1':
              myInputTextFieldValue.val('A');
              break;
            case '2':
              myInputTextFieldValue.val('B');
              break;
            case '3':
              myInputTextFieldValue.val('C');
              break;
          }
        });
      });
    }
  };

})(jQuery, Drupal);

```

Which solves the problem.
> 0 votes

---
Tags: 8, javascript, paragraphs
---


# Question
Title: Is it possible to set a role specific value for "allow_insecure_uploads?"
I want to override the value for "allow\_insecure\_uploads" which is in system.file config, but only for specific roles. Am I going to need to do this in a module / does one already exist?

# Answer
Module suggestions are usually frowned upon on DA, but regardless the answer is yes; role-specific config values are possible via the D8 config override system.

The Drupal 8 docs has a section on the config override system with a relevant example in the **Providing overrides from modules** section. After you've declared the override class in your module's `.services.yml` & created the override PHP class, you'll do something like this in the `loadOverrides()` method:

```
 public function loadOverrides($names) {
    $overrides = array();
    // @TODO: define a hasRole($role) class method that checks Drupal::currentUser() for a given role
    $has_role = $this->hasRole('my_role');
    if (in_array('system.file', $names) && $has_role) {
      $overrides['system.file'] = ['allow_insecure_uploads' => TRUE];
    }
    return $overrides;
 }

```
> 0 votes

---
Tags: 8, users, configuration
---


# Question
Title: Composer won't update Drupal Core, can't determine what is stopping it
I am trying to update Drupal Core 8.6.3 to 8.6.5 (which is the latest Core update at time of writing this).

Using this CLI Composer command:

```
composer update drupal/core --with-dependencies

```

completes the whole process without errors.

But after clearing Drupal's cache and checking Status Report, it still shows the previous version (8.6.3).

I'm assuming a dependency may be blocking the Core update.

To test this I ran this CLI Composer command:

```
composer prohibits

```

and received this error:

```
[Symfony\Component\Console\Exception\RuntimeException]
  Not enough arguments (missing: "package").

```

After searching a few forums I could not find a definite explanation of that error's meaning or how to address it.

**UPDATE - As per my answer below, I found a solution which was:**

I noticed in a few threads that this inclusion kept being referred to as a potential Core update issue:

```
webflo/drupal-core-require-dev

```

So I checked my composer.json require list and it was there, specifying the earlier Core version:

```
    "require-dev": {
    "webflo/drupal-core-require-dev": "8.6.3"
},

```

To correct this, I ran this CLI Composer Command:

```
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

```

After clearing cache (drush cr) I checked back on my composer.json and the require had changed to:

```
    "require-dev": {
    "webflo/drupal-core-require-dev": "^8.6.0"
},

```

This then triggered a Status Report Warning that 2 Tables required update. To fix this I ran this CLI Command:

```
drush updatedb

```

I then successfully run this CLI Composer command:

```
composer update drupal/core --with-dependencies

```

After another cache clear, I checked Drupal's Status Report which showed the update to Core had worked. I was happy with this so (as I was in maintanenace mode during this time) I then used this CLI command to turn off maintenance mode:

```
drush sset system.maintenance_mode 0

```

And all is well and working correctly.

# Answer
I found some other threads that highlighted webflo/drupal-core-require-dev as being an issue, In CLI I ran

```
composer show

```

This showed me that webflo/drupal-core-require-dev was set to 8.6.3

So I ran update in CLI:

```
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

```

This updated the require version to 8.6.5. Upon checking Drupal Status Report it also triggered a warning requiring Database updates, so I ran:

```
drush updatedb

```

and approved"yes" to the 2 updates.

This removed the Database error from Status Report and I then ran the core update CLI again:

```
composer update drupal/core --with-dependencies

```

This time it worked, so I cleared cache and turned off maintenance mode:

```
drush cr
drush sset system.maintenance_mode 0

```

and the Status Report is now clear of errors and warnings.
> 1 votes

---
Tags: composer
---


# Question
Title: How do I programmatically update pathauto paths for an entity?
If an entity has opted into auto generated paths, you could simply re-save the entity. However saving an entity is particularly inefficient, and the path/routing system runs outside of the entity system.

How do I update a path for an entity without saving the entity?

# Answer
> 3 votes
You could use the `pathauto.generator` service provided by Pathauto:

```
\Drupal::service('pathauto.generator')->updateEntityAlias($entity, 'update');

```

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


# Question
Title: When adding media to content, how can I search for the media by tag or term?
In Drupal 8, I created a new Media type "PDF Files." I have imported almost 30,000 of them, each complete with Title (Name), file, and the taxonomy that categorizes them.

On the content type (Let's say the default Article, for example) I've added an entity reference field and the ability to locate a file via the Entity File Browser project (https://www.drupal.org/project/entity\_browser).

This is working well enough, but it searched via the Name field only by default.

How can I accomplish the same thing but searching by comma separated tags?

So, each file has a tag structure TAG1, TAG2, TAG3.

In the search field for the file while in the content type, if I type in TAG1, TAG3 then all the files with that combination of tags should come up.

Before I dive into a custom script or extending the entity browser, wanted to make sure this isn't something simple I'm overlooking. (Just now getting into D8 after a long D7 background).

UPDATES:

So as has been suggested in the comments, use a view as a reference. It seems that choosing a view reference requires that the view be an Entity Reference (instead of type Page, Block, etc.) But, it seems that Media doesn't have the ability to search by tag. This Drupal project seems to try to address that - https://www.drupal.org/project/media\_taxonomy\_filter but no luck.

Also, another hurdle I seem to have hit is that when creating a View of type Media, there is no taxonomy field filter. This seems odd in that Media now can be categorized with taxonomy. Is that right? Like, for the admin media page which is powered by a view, can I not filter that by taxonomy?

# Answer
> 3 votes
As Kevin said, you need to install the Entity browser module

Optional module: I personally also use Entity Browser Enhance(d|r) for a much better usability when selecting media.

Go to `/admin/structure/views/add` and create a view showing `Media` items. On the next screen add a display type `Entity browser` to your view. You must add the special `Entity browser bulk select form` field to this view. Configure the view with additional fields and filters of your own choice. E.g. if you need taxonomy tags, add an exposed filter for your tags field.

Under `Configurarion > Content Authoring > Entity browsers`, create a new entity browser for your media. Configure as you need, and in the last step add the previously created view as widget plugin.
(Beyond the selection view you could add multiple widgets here like DropZoneJs for in-place uploading or Inline Entity form for in-place creating of new nodes).

Go to `Structure > Content Types`, and edit the form display of your node. Change the widget of the media field to `Entity browser` and select your previously created browser.

There are quite a lot of configuration options on the way, but this is a basic outline to get a media browser like this:
(The search part can contain any/multiple exposed filter like a "normal" view)

I recommend this tutorial for additional information
https://www.electriccitizen.com/blog/media-libraries-drupal-8
(but I personally would not use Inline entity forms for media, better stick with Entity browser for selection and DropZoneJS for in-place uploading)

---
Tags: 8, entities, files, media
---


# Question
Title: How can I validate exposed filter from View?
I have build View which work for search exactly content by number filed "ICO". How can I validate exposed filter form for only number and regular expression which enable only eight digit number?

Can you any help me with some example code for build it?

# Answer
> 2 votes
You should use `hook_form_alter()` to add a custom submit handler to the form like so:

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

function my_custom_validation() {
  // Add the logic that you want in here
}

```

Then use `form_set_error()` to indicate if the value is wrong.

# Answer
> 0 votes
I've tried using

```
$form['#validate'][] = 'events_month_filter_check_month_year';

```

My Requirement was to add a year drop down and I need validate if month and year was given in search. I've added month and year exposed filter in the view. Then I've altered year field from `form_alter` hook like below because I was not getting granular years.

User has to select both month and year when doing a search. If month or year is ignored I should validate and throw the error. this validation worked for me.

```
function events_month_filter_form_alter(&$form, &$form_state, $form_id) {

      if($form_id == 'views_exposed_form'
          && $form['#id'] == 'views-exposed-form-civi-events-page' )
      {
          $dropdown_array = array('All' => t('-Year'));
                $dropdown_array[date('Y')] = date('Y');
                $dropdown_array[date('Y') + 1] = date('Y') + 1;

          // Alter form
          $form['start_date_2'] = array(
             '#type' => 'select',
             '#default_value' => '1',
             '#options' => $dropdown_array,
          );
          $form['#validate'][] = 'events_month_filter_check_month_year';

       }//endif

     }

```

then validated using `$form['#validate'][] = 'events_month_filter_check_month_year';`

```
    function events_month_filter_check_month_year(&$form, &$form_state, $form_id) {
        //dsm('validate function');
            //dsm($form_state);
        $start_date_month = $form_state['values']['start_date_1'];
            if($start_date_month == 'All')
            {
                 $start_date_month = '';
            }

        $start_date_year = $form_state['values']['start_date_2'];
            if($start_date_year == 'All' || $start_date_year == 1 )
            {
                 $start_date_year = '';
            }

            if(!empty($start_date_month)){
                if(empty($start_date_year)){
                    form_set_error('start_date_2', t('Please choose a year.'));
                }

            }
            if(!empty($start_date_year)){
                if(empty($start_date_month)){
                    form_set_error('start_date_1', t('Please choose a month.'));
                }
            }
 }

```

Hope it helps someone in future.

---
Tags: views
---


# Question
Title: How to use Represenstive Views to display users representative nodes?
# Main view (User entity):

Fields:

* (Representative node) Content: Nid
* (Representative node) Content: Type
* (Representative node) Content: Post date
* (Representative node) Content: Title
* other fields

Filter criteria:

* user roles, user active

Relationships:

* User: Representative node

# Represantative view (Content based)

Fields:

* Content: Nid

Filter criteria:

* Content: Type (in Innovation, ...)
* Content: Language (= Current user's language)
* Content: Promoted to front page (Yes)

Sort:

* Content: Post date (desc)

Generated query: http://pastebin.com/cvKD3zzB

Error:

> Error message SQLSTATE\[HY093\]: Invalid parameter number: number of bound variables does not match number of tokens

Could someone give me any advice?

# Answer
The error has to do with a bug related to User: Representative node. Checkout https://www.drupal.org/node/1417090. Comment #35 has a patch for the latest dev version of views that will possibly fix the issue.
> 1 votes

# Answer
Drupal 8 still has problem here is the related issue with patches available
> 1 votes

---
Tags: 7, views, nodes, users
---


# Question
Title: How do I show only the latest post from each user in a view?
I'm trying to show a list of only the most recently published post by every user (not including the logged in user) in a view. What should my Views filters look like in order to accomplish this? I'm completely stuck!

At the moment, my view shows all posts from all other users. I now need to filter it down once more so that it ONLY shows the most recent post by all of these users.

**Reference (issue):**

# Answer
> 4 votes
The problem is that you are trying to filter based on two things:

* Show the most recent content by an individual user.
* Show each user.

In Views, you can generally only filter one kind of entity (content OR users) at a time.

However, there is a module that can help, Views Field View. This module lets you embed one view inside another.

So, you can do something like this:

1. Create a view that shows the most recent content for a single user (takes a contextual filter of UID, returns one result, sorted by descending most recent).
2. Create another view that shows all users except the logged in user. Use Views Field View module to embed the first view and show the most recent post by each user.

I haven't done this exact implementation before, but I've used Views Field View for similar things. There is a tutorial here.

If you use this module, do note this warning from the documentation:

> Please note that using this module can impact the performance of your site, if the views being rendered are very resource-consuming. It's highly recommended to use this module in conjunction with other modules that provide views caching.
>
> Good candidates to cache your views are the modules Views content cache and Cache Actions.

# Answer
> 1 votes
Latest views Drupal 7 and 8 can do this without needing extra module

Add new view Show: Users

Relationships Add a relationshop "User: Representative node" Change "Representative sort criteria" to "Content: Updated date"

FIELDS Add a "Content:Title" field and make sure the Relationship is set to "Representative node"

Sort criteria Add a "Content: Updated date" to Sort criteria section and again make sure the Relationship is set to "Representative node" and also the "Sort descending" radio box is checked.

---
Tags: 7, views
---


# Question
Title: How to change the 'Quantity' label in commerce-order-item-add-to-cart-form
I'm trying to modify my 'Add to cart' form, changing the 'Add to cart' button text and the 'Quantity' label:

```
if(strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce') !== false) {
    $form['actions']['submit']['#value'] = t('Book Now');
    $form['edit-quantity']['und'][0]['value']['#title'] = t('Number of days');
  }
}

```

The first part is working, changing the 'Add to cart' button text, but the second part is failing changing the 'Quantity' label.

Any idea how to fix it?

# Answer
> 1 votes
To change label try with:

```
$form['edit-quantity']['widget']['value']['#title']  = t('Number of days');

```

Or:

```
$form['edit-quantity']['widget'][0]['value']['#title']  = t('Number of days');

```

Use Devel to check `$form['edit-quantity']['widget']` with `dsm($form['edit-quantity']['widget'])` or `dpm($form['edit-quantity']['widget'])`.

---
Tags: 8, commerce, hooks
---


# Question
Title: How do I implement a one page navigation with anchors?
So the specific functionality I'm looking for is a link on one page (e.g. drupalsite/home) leading directly to a specific section of another page (e.g. a section on drupalsite/otherpage).

I believe that to implement this I need to use hash based navigation such that the content I want to link to is has it's css class name preceded by a hash (pound sign or number symbol) `<div class="#mydiv">` and is linked to by including the hash referenced content in the href attribute of an anchor tag. Such that `<div class="#mydiv">` on page drupalsite/mypage via `<a href="/mypage#mydiv">`.

Will this work without out of the box with just HTML changes? Or is additional JavaScript configuration necessary?

I know that more specific and fluid implementations will necessitate JavaScript and jQuery, but I want to know if the core HTML works without conflicting with Drupal's internals.

# Answer
This is the code I'm using on most of my projects

```
(function ($, Drupal) {
  var wt = window.wt || {}; //just my personal namespace

  wt.getFixedTop = function() {
    /* return pixel height of fixed elements, e.g. Admin Toolbar or a fixed main nav */
  };

  wt.scrollTo = function(uri) {
    if ((uri.indexOf(location.pathname) === 0 || uri.indexOf('#scroll') === 0) && uri.indexOf('#scroll') !== -1) {
      var selector = decodeURIComponent(uri.substring(uri.indexOf('#scroll') + '#scroll'.length));
      var regex = /^=[#\.\[\]a-zA-Z0-9-_]+$/;
      if (selector.search(regex) != -1) {
        selector = selector.substring(1);
        $('html, body').animate({scrollTop: $(selector).offset().top - wt.getFixedTop() }, 1000);
      }
      return false;
    }
  }

  $('body').on('click', 'a[href*="#scroll"]', function () {
    wt.scrollTo($(this).attr('href'));
  });

  $('body').imagesLoaded( function() {
    window.setTimeout( wt.scrollTo(location.pathname + location.hash), 200 );
  });

}(jQuery, Drupal));

```

It requires ImagesLoaded and works within and across pages, and with responsive images. It also allows linking to IDs *and* classes by appending the proper CSS selector, e.g. `/some-page#scroll=.my_class`

It certainly is not a perfect solution, but our internal, HTML-trained editors can quickly create deep links to any section they want by adding `#scroll=<CSS_ID_OR_CLASS_SELECTOR>` to any link.
> 0 votes

---
Tags: 8, javascript, navigation
---


title: Require field on publish only

text:
# Question
Title: Require field on publish only
I have a D8 site on which I would like to require an image field to be completed only when a node is published; if the publish box is not checked, the field should not be required. I was able to do this with a custom module in D7, but since D8 has decoupled entity validation from form validation, I'm at a loss.

I've tried doing this with the Rules module, with no luck.

# Answer
> 3 votes
Simply add a validation on the entity level, then you have easy access to the whole entity.

You can see an example in content\_translation\_entity\_type\_alter():

```
$entity_type->addConstraint('ContentTranslationSynchronizedFields');

```

You register a constraint like any plugin, the only special thing is that there are two classes, the plugin class itself doesn't really have anything except the messages usually while the validator has the logic, in the validate method::

ContentTranslationSynchronizedFieldsConstraint ContentTranslationSynchronizedFieldsConstraintValidator::validate

Once you have that, writing the actual logic is often much easier, because you have a fully built entity object to work with and don't have to wory about getting the raw values from the form values. And as a bonus, it will also automatically work for REST/json\_api and any other module that uses the validate() method to ensure that created entities are valid before saving them.

For example, verifying that an image field is not empty when the entity is published:

```
if ($entity->isPublished() && $entity->hasField('field_image') && $entity->get('field_image')->isEmpty()) {
  // add a violation...
}

```

# Answer
> 1 votes
I know this question was answered, but if anybody else is looking for a less custom solution I wrote a module that adds this functionality: https://www.drupal.org/project/require\_on\_publish.

# Answer
> 0 votes
You can do that by adding custom validation for the form

```
function custom_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#validate'][] = 'mycustom_node_form_validate';
}

```

Then you need to implement your custom validator:

```
function mycustom_node_form_validate($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  if ($node->getType() == 'node_type') {
    // Get status and image values.
    $status = $form_state->getValue('status');
    $image_field = $form_state->getValue('field_my_image_field');
    // Check if image is empty and status is published.
    if (empty($image_field['fids']) && $status['value']) {
      $form_state->setErrorByName('field_my_image_field', t('Image missing.'));
    }
  }
}

```

Another way to accomplish that can be by using Conditional Fields This is a really great module which let you control the visibility of the fields based on values of another field.

Just enable it and under the content type operations, you can find Dependencies option where you can map the dependency.

---
Tags: 8, forms, entities
---


# Question
Title: How to favor exact matches in entity reference autocomplete?
Right now if you use entity reference autocomplete for short titles of a node type or entity type, and you have many items, due to the fact that by default they are ordered by entity id (nid), less relevant entries show up before exact matches.

For example, if you create a content type for stock symbols, and you have tens of thousands of them, and you want to search for "EA" or "DIS", longer strings that contain these substrings show up before exact matches.

How can you change the behavior so exact matches show up before other matches with lower entity ids?

# Answer
> 5 votes
Here's a way to alter the query for entity reference autocomplete. You can add an expression that returns the string length and then sorts by this. This way, if a string contains "DIS", and it sorts by the string length, it will start with 3, and the only item that contains the string and is of the shortest length that contains the string (3) is the exact match, so it will show your exact match first, and then other relevant items that contain the string. For example "ADIS" or "DISV".

```
/**
 * Implements hook_query_TAG_alter().
 *
 * Favor exact matches and shorter matches in node reference
 * autocomplete.
 */
function mymodule_query_entity_query_node_alter(AlterableInterface $query) {
  $routeMatch = \Drupal::routeMatch();

  if ($routeMatch->getRouteName() != 'system.entity_autocomplete' ||
    $routeMatch->getParameter('selection_handler') != 'default:node' ||
    $query->getMetaData('entity_type') != 'node') {
    return;
  }

  if (is_object($query->getMetaData('entity_reference_selection_handler')) && $query->getMetaData('entity_type') == 'node') {
    $tables = $query->getTables();
    if (!empty($tables['node_field_data'])) {
      $query->addExpression('CHAR_LENGTH(node_field_data.title)', 'shortest');
      if ($groups = $query->getGroupBy()) {
        $query->groupBy('shortest');
      }
      $query->orderBy('shortest');
    }
  }
}

//You can use the same basic template for other entity types:

/**
 * Implements hook_query_TAG_alter().
 *
 * Favor exact matches and shorter matches in mycustomentity entity reference
 * autocomplete.
 */
function mymyodule_query_entity_query_mycustomentity_alter(AlterableInterface $query) {
  $routeMatch = \Drupal::routeMatch();

  if ($routeMatch->getRouteName() != 'system.entity_autocomplete' ||
    $routeMatch->getParameter('selection_handler') != 'default:mycustomentity' ||
    $query->getMetaData('entity_type') != 'mycustomentity') {
    return;
  }

  if (is_object($query->getMetaData('entity_reference_selection_handler')) && $query->getMetaData('entity_type') == 'mycustomentity') {
    $tables = $query->getTables();
    if (!empty($tables['mycustomentity_field_data'])) {
      $query->addExpression('CHAR_LENGTH(mycustomentity_field_data.title)', 'shortest');
      if ($groups = $query->getGroupBy()) {
        $query->groupBy('shortest');
      }
      $query->orderBy('shortest');
    }
  }
}

```

---
Tags: 8
---


title: How to Search Content in Views?

text:
# Question
Title: How to Search Content in Views?
I have created a view to list all the contents I created. I need a search field in the view to search for contents. I tried the search module and when I search using one of the content names, it doesnt display the result.

# Answer
> 1 votes
views allow you to add some **"Filter criteria"** example:

> Add filter by content title then check **Expose this filter to visitors, to allow them to change it**

---
Tags: views
---


# Question
Title: Using the fetch() method in database query to get an array
I have a very simple query that does the job, to get a collection of a specific content type's node id and title, that's it.

```
$connection = \Drupal::database();
$query = $connection->select('node_field_data', 'n');
$query->condition('n.type', 'employee');
$query->condition('n.status', 1);
$query->fields('n', ['nid', 'title']);
$results = $query->execute()->fetchAll();

```

And what i get is an array filled with objects (for each individual results) with two `properties` the nid and title values. But i want to have an single layer/dimension array filled with key =\> valued pairs (nid =\> title). Example bellow.

```
$results = [
  0 = {stdClass} (
     nid => 123,
     value => Susan Green
  )
];

```

And what i want:

```
$results = [
  123 => Susan Green,
  567 => Bob Young
];

```

I've tried fetchAllAssoc, fetchAssoc, etc but either the `result` is empty or i get something completely opposite of what i want.

Any ideas? **without using a parses to convert objects into what i want, that's what i'll do if none one can find an appropriate answer.**

# Answer
You can use fetchAllKeyed try with:

```
  $connection = \Drupal::database();
    $query = $connection->select('node_field_data', 'n');
    $query->condition('n.type', 'employee');
    $query->condition('n.status', 1);
    $query->fields('n', ['nid', 'title']);
    // use fetchAllKeyed
    $results = $query->execute()->fetchAllKeyed(0,1);

```
> 5 votes

---
Tags: database
---


# Question
Title: How can I get the full content of a PHPUnit test truncated response?
I'm writing a Functional test (extending BrowserTestBase) for a Drupal REST resource. My resource works fine in real life, but the test (running with --verbose and --debug options) throws a server error

`...resulted in a '500 500 Service unavailable (with message)' response:
The website encountered an unexpected error. Please try again later.

Drupal\Component\P (truncated...)`

This happens when I make the request, before I can try to catch it in an assertion. I'm pretty sure that truncated output has the information I need to solve this, but I'm having no luck getting to it. Drupal console docs say there's a `test:run` command but when I try that (v1.8.0), it tells me that's not a valid command name. I've tried running my test through the debugger but no help there, either.

Is there any way I can get to see what's in the truncated part of the response?

# Answer
> 0 votes
My problem stemmed from trying to use GuzzleHttp to make my request, instead of BrowserTestBase::drupalGet(). I still don't know about getting to that truncated output, but using drupalGet() returns the output without truncating.

---
Tags: testing
---


title: Solr facets returning deleted TIDs

text:
# Question
Title: Solr facets returning deleted TIDs
This seems to be a common issue when deleting terms linked to indexed content via term/entity reference, but no solution has worked so far.

I am using the following:

* Drupal 7
* Solr 5.5.3
* Search API 7.x-1.22
* Field reference delete 7.x-1.0-beta1

The terms are linked via a term reference field on a node.

When the term is deleted, Field reference delete module informs Solr the referenced nodes need reindexing, which removes all articles containing the TID. This works fine. However after reindexing the term ID is still shown with (0) results on display instead of the term name.

Only deleting all indexed content and reindexing removes the facet as expected.

Before this, querying Solr for facets returns this:

```
{
  "response": {
    "numFound": 1139,
    "start": 0,
    "maxScore": 0.43971312,
    "docs": [
      {
        "item_id": "124618",
        "score": 0.43971312
      }
    ]
  },
  "facet_counts": {
    "facet_queries": {},
    "facet_fields": {
      "im_field_tax_tags": {
        "1107": 8,
        "1108": 212,
        "1109": 29,
        "1110": 619,
        "1111": 0,
        "1112": 61,
        "1114": 59,
        "1115": 105,
        "1117": 48,
        "1118": 35,
        "1119": 67,
        "1121": 120,
        "1124": 234,
        "1125": 15,
        "1127": 60,
        "1129": 6,
        "1133": 304,
        "1134": 59,
        "1214": 856,
        "1215": 317,
        "1216": 397,
        "1217": 819,
        "1219": 597,
        "1220": 6
      },
    },
    "facet_dates": {},
    "facet_ranges": {},
    "facet_intervals": {},
    "facet_heatmaps": {}
  }
}

```

Note 1111 has been deleted and has 0 results, yet still appears in Solr's list of facets. I presume this is cached somehow. Searching for im\_field\_tax\_tags:1111 also returns 0 results.

It is also worth noting that the facet display has a Minimum facet count of 0, as the way they are displayed requires empty facets to be shown. I understand changing this to 1 would solve the problem (I suspect this is a more common configuration, which may explain why others have had more success), but it is unfortunately not an option.

Any help would be appreciated.

# Answer
> 0 votes
Go to Solr Admin (usually http://localhost:8983/)

Go to Core Admin or your core selector and click Reload. When refreshed, you should see a green check mark on the "current" field. After this, your solr cache will be deleted and refreshed with new indexes.

# Answer
> 0 votes
To remove items with count 0, Optimize your core.

Go to the solr admin page, select the core you are working on, and click on "optimize" button.

---
Tags: search
---


# Question
Title: Trying to display or render values from links field within paragraph field base on its current language
I'm currently using Drupal 8 Paragraph and I'm trying to figure out how I can display or output the url and title of a link field from within a Paragraph base on the current language via preprocess. Here is a snippet of the code I'm working on.

```
function iom_preprocess_paragraph(&$variables) {

    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

```

---

```
function _generatePrimaryLinkElement($currentNode, $entity, $title, $url) {

    $attributes = new Attribute(['class' => ['menu-item']]);

    if ($entity && ($currentNode->id() === $entity->id())) {
        $attributes['class'][] = '-active';
    }

    return [
        'attributes' => $attributes,
        'link' => [
            'attributes' => new Attribute([
                'href' => $url,
                'class' => ['link']
            ])
        ],
        'title' => $title
    ];
}

```

---

```
function _preprocess_primary_links_paragraph($paragraph, &$variables) {
    // Current page node
    $currentNode = \Drupal::request()->attributes->get('node');
    $activeLanguage = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $links = [];

    foreach ($paragraph->field_link as $link) {
        $entity = _loadEntityByUri($link->uri);

        $title = $link->title;

        // If there is an entity and the title is not set of the link
        // use the entity title instead
        if ($entity && !$title) {
            $title = $entity->title->value;
        }

        $links[] = _generatePrimaryLinkElement($currentNode, $entity, $title, $link->getUrl()->toString());
    }

    $variables['label'] = $paragraph->field_label->value;
    $variables['links'] = $links;
}

```

---

```
<div class="sidebar-menu-group primary-link">
    <span class="label">{{ label }}</span>
    <ul class="menu -sidebar">

        {% for link in links %}

            <li {{link.attributes}}>
                <a {{link.link.attributes}}>{{link.title}}</a>
            </li>
        {% endfor %}
    </ul>
</div>

```

# Answer
> 1 votes
Below is some general purpose code I wrote to solve this problem across a lot of code. It can take either a standard /node/## path or an alias and convert it to the desired language. It assumes you are using prefixed language URLs and 'en' is the default language. If FL URL can not be found, the same URL is returned.

```
/**
 * Utility function to take a standard drupal path or alias and convert to the specified language alias path.
 *
 * @param string $path Root relative standard path, e.g. /node/### or english alias, e.g. /my/view and the like.
 * @param string $langCode  Language code for the resulting url. If not specified current language is used.
 * @param boolean $testPrefix If true, the input URL will be tested to see if the language prefix is already there.
 * @return string
 */
function my_i18n_language_url( $path, $langCode=NULL, $testPrefix=FALSE ) {
  if ( empty($langCode) ) {
    $langCode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  }
  // Optional check to see if url already has language prefix.
  if ( $testPrefix ) {
    $languages = \Drupal::languageManager()->getLanguages();
    foreach ( $languages as $code => $lang ) {
      if ( strpos($path, "/{$code}/") === 0 ) {
        return $path;
      }
    }
  }
  // If in alias format convert to node/### format.
  if ( strpos($path, "/node/") !== 0 ) {
    $url = \Drupal::service('path.alias_manager')->getPathByAlias($path,'en');
    if ( $url == $path ) {
      // Maybe it's a view
      try {
        $url = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langCode);
        if ( $url == $path ) {
          return $path;
        }
      }
      catch ( Exception $e ) {
        watchdog_exception('my_i18n', $e );
        return $path;
      }
    }
    $path = $url;
  }
  $url = $path;
  try {
     $url = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langCode);
  }
  catch ( Exception $e ) {
    watchdog_exception('my_i18n', $e );
    return $path;
  }
  $url = my_i18n_language_prefix($langCode) . $url;
  return $url;
}

/**
 * Utility function to get a language prefix based on the current page language.
 *
 * @param string $langCode  Optional - defaults to current language
 * @return string
 */
function my_i18n_language_prefix( $langCode=NULL) {
  $manager =  \Drupal::languageManager();
  $default_lang = $manager->getDefaultLanguage()->getId();
  if ( empty($langCode) ) {
    $langCode = $manager->getCurrentLanguage()->getId();
  }
  if ( $langCode == $default_lang ) {
    return "";
  }
  return "/{$langCode}";
}

```

---
Tags: theming
---


title: Drupal 8 Custom Composite Masked Input

text:
# Question
Title: Drupal 8 Custom Composite Masked Input
Are masked inputs supported in custom composites?

I've tried the following and it doesn't break but it also doesn't mask.

```
$elements['job_details']['job_phone'] = [
  '#type' => 'textfield',
  '#input_mask' => '(999) 999-9999',
  '#title' => t('Company Phone Number')
];

```

# Answer
> 0 votes
If you want to get simple form elements to include webform element enhancements you have to 'initialize' the composite's sub-elements using `\Drupal\webform\Element\WebformCompositeBase::initializeCompositeElements`

# Answer
> 0 votes
If anyone else came here (like me) looking for a way to add an input mask to a custom composite created through the Webform Composite Tools UI, you just need to add a custom property to your (sub)element:

```
input_mask: '''alias'': ''currency'''

```

---
Tags: webforms
---


# Question
Title: View listing related nodes by taxonomy term
I have a content type representing a book. Each book as a genre (SciFi, Fantasy, Thriller ...) and I would like to expose, on the page of a book some books sharing the same genre.

I created a view with a contextual filter on the taxonomy term, but I retrieved the current book so I added a contextual filter on tue current node id to exclude it.

Now I don't retrieve anything from my view.

Each contextual filter on his own his working. If I just use the contextual filter on the content id, I retrieve the list of my books without the current book. If I just use the contextual filter on the taxonomy term, I retrieve the list of my book for that genre (including my current book).

How am I supposed to proceed to have both filter working together ?

# Answer
Many of the Drupal features seem magical, but sometimes there are more steps to configure to make them work.

## How to use Views Preview with Contextual filters

Contextual filters are strictly linked to individual Fields. It isn't enough to use only the NID Contextual filter (in your Preview) that would then be able to "pull" all the other information, no matter if you have the other Contextual filters set up.

What you enter into the Preview field is what Drupal would take from the URL, or the specified default value as if the URL value is available.

**If you have two Contextual filters, you need to enter two filter values into the Preview, one for each filter, in the correct order, separated by `/`.**

To test the complete situation you enter a value for both Contextual filters, for example `thriller/35` or `21/35` if Thriller has TID 21 and your first Contextual filter is for term ID and not term name, and 35 is the "current node" NID.

Most Contextual filters have the `Exception value` set to `all`. This is a sort of a bypass, the Contextual filter behaves as if it weren't there.

So if you have two Contextual filters and you enter `all/all` you will see the Views results as if there are no Contextual filters at all.

This is useful when you have to test a Contextual filter while making sure the other one isn't in the way. So you enter `all/35` to see all nodes but not the current one (if the current one has NID 35). Or you enter `thriller/all` so see nodes tagged Thriller but the current one is still on the list.

The Views Preview field (arguments) can test only the part of the Contextual filter that has `Provide default value` or `When the filter value IS available or a default is provided` options.

Preview does help to test and configure Contextual filters more quickly, but it doesn't gurantee that you have set them up correctly for *cases that don't take values from the URL*, so you have to test the Block on the appropriate location anyway.
> 1 votes

# Answer
It appears I'm just too stupid to understand Drupal. The view is working when I place a block on the book page. The problem was in the preview with contextual filters. I specified the node id, expecting Drupal to retrieve everything from this id but it appeared it is not enought so it was answering me that No query was run.
> 0 votes

# Answer
Use Similar terms module.

Usage:

1. Create a freetagging vocabulary called "Tags" assigned to the content types on which you'd like to display the "Similar" view block.

2) Enable the view block called "Similar entries from the Tags vocabulary".

3) Add keyword tags to the content.
> 0 votes

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


# Question
Title: How to let content editors use pre-defined block-like content?
In wordpress (gutenberg), content editors can choose some kind of pre-defined blocks to their content. If I have content editors, that can create new nodes, I want them to be able to add such blocks into their content, but in a more drupal like way.

Let's say, the editor wants to create an article and wants to add a quote, a picture with a description or a Video with a description. I would assume, that I could create custom block types for these, to have the required fields and to create a design for these blocks.

But:

* The editor should be able to create one or more of these blocks, preferrably *on* the page that they're editing.
* And they should be able to place these peaces of content anywhere in their content.

An example would be an outstanding quote, that could be placed anywhere in the text, but not by creating/designing it at that place in the text, where it makes sense content-wise, but without having to design it, using the text editor itself.

Best case: They could even be able to chose whether they place it within the text in a big version or in a sidebar in a smaller version.

My problem:

* If it's a custom block type, how can I assign only a defined set of these to a certain content type? This only works with fields, does it?
* How can I add them to the editor form without cluttering it with forms for all possible types?

# Answer
Just because you're calling it a block-type of content it doesn't mean it will necessarily be the Block structure in Drupal.

Using Paragraphs you can create such structures for your nodes, where editors will be able to choose and reorder different types of paragraphs *you* have set up for them.

You can think of Paragraphs as Blocks to be inserted/reordered within content if you like. One Paragraph type in your case would have an image field and the quote/description field. The other paragraph type would have a video field and a description field.

You style each paragraph in your subtheme the way you want it too look like (for example you want the image to be centered above its description, but entire paragraph is floated within other fields, like Body text).

Paragraphs on the Edit form present as a Drop-down choice, so you won't see all available forms to start with and the interface isn't cluttered. You choose to add one paragraph at a time.

Once you have more than one paragraph added on the Edit page you can "collapse" them so they don't take a lot of space. This also makes them easy to reorder.

## For more advanced layout use Bricks

For more advanced layouts and flexible building of nodes you should use the Bricks module with the Layout Builder and Inline entity form.

Bricks is a more advanced/apstract module than Paragraphs. It lets you reuse Paragraphs and choose Layouts right on the Create/Edit page.
> 1 votes

---
Tags: 8, blocks, paragraphs
---