# Question
Title: Getting an error while updating core to version 8.7.0
When update Drupal 8.6 to 8.7 getting the following error. Anyone help would be appreciated.

```
TypeError: Argument 3 passed to Drupal\views\EntityViewsData::mapFieldDefinition() must implement interface Drupal\Core\Field\FieldDefinitionInterface, null given, called in /Users/punya/htdocs/un-nip/core/modules/views/src/EntityViewsData.php on line 290 in Drupal\views\EntityViewsData->mapFieldDefinition() (line 387 of core/modules/views/src/EntityViewsData.php).

Drupal\views\EntityViewsData->mapFieldDefinition('file_managed', 'type', NULL, Object, Array) (Line: 290)
Drupal\views\EntityViewsData->getViewsData() (Line: 16)
Drupal\file\FileViewsData->getViewsData() (Line: 178)
views_views_data()
call_user_func_array('views_views_data', Array) (Line: 392)
Drupal\Core\Extension\ModuleHandler->invoke('views', 'views_data') (Line: 243)
Drupal\views\ViewsData->getData() (Line: 160)
Drupal\views\ViewsData->get('node_field_data') (Line: 85)
Drupal\views\Plugin\ViewsHandlerManager->getHandler(Array, NULL) (Line: 889)
Drupal\views\Plugin\views\display\DisplayPluginBase->getHandlers('sort') (Line: 1040)
Drupal\views\ViewExecutable->_initHandler('sort', Array) (Line: 898)
Drupal\views\ViewExecutable->initHandlers() (Line: 2267)
Drupal\views\Plugin\views\display\DisplayPluginBase->preExecute() (Line: 1692)
Drupal\views\ViewExecutable->preExecute(Array) (Line: 1627)
Drupal\views\ViewExecutable->executeDisplay('page_1', Array) (Line: 77)
Drupal\views\Element\View::preRenderViewElement(Array)
call_user_func(Array, Array) (Line: 378)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

# Answer
I just worked through a similar issue. Yours may not be exactly the same, but I had to do two things. (1) Remove all old code associated with 8.6 and older versions. Basically, instead of copying 8.7 on top of 8.6, I deleted everything except my sites directory from 8.6, and copied the 8.7 files and folders fresh. (2) In sites/all/modules, I was using profile. Apparently, this module is not compatible with 8.7, at least the version I am using. Removing this folder completely allowed my site to upgrade with no further issues. There may be other contributed modules that also have issues with 8.7.
> 2 votes

---
Tags: entities
---


# Question
Title: Taxonomy Term Field of a Reference Field in a Product not available in Data Selector for CheckOut Rules
I installed Drupal Commerce Kickstart 2 with drupal version 7.54 and drupal commerce Version: 7.x-1.14. My problem is I want to send email to the store owner every time an order is completed. So in `CheckOut Rules`, I created a rule `Commerce order message: order notification e-mail`.

My Event is `Completing the CheckOut Process.` My Action is to `Send Mail` but in the `To` field, I could not find the right replacement pattern I need. The referenced custom field `field_store_email_address` was not available there. Below is the setup

My website sells Pizza, so I have a `Pizza` content type. In the Pizza content type my fields are `Store(field_store)` and I will not name other unrelated fields. The `field_store` in my Pizza content type is a term reference to a vocabulary taxonomy `Store`. In the taxonomy `Store`, it has a field `store_email_address(field_store_email_address)`. `field_store_email_address` is where I want to send my email.

When the checkout process is completed, I want to send an email to unique store owners of items included in the order. So my question here is how will I formulate my `Conditions Rules`? Please help me.

# Answer
> 2 votes
D7, install Conditional rules module, this module let's you add aditional conditions at action section in rules UI.

You say your event is 'checkout proccess', so, the first thing you need is to load your 'pizza' node object in to rules, I am assuming that you have a field in your product-fields referencing to your 'pizza-content-type'.

To do this, in actions UI add a conditional, add and if, entity has field, your product-field that is referencing to pizza-content-type, if true (always be true, but you need this so rules can load your pizza-node), then fetch entity-by-id, your pizza-node, now you have pizza-object available

Add another conditional, add another if, entity has field, your taxonomy-term related to taxonomy store, then, fetch entity by id, your taxonomy term, now you have available taxonomy term related to store, then add a conditional, entity has field, your taxonomy-term `field_store_email_address`, and now you have now available `field_store_email_address` value in rules, send your email, done.

Here is an img that look alike what your rules action will look.

---
Tags: 7, commerce, taxonomy-terms, rules, actions
---


# Question
Title: Populate a field in form alter with user name and one with user ID
can someone tell me why this works

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

  global $user;
  if ( $form_id == 'node_test_form'){
    $form['field_owner']['widget'][0]['value']['#default_value'] = 'test';
  }
  return $form;
}

```

but this doesn't

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

      global $user;
      if ( $form_id == 'node_test_form'){
        $form['field_owner']['widget'][0]['value']['#default_value'] = $user->uid;
      }
      return $form;
    }

```

I'd also like to know how I get the current users name too, if someone can assist with that it would be much appreciated.

# Answer
> 2 votes
The D8 `uid` property reference isn't something that can be cast into a string as you could in D7.

In D7, user objects use a generic PHP object class (`stdClass`) with a `uid` property containing a string. In D8, user objects use a `Drupal\user\Entity\User` class. This class does't have a *direct* `uid` string property.

In D8 the `uid` property magically retrieves the User entity field property instead of a simple uid string.

As such, there are other new methods/properties (as you've mentioned) to retrieve the underlying uid value.

# Answer
> 0 votes
This worked for me

```
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// retrieve field data from that user
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;

```

Then you can just use

```
$form['field_owner']['widget'][0]['value']['#default_value'] = $uid;

```

or

```
$form['field_owner']['widget'][0]['value']['#default_value'] = $name;

```

Thanks for looking, if there is a better way then please let me know

Gibbo

---
Tags: 8, forms
---


title: Media images link to their own image

text:
# Question
Title: Media images link to their own image
I have inherited a site which had no image management. Instead each image field required you to upload an image instead of reuse an existing one. I enabled Media Browser and updated to 8.7. I am also using the following modules \[these are the ones I have installed ontop of existing\]:

* embed
* entity\_embed
* editor\_advanced\_link
* inline\_entity\_form
* entity\_browser
* media\_entity\_browser

The problem is every image, either added via an image filed or in CKEditor wysiwyg is now wrapped in a link to the image file:

```
<a href="/path-to-image/image.ext"><img src="/path-to-image/image.ext"></a>

```

Twig template: \core\modules\image\templates\image-formatter.html.twig

has the following:

```
{% if url %}
  <a href="{{ url }}">{{ image }}</a>
{% else %}
  {{ image }}
{% endif %}

```

But I cannot see where the URL is set in the CMS admin, or how to stop it creating a link to itself. So far I have just copied the template to my theme and removed the url, but I would like to know how to manage this properly.

# Answer
> 1 votes
In: structure -\> media types -\> image -\> display

/admin/structure/media/manage/image/display

the image field settings had 'Link image to' -\> file

Set this to nothing, removed the theme image-formatter.html.twig template and the file link added to each image was no longer there.

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


# Question
Title: Add an entity reference select to a form
I am writing a Drupal 8 module, and I have some code that adds an entity reference field to a form.

```
$form['commitment']['goal'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => 'Goal',
    '#target_type' => 'node',
    '#selection_settings' => ['target_bundles' => ['goal']],
);

```

This works, except that I want a select list instead of an autocomplete.

How can I accomplish this?

# Answer
Basing on the OP solution, I would suggest the follow code.

```

$options = [];
$goal_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => 'goal',
]);

foreach ($goal_nodes as $goal_node) {
  $options[$goal_node->id()] = $goal_node->label();
}

$form['commitment']['goal'] = [
  '#type' => 'select',
  '#title' => t('Goal'),
  '#options' => $options,
];

```

This has still two issues:

1. Entities are not translated
2. Bundle label ('Goal') is not programmatically coming
> 5 votes

# Answer
Found out after 2 hours of search in drupal core:

```
->setDisplayOptions('form', array(
            'type' => 'options_select'
        ))

```
> -1 votes

---
Tags: 8, entities
---


title: How do I turn off account creation?

text:
# Question
Title: How do I turn off account creation?
Recently I've been receiving many spammers creating an account on my website, which is quite basic and for which I don't need users create an account.

What would the likely URL that spam bots are finding be?
Is there a way to turn off account?

# Answer
> 38 votes
The answer given on How do I remove the user registration/login form? is relevant for this question too.

> While it's technically possible to remove the login functionality, you shouldn't, because then your administrator could never log onto the site.
>
> In order to remove the register functionality, you simply need to browse to admin/user/settings (for Drupal 6) or admin/config/people/accounts (for Drupal 7 and 8) and select the the "Only site administrators can create new user accounts" option.

# Answer
> 1 votes
You can disable the forms all together. In a custom module:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_login':
    case 'user_register_form':
      $form['#access'] = FALSE;
    break;
  }
}

```

Depending on your needs, you can either create a custom page and set the login block there, so you and other administrators can login, or install HybridAuth module to allow visitors to login and register new accounts only through social media 3rd parties.

# Answer
> 0 votes
As an additional step to the above you could change the default url path from /user login screen using "rename admin paths" module to something nobody would guess.

Eg, www.sitename/randomcombition/ \< this way user's will have to know this url before they can even try logging in.

# Answer
> 0 votes
1. yourwebsite.com/user - this is the standard Drupal login URL (at least for 7) and bots find it routinely.
2. Remove visitor registration as described in Chapabu's answer

---
Tags: 7, users
---


title: Adding event listener on an AJAX button

text:
# Question
Title: Adding event listener on an AJAX button
I've tried to add a loading animation to the website in case if the user clicks on buttons or input submit buttons. It work, except on those buttons which using AJAX. For some reason those buttons are processed, but my event listener looks like it was detached... Anybody know the reason or how can I fix it?

Code for the loading (it will create an overlay with a spinner and text):

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleLoading = {
    attach: function attach(context) {
      $('button, .btn, input[type=submit]').not('.close').once('loading').on('click', function (event) {
        // Create the loading DOM.
        var background = $('<div>', document);
        background.addClass('loading-background');
        var logo = $('<div>', document);
        logo.addClass('loading-container').append(
          $('<div>', document).addClass('loading-container-inner').append(
            $('<div>', document).addClass('loading-icon')
              .append($('<div>', document)).append($('<div>', document))
              .append($('<div>', document)).append($('<div>', document))
              .append($('<div>', document)).append($('<div>', document))
              .append($('<div>', document)).append($('<div>', document))
          ).append(
            $('<div>', document).addClass('loading-text').text('Processing...')
          )
        );

        // Add to the body the created DOM.
        $('body').append(background).append(logo);
      });

      // Remove any remaining loading if user close a modal.
      $('.close').on('click', function () {
        $('.loading-background, .loading-container').remove();
      });

      // If it was an AJAX call this will be called.
      $('.loading-background, .loading-container').remove();
    }
  };
}(jQuery, Drupal));

```

Keep in mind, it works on those buttons, which doesn't use AJAX at all. With those buttons which using AJAX, it doesn't work from the beginning, but the `loading-processed` class is visible, which is added by the `once('loading')` code. I guessing there's a magic somewhere in Drupal which prevents to call other event listeners? (In chrome there's a way to stop the script and debugging if a click event happened, in AJAX buttons it doesn't stop, in normal buttons it stops, both are `input[type=submit]` type buttons.)

# Answer
> 0 votes
I'm not sure, based on your code, how you are adding buttons to your form(s)/pages, however, I would venture to guess the AJAX controlled buttons are not working because they are calling the built-in loading/submit callbacks within the Drupal 7 AJAX API (example.)

You may find the following example useful:

```
/**
* Implementation of hook_menu().
*/
function myModule_ajax_menu() {
  $items['get/ajax/Simple Drupal AJAX load with jQuery and delivery callback'] = array(
  'page callback' => 'myModule_ajax_get_ajax', // Render HTML
  'type' => MENU_CALLBACK,
  'page arguments' => array(2),
  'access arguments' => array('access content'),
  'delivery callback' => 'myModule_ajax_callback',  // Magic goes here
 );
 return $items;
}

```

---
Tags: 7
---


# Question
Title: How do I specify a Forena PDO data source in settings.php?
I would like to override my Forena data sources in a local settings file for development. I would also like them in settings.php on production for database independent deployment.

I have checked the documentation but a full example is not provided. Can anyone provide a full example?

# Answer
> 2 votes
A sample of what you are looking for can be found in Forena subfolder `repos/sample/settings.php`, it looks like so (and is for 7.x-4.x):

```
<?php
/*
 * Sample Repository configuration file
 */

/*
 * Security provider:  Specify the class name that is used to provide security
 */
$conf['access callback'] = 'user_access';

/*
 * Data provider:
 * Specify the class name that will be used to interpret data block files.
 * Note that data blocks in a repository
 *
 */
$conf['data provider'] = 'FrxPDO';

/*
 * URI:
 * The format of the uri depends on the type of data engine that's being used.
 * In database engines it might be the connection string to the db.  In the file
 * engine it would be the path to the directory containting the files
 */
$local_path = realpath(dirname(drupal_get_path('module','forena').'/forena.info'));
$conf['uri'] = 'sqlite:'. $local_path . '/repos/sample/sample.db';
$conf['debug'] = FALSE;
/**
 * Uncomment the following line to specify a particular path in which to save reports.
 * The default value would be controlled by Forena configuration page. If you'd like users
 * to be able to define their own reports in this repository then you need to make sure that this
 * is writable by the web user (e.g. apache).
 */
// $conf['report_path'] = 'sites/files/reports'

```

Disclosure: I'm a Forena co-maintainer.

# Answer
> 0 votes
I have found a format that works in settings.php. It is actually shown in snippet form in the linked documentation but not fully expanded on.

```
global $_forena_repositories;
$_forena_repositories['source1'] =
  [
    'path' => 'sites/all/forena_repos/source1',
    'title' => 'Source1',
    'data provider' => 'FrxPDO',
    'uri' => 'mysql:host=mydb.site.localhost;dbname=source1;charset=UTF8',
    'user' => 'root',
    'password' => 'changeme',
  ];
$_forena_repositories['source2'] =
  [
    'path' => 'sites/all/forena_repos/source2',
    'title' => 'Source2',
    'data provider' => 'FrxPDO',
    'uri' => 'mysql:host=mydb.site.localhost;dbname=source2;charset=UTF8',
    'user' => 'root',
    'password' => 'changeme',
  ];

```

---
Tags: forena
---


# Question
Title: How to print taxonomy terms field in node templates?
How can I display node taxonomy terms field in node templates of Drupal 8?

We do this in Drupal 7 by add this code to node.tpl.php file:

```
print render($content['field_tags']);

```

I tried adding the below code in Drupal 8:

```
{{ content.field_tags }}

```

but with this code have problems:

1. If I add some styles or make some changes to `field--node--field-tags.html.twig` file these changes displays in all content types also.
2. If I don't want to show default taxonomy terms in the bottom of article nodes (I want to move and show taxonomy terms in the top of the article) and I assign "Hidden" value in "Administration\>Structure\>Content types\>Article" in "Format" section, this settings cause to not displays all the taxonomy terms fields in throughout of the article nodes at all.
3. Taxonomy terms **Label** always display even if no tags added to the node. How can I show taxonomy terms label and their values only when have been added any tags to it?

# Answer
> 3 votes
To answer the questions:

> If I add some style to field--node--field-tags.html.twig file that's also displayed again in node.html.twig file?
>
> If I don't want to show default taxonomy terms in end of an article node and i assign "hidden" value in "Administration\>Structure\>Content types\>Article" in "Format" section, that's also not displayed?

Both questions are connected and I think they come from a D7 background. In D7 when you print a field, it will be hidden from further output. This is not the case in D8. If you print a single field in a node twig:

```
{{ content.field_tags }}

```

You have to exclude it later when the complete content is outputted:

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

```

That is the only way. You can't hide it in the "Format" section, because then you have no field content you can use for the first twig statement.

> It always displays Taxonomy Terms even if no tags added to node. How can I show only Taxonomy Terms name and their links without any previously added style, if added any tags to node?

You can configure if the label will be displayed in the "format" section mentioned before. But you can also use

```
field--field-tags.html.twig

```

to change wether and in what form the label should be displayed. You can also use this twig to theme the html and prepare for css. You need some css for nice tags.

# Answer
> 8 votes
1. Yes, this will be used in all nodes with that field ! You could add a contenttype specific node.html.twig (see next point), or if you only want to add classes, do it in `template_preprocess_node(&$variables)`, add classes to `$variables['content']['field_tags'][x]['attributes']['class'][] = 'my-style'`, you can check there for the contenttype.
2. What are you rendering ? If you render the node's field, you'll only get the assigned terms ?! For custom node-specific theming you could use something like this in

**node--type-your\_contenttype.html.twig**:

```
   {% for item in content.field_tags %}
      {% if item['#title'] %}
        <a href="{{ item['#url']}}" class="link-item">{{ item['#title']  }}</a>
      {% endif %}
    {% endfor %}

```

Also `{{ item['#options'].entity.url() }}` or `{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': item['#options'].entity.tid}) }}` could be used to retrieve the URL.

---

# Regarding your icons

Use tid or parent and name it like icon-34. Access it in twig like: item\['#options'\].entity.parent or item\['#options'\].entity.tid.

> But I would recommend the use of a preprocess function to add a key-value pair to each item array where you set the name. For example from a field you added to your taxonomy. You could then access it in twig like `{{ item.key }}`

# Answer
> 5 votes
Displaying the name of a single term associated with the node:

```
<div class="term-display">{{ node.field_my_taxonomy.entity.name.value }}</div>

```

Looping through list of term names within that taxonomy (if you have multiple values):

```
{% for item in node.field_my_taxonomy %}
  <div class="term-display">{{ item.entity.name.value }}</div>
{% endfor %}

```

---
Tags: theming, 8, nodes, entities, taxonomy-terms
---


# Question
Title: Multiple database group users for one database
For a blog post, I have db design of 1 database in D7, the database contains multiple database users:

**Anonymous** \- Only Read privilege on Database
**Writer** \- CRUD privilege on Database
**Admin** \- Has all privilege to Database

How do I achieve this in Drupal 7 ? The settings.php in Drupal has only one database connection section, as I'd need to connect the database from all 3 database users, and change the database user when they log in, like when Admin logs in, he'll also be admin database user, and so on...

# Answer
> 0 votes
I haven't ever tried this so it's just theory...

* Define 3 different connections in settings.php, with the relevant credentials. The default database should login as the user with only read access.
* The connection key for the other 2 should be the name of the relevant Drupal role. (in reality they can be anything you choose to map against but for this example...)
* Write a custom module to implement `hook_boot()`, with code like this:

```
function MYMODULE_boot() {
  global $user;
  if (in_array('admin', $user->roles)) {
    db_set_active('admin');
  }
  elseif (in_array('writer', $user->roles)) {
    db_set_active('writer');
  }
  else {
    db_set_active(); // Use the default
  }
}

```

As I say I've never tried that but it feels like it would work. I'm also not sure it would be considered 'best practice'. The code could be made a lot more generic as well but I'll leave that up to you :)

You need to bear in mind that unless you lock down Drupal's own permissions to match those of the DB CRUD permissions *exactly*, your users may well get exceptions when they (or indeed the system on their behalf) tries to write to the database.

Actually I'm thinking this out as I'm going along and I'm not sure a situation exists where Drupal wouldn't try to write to the database during a bootstrap. I'll leave this code in as an example in case you manage to get it to work, but my gut instinct is you might be out of luck here.

# Answer
> 1 votes
Although the question is a little unclear, it sounds like you just need 3 roles in your Drupal install

1. Administrator
2. Writer
3. Anonymous ( built-in )

You can add the roles at `/admin/people/permissions/roles` and configure access permissions for each role, regarding node creation etc, at `/admin/people/permissions`

# Answer
> 1 votes
You seem to make the assumption that, since the anonymous users are not allowed to create content, there isn't any database table that is written for anonymous users, which is not true. There are some database tables that are written, even when the user is the anonymous user, or another user who is not allowed to create any node; those tables include:

* Cache tables
* The cache\_form table, which contains data about any form shown to the user, including the login form
* The batch table, used when a module uses batch operations to complete an operation
* The flood table, which is also used to register the IP of those users who try to login using a username, but a wrong password, too much times
* The semaphore table, that is used to to coordinate long-running operations across requests
* The sessions table, which contains session data

Drupal, and any module require write access to the database. Without that, Drupal doesn't work.

If you are concerned about security, you should be sure to use modules without security issues, and to update Drupal, or modules, when there are fixes for security issues.

# Answer
> 0 votes
Before we start, we must be aware of the fact that there are few tables of Drupal, which gets updated when an anonymous user makes request to Drupal 7:

The list goes below, on analysis, which requires more than SELECT privileges for an Anonymous user:

cache, cache\_\*, watchdog, semaphore, flood, sessions

Any Other depending on Contrib Modules you use, like ctools\_css\_cache Enable Query Log in your Database to observe what other tables require write access

To enable in Mysql:

```
SHOW VARIABLES like 'general%'; // To see global variable is enabled or not
SET GLOBAL general_log = ON;

```

Create Two users for your database, the one by default is the 'root' and the other of your choice like 'readuser'.

```
CREATE USER readuser identified by 'your password';
GRANT SELECT ON DATABASENAME.* TO readuser;
GRANT SELECT, INSERT, UPDATE, DELETE ON DATABASE_NAME.tablename TO readuser;

```

\*Change DATABASE\_NAME with yours and tablename with the list mentioned above.

Update Database Configuration in settings.php in the Drupal installation folder.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database_name',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

$databases = array (
  'readuser_db' =>
  array (
    'default' =>
    array (
      'database' => 'database_name',
      'username' => 'readuser',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

Multiple Database Configuration reference: https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-connect-to-multiple-databases-within-drupal

Create a Custom Module and name it **db\_user\_switch**

create two files: db\_user\_switch.info and db\_user\_switch.module

db\_user\_switch.info:

```
name = "DB USER SWITCH"
description = "A Module to Switch Database Users."
core = "7.x"

```

db\_user\_switch.module:

```
// hook_init implementation
function db_user_switch_init(){
    if (!user_is_logged_in()) {
        db_set_active('readuser_db');
    }
    else {
        db_set_active();
    }
}

// hook_form_alter implementation
function db_user_switch_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block' :
      array_unshift($form['#submit'], 'db_switch_onlogin');
      break;
  }
}

//Custom Login Form Submit Handler
function db_switch_onlogin($form, &$form_state) {
  db_set_active();
}

```

Enable the module and test, it should work.

For Reference see other posts: https://gist.github.com/CashWilliams/901f16e32b3d9f77a15f What MySQL privileges would a read-only drupal db user need

---
Tags: 7, database
---


# Question
Title: Output data of different content types in same page
I have two content types :

* Content type 1 named `book` with two fields `author` and `language`
* Content type 2 named `movie` with two fields `date` and `resolution`

In `my-theme/templates/page.html.twig` I want to render a first section with all the books and a second section with all the movies :

```
<div id="first-section">

<h3>Book Author 1</h3>
<p>Book Language 1</p>

<h3>Book Author 2</h3>
<p>Book Language 2</p>

<h3>Book Author 3</h3>
<p>Book Language 3</p>

</div>

<div id="second-section">

<h3>Movie Date 1</h3>
<p>Movie Resolution 1</p>

<h3>Movie Date 2</h3>
<p>Movie Resolution 2</p>

<h3>Movie Date 3</h3>
<p>Movie Resolution 3</p>

</div>

```

How can I achieve that in Drupal 8 and Twig, is it mandatory to use `pre-processing` and provide the template with the variable, should I create `views` or `blocks` and render them in my page... What is the correct way to do that?

A concrete example will be much appreciated !

```
<div id="first-section">
    {% for book in books %}
            <h3>{{ [Book Author Here] }}</h3>
            <p>{{ [Book Language Here] }}</p>
    {% endfor %}
</div>

<div id="second-section">
    {% for movie in movies %}
            <h3>{{ [Movie Date Here] }}</h3>
            <p>{{ [Movie Resolution Here] }}</p>
    {% endfor %}
</div>

```

# Answer
> 1 votes
These types of problems are usually solved using Views.

You can create a single Page Display in Views listing the two Content Type nodes. Set the Page Path to what your link to that page to be. Add Sort Criteria by Content type so all the `book` nodes appear before the `movie` nodes (add more Sort criteria if necessary after that one). Make sure you set the Fields to be Hidden if Empty, since the two CTs you want to list don't share any Fields. Set that under each Field settings, and under Format settings.

Another, probably more common way to build the lists is to **create two different Views Displays, one for each Content Type**. For example you can create a Page Display to list only the `book` nodes with the two related Fields, then add Attachment Display in the same View and override it to show only `movie` nodes. Also override the Fields to show the two Fields you have on `movie` CT, instead of the two Fields from the `book` CT. Set the Attachment to show on the Page Display.

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


# Question
Title: Create multiple basic pages with different fields
I have a question to create a site in Drupal 8.

It is a website with about 60 basic pages, but each of them has different relationships, paragrphs, media.

My question is, how can I assign different fields per page and that the type of content does not grow monstrous? I am trying to reuse fields, but it has been very complicated for me.

# Answer
> 0 votes
IIUC you need the Bricks module. This module is similar to Paragraphs but a lot more abstract and allows for the customized options you mention.

You will have to create all the possible "Bricks" that can be found on your pages, then it won't be difficult to create each page with the custom structure it's supposed to have.

You don't have to use the Layout builder if your cases aren't that complex. The most important thing is to create some strategy around your different cases, analyze your needs so you know what different combinations need to be created. Go for the simplest possible solution, don't overcomplicate needlessly or you'll create a mess that is difficult to maintain.

---
Tags: 8
---


# Question
Title: Selecting an SVG as an Image Field value
I have a Content Type, News, with an Image Field, News Icon.

When the field settings are viewed at /admin/structure/types/manage/news/fields/node.news.field\_news\_icon

I have supplied SVG as one of the allowed types. I have also tried allowing only SVG.

We also have IMCE in use so I have SVG set up in the IMCE config like so at /admin/config/media/imce I have also tried using a list separated by spaces including SVG.

The Widget settings for the field at /admin/structure/types/manage/news/form-display allow for the IMCE manager to be enabled. I have tried disabling but it did not resolve the issue.

The widget displays and lists allowed types but no SVG.

IMCE allows upload of SVGs but when selecting one as the news\_icon I get

The normal (non-IMCE) file browser gives the following when an SVG is selected for upload:

Is there a deeper setting I am missing to get SVG included in the list of allowed extensions for use as an Image Field value?

# Answer
AFAIK the jpg/png/gif limitation is hardcoded in the image field, you can't solve this (only) with configuration.

SVG Image allows `.svg` files in core's image field. You can use the standard image formatter with it (or better: you must use the standard image formatter, it will not work with Focal Point or similar)

SVG formatter uses the file field and provides an SVG formatter for the file field.

Both also work with media entities, but I've not tested them with IMCE yet.
> 4 votes

# Answer
SVG Image Field is an alternative to SVG Formatter and SVG Image that is worth a try.

Some of the advantages of this module over these other two:

* Unlike SVG Formatter, you may set custom alt text on SVGs. SVG Formatter relies on core file field under the covers, which does not support alt at the database schema level.
* Unlike SVG Image module, you may still use Crop API, Focal Point, and other raster-based image modules on your normal image fields without affecting SVGs because SVG Image Field provides a separate field type and doesn't alter or touch regular core image field. The SVG Image module modifies core image fields to allow SVG files to be uploaded along side raster-image files like PNG, JPG, GIF, but comes with some costly tradeoffs and limitations.
* Far less configuration required out of the box: With SVG Formatter and SVG Image modules, the site builder must take additional steps to configure their fields to display all images appropriately, eg adding SVG extension to the file field settings, selecting a field formatter, playing with and testing formatter settings with different image types to see what breaks.
* Less end-user confusion and error states when trying to combine with other image types: With SVG Formatter, if user uploads non-SVG file it will break output. This isn't possible with SVG Image Field, because the file extensions are limited to only SVGs.
* Similar to the above, with SVG Formatter, if user uploads png and the field is configured with an inline output as the formatter, it will break output.
* SVG Image Field has an image preview feature on file upload out of the box. SVG Formatter does not.
* For existing installations, there are fewer opportunities to break the site with a misconfiguration. SVG Image Field solves the specific SVG use case, and doesn't interfere with other existing image field configs.

If you happen to be using Media in core, and Media Library check out my other post which explains how to set up SVG Image Field with Media module to end up with a single Media field on your node that can reference either Images or SVGs.
> 2 votes

---
Tags: 8, media
---


# Question
Title: After update 8.7.0 seven admin theme can't find icons
I updated my Drupal 8.6.15 \> 8.7.0 After updated page not found error keep coming. (I attached photo below)

It happens only in Admin theme, when I change admin theme to default theme, errors are gone. I installed a new test site with 8.7.0. but no error has happened. I tried to change core folder, theme folder. and icon files are still in the same location. I'm really confusing now. I tried to revert older version of drupal core. when it happened errors are gone but my drupal has problem. (DB is still has information of newer version I guess..) I think path of icon is wrong. error shows me wrong location.

I guess nothing wrong with new core version. but something has happened with my previous settings which I never know. anyone can help me?

# Answer
> 1 votes
## Suggestions

I see that you are new to the community, so welcome. Here are some suggestions:

1. Make sure you performed the updates correctly (preferably using composer)
    * I see that you've already cleared cache (:
2. See if the files are actually there in your file system.
    * If you're not getting this problem on your dev env and only getting it on your server, see if the files are getting uploaded properly.
    * I had a similar problem and the reason was because of a `.gitignore` entry which was ignoring the icon files, so they were not getting committed and as a result, they were not being uploaded to the server.
3. If the SVG files exist on your server, see if you can access them by typing an absolute URL to those files
    * If not, then maybe there's something in your `.htaccess` or in your server config which is preventing you from seeing SVG files.

If all of the above don't work, please post a comment and I'm sure me / someone else will surely help.

# Answer
> 0 votes
After I compared all file that already committed in git and I found nothing was wrong. And I found one of extension of my chrome called "Dark reader" could be effected to my server. I don't know the reason. Dark reader effects to localhost and one of my drupal site. when I turned off, my site works well again without any errors. I think dark reader can only be adjusted result of display but It can also make some changes to my server response or request. if someone have same problem. please check your chrome extensions as well.

---
Tags: 8
---


# Question
Title: How do I load a field of a product in a custom module?
A customer want to have the possibility to use different discounts on products. I'm working with the price resolver and I'll give the possibility to manage different discounts with taxonomy terms. I added an entity reference field (field\_discount) to the product.

I'm writing the module that should look which discount is given to the product and then calculate the price based on the discount.

How can I load the value of *field\_discount* in my module?

I made now a lot of research and I tried many different things, but nothing worked.

# Answer
Have you tried?

```
$product->get('field_discount')->entity

```
> 0 votes

# Answer
Try

```
$product->field_discount->value

```
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: Why are the terms filled when they are actually empty?
Below is the JSON output of a product I am having the issue with:

```
  {
     "StkGrupKodu1" : "10090",
     "StokAdi" : "7 Parça Kombine Anahtar Takımı",
     "StkGrupKodu2" : "",
     "SiparisVerilebilir" : true,
     "StokMiktari" : 0,
     "StkGrupKodu4" : "",
     "StokTipiAdi" : "Ticari Mallar",
     "KDVOrani" : 18,
     "StokTipi" : "00000",
     "DovizCinsi" : "EUR",
     "Fiyat" : "34.00000",
     "StkGrupKodu3" : "",
     "StkGrupKodu5" : "",
     "PasifStok" : false,
     "EskiBilgileri" : {
        "EskiStokKodu" : "",
        "DegistirmeTarihi" : "1920-04-23T00:00:00"
     },
     "StokKodu" : "JBM50563"
  },

```

In this e-commerce system, I am consuming a web service and creating corresponding products. With a few products such as the above and a few others, I am having this dreadful issue. As you can see, StkGrupKodu2 and StkGrupKodu3 are empty but when I go to the edit page of the product, it's not empty. You can see from the screenshot below:

This is the code I am using to associate terms with products

```
foreach ($excel_products as $e) {
    $req = \Drupal::httpClient()->get("http://mitapp.mitacan.com/b2b/api/vStkLib/GetStkKodlist?UserCode=B2BUSER&StokKodu=".$e->stokkodu);
    $res = $req->getBody();
    $res = json_decode($res);
    $data = $res->Data[0];
    $sid = \Drupal::database()->select("commerce_store_field_data", "csfd")->fields("csfd", ["store_id"])->condition("default_currency", ($data->DovizCinsi == "TRL")?"TRY":$data->DovizCinsi)->execute()->fetchCol();
    $product = Product::create(["type" => "default"]);
    <snip>
    if (!empty($data->StkGrupKodu1)) {
        $tid_1 = \Drupal::database()->select("taxonomy_term__field_stok_grup_kodu", "ttfsgk")->fields("ttfsgk", ["entity_id"])->condition("field_stok_grup_kodu_value", $data->StkGrupKodu1)->execute()->fetchCol();
        $tid_1 = (!empty($tid_1[0]))?$tid_1[0]:"";
    }
    if (!empty($data->StkGrupKodu2)) {
        $tid_2 = \Drupal::database()->select("taxonomy_term__field_stok_grup_kodu", "ttfsgk")->fields("ttfsgk", ["entity_id"])->condition("field_stok_grup_kodu_value", $data->StkGrupKodu2)->execute()->fetchCol();
        $tid_2 = (!empty($tid_2[0]))?$tid_2[0]:"";
    }
    if (!empty($data->StkGrupKodu3)) {
        $tid_3 = \Drupal::database()->select("taxonomy_term__field_stok_grup_kodu", "ttfsgk")->fields("ttfsgk", ["entity_id"])->condition("field_stok_grup_kodu_value", $data->StkGrupKodu3)->execute()->fetchCol();
        $tid_3 = (!empty($tid_3[0]))?$tid_3[0]:"";
    }
    $tids = [$tid_1, $tid_2, $tid_3];
    $tids = array_filter($tids);
    <snip>
    foreach ($tids as $tid) {
        $product->field_stok_grup_adi[] = [
            "target_id" => $tid,
        ];
    }
  <snip>
}

```

What am I doing wrong or missing?

# Answer
Looks to be a PHP issue and not drupal. You're not clearing your $tid\_1,$tid\_2,$tid\_3 values within your for loop

So when $data-\>StkGrupKodu1 isn't set for example the value of $tid\_1 is still that of the last time $data-\>StkGrupKodu1 did exist.

You could declare your $tid\_1,$tid\_2,$tid\_3 variables at the top of your foreach loop so they get set similar to what you're doing if the database results null
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: The specified database connection is not defined: legacy
I used Drush command to migrate

```
drush migrate-upgrade --legacy-db-url=mysql://root:@127.0.0.1/tsa_v8 --legacy-root=http://127.0.0.1/new_projects/tsa --configure-only

```

But it return error: **The specified database connection is not defined: legacy**. How can I fix this error?

# Answer
> 1 votes
Try using the `--legacy-db-key` option which allows you to use a $databases array, with matching key, defined in `settings.php`.

So, your drush command can be sth like:

```
drush migrate-upgrade --legacy-db-key=tsa7 --legacy-root=http://tsa7.com --configure-only

```

And in your `settings.php` or `settings.local.php`:

```
$databases['tsa7']['default'] = array(
  'database' => 'tsa7',
  'username' => 'tsa7_user',
  'password' => 'tsa7_pass',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

---
Tags: migrations
---


# Question
Title: How to populate select field from View result like in
In a custom content entity, I have defined this field

```
$fields['from_seliste_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Offreur'))
  ->setDescription(t('Le SÉListe qui a rendu le service (qui reçoit les graines)'))
  ->setSetting('target_type', 'person')
  ->setSetting('handler', 'views')
  ->setSetting('handler_settings', [
    'view' => [
      'view_name' => 'sel_selistes',
      'display_name' => 'entity_reference_1',
    ],
  ])
  ->setDisplayOptions('view', array(
    'weight' => $weight,
  ))
  ->setDisplayOptions('form', array(
    'weight' => $weight,
    'type' => 'options_select',
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(TRUE);

```

In the corresponding form, the field appears as wanted as a dropdown list populated with the result of the View `sel_selistes`:

I'd like to create another form with the same functionality.
How should I code the field in the form?

```
$form['mySelectField'] = array(
  '#type' => 'select',
  '#options' => [], <-- ??????
  '#title' => $this
    ->t('whatever'),
);

```

# Answer
> 1 votes
I don't have time to provide an exact answer, but something along these lines.

```
// Programmatically execute view
$view = views_get_view('sel_selistes'); //  view machine name
$view->set_display("entity_reference_1"); // view display name
// $view->set_arguments($arg) // looks like you don't have arguments.
$view->execute();

$view_results = []; // create array
// loop through results
foreach ($view->result as $row_id => $row) {
  // some php magic so you add to array like this $view_results[$nid_value] = $some_field_row_value;
}

$form['my_select_field'] = array(
  '#type' => 'select',
  '#options' => $view_results,
  '#title' => $this
    ->t('whatever'),
);

```

---
Tags: 8, forms
---


# Question
Title: The following SSH command responded with a non-zero exit status (drupal-vm)
My environment:

* Vagrant 2.2.4
* VirtualBox 6.0.6r130049
* ansible 2.7.10 config file = None

Mac OS Mojave (10.14.4)

I use drupal-vm to build my local development environment.

I cloned this repo and run `vagrant up`. After first time `vagrant up` everything was fine and Drupal was installed correctly. Then I did `vagrant halt`, to stop my VM.

After I do `vagrant up` again I get this error:

```
==> drupalvm: [vagrant-hostsupdater] This operation requires administrative access. You may skip it by manually adding equivalent entries to the hosts file.
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

 setup

Stdout from the command:

Stderr from the command:

bash: line 5: setup: command not found

```

What do I have to do and what's wrong?

# Answer
It seems to be related to a bug in VirtualBox 6.0.6. I downgraded to 6.0.4 and it now works.

Source: https://github.com/dotless-de/vagrant-vbguest/issues/278#issuecomment-486505824
> 0 votes

---
Tags: 8, composer, virtual-machine
---


# Question
Title: Running Drupal's drush cron jobs with a newer PHP version from Software Collections
How do you run Drupal's `drush` cron jobs when your server has a newer PHP version installed from Software Collections?

The server is running Scientific Linux 7, which comes with PHP 5.4, but we need, and have installed, PHP 7.1 using the Software Collections `rh-php71` package. Apache and therefore Drupal work fine with PHP 7.1, but we also need to add the drush cron jobs to our crontab, and ensure that drush is using the newer version of PHP when it does so. We have tested to see if drush (we have drush 8.1.10 installed) will run with the default PHP 5.4, just in case, but the cron jobs understandably crash with errors.

We have tried to test the cron command (in the way that you would normally attempt to run a command within a scl wrapper), by running the following as root:

```
scl enable rh-php71 drush cron -r /data/webs/www/siteroot

```

but this will not run, returning the error:

`Unable to open /etc/scl/conf/drush!`

Further testing (in a terminal) shows that we can however successfully run the drush command within a subshell which is within a scl wrapper:

```
scl enable rh-php71 bash
drush cron -r /data/webs/www/siteroot
exit

```

Is there some way that we can run the necessary drush commands just as a 'one-liner' in the crontab, or do I have no option but to have to create a separate shell script containing the above commands, and call that as the cron job command instead?

(I have also asked this question on Unix.SE, as it seems more of a Linux question than a Drupal one as such, but have had no responses.)

# Answer
> 0 votes
After reading a more technical section of the Software Collections guide it turns out that when trying to run a *command which has arguments* within a `scl` wrapper, you need to enclose the command in single quotes or separate it from the wrapper part of the line with two minus signs:

> If you are running a command with multiple arguments, remember to enclose the command and its arguments in quotes:

`scl action software_collection_1 software_collection_2 'command --argument'`

> Alternatively, use a -- command separator to run a command with multiple arguments:

`scl action software_collection_1 software_collection_2 -- command --argument`

My drush command runs successfully now.

---
Tags: drush
---


# Question
Title: Migrate into Multi-value Checkbox from CSV
**Update:** Turns out typos suck. But added an answer to this as well, in case anyone ever stumbles upon this...

I'm running into a bit of an issue using Migrate API. I thought I had a fairly simple use-case, but am unable to actually find an example for this particular instance.

I have a CSV I'm importing, utilizing the `migrate_source_csv` module. My migration was working just fine, but now I need to add a `field_dealer_type` field. **This field is a multivalue checkbox. In the CSV, it's represented in a single `dealer_type` column, separated by commas (I've also tried other delimiters with no success).**

A couple example rows of my CSV would look like:

```
id,name,city,dealer_type
1,Sample Location,Cool City,"trucks,motorcycles"
2,Another Location,Second City,trucks

```

The CSV is well-formatted, wrapping the `dealer_type` column in quotes when necessary.

However, I'm not able to get these to import properly into my nodes. I've verified the values through the CSV are valid options in the field definition as well (trucks, motorcycles).

I've started with the `explode` plugin, as other examples use that as well, but I know I'm missing a follow-up processing. I've seen example using Taxonomy and `entity_generate`, but that doesn't fit my use-case. I also have the `migrate_plus` module installed, for clarity.

```
langcode: en
status: true
dependencies: {  }
id: dealers_csv
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: default
label: 'Import Dealers'
source:
  plugin: csv
  path: sites/default/files/dealer_locations.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: 'Unique Id'
    -
      name: 'Dealer Name'
    -
      city: City
    -
      dealer_type: 'Dealer Type'
process:
  title: name
  type:
    plugin: default_value
    default_value: dealer_location
  field_dealer_name: name
  field_dealer_city: city
  field_dealer_type:
    plugin: explode
    limit: 2
    delimeter: ','
    source: dealer_type
destination:
  plugin: 'entity:node'

```

# Answer
Turns out typos can send you down a completely misguided rabbit hole!

Within the `explode` plugin, the property should be `delimiter`, not `delimeter` (incorrect spelling).

After that switch, things are working great. Yay.
> 1 votes

---
Tags: migrations
---


# Question
Title: Getting a view of unique years of a date field
I'm tasked with creating a Year filter for our press releases page. We're using the `Article` content type, to which we've added a field called `Release Date`.

We have the press releases as a block display of a view of articles. Using this question, I was able to add a contextual filter that would accept a four-digit year.

Now I need to make the UI widget for the user to specify the year to filter on. I want it to be populated by the `Release Dates` of the article nodes, so that we automatically have all the years appearing in the filter, and don't have to manually add a new one when a new year rolls around.

However I'm having difficulty finding how to get the distinct values of the year part of the `Release Date` date field. I've created a display of just the release date field, and set the "Date format" to `HTML Year (2019)`. I added aggregation, and for the Aggregation settings of the field, the "Aggregation type" is `Group results together`, and the "Group Column" is `Value`. I've also set checked `Distinct` in query settings.

However, when I look at the preview, I see a number of repetitions of the year. When I add in the full `Release Date` field, I see that I am getting one year per distinct date in that year. It seems that the query is pulling each unique date (which is all Article nodes-- none of them share a date), and then doing the formatting (to show only the year) *after* the select has been performed.

I looked at the Query preview, and it seems that this is indeed what is happening:

```
GROUP BY node_field_data.nid, node__field_release_date_field_release_date_value, node_field_data_created

```

I don't understand why it's grouping first by nid, and then also the created date at the end.

FWIW here is the entire query:

```
SELECT DISTINCT node__field_release_date.field_release_date_value AS node__field_release_date_field_release_date_value, node_field_data.created AS node_field_data_created, node_field_data.nid AS nid, MIN(node_field_data.nid) AS nid_1
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_release_date} node__field_release_date ON node_field_data.nid = node__field_release_date.entity_id AND node__field_release_date.deleted = '0'
WHERE (node_field_data.status = '1') AND (node_field_data.type IN ('article'))
GROUP BY node_field_data.nid, node__field_release_date_field_release_date_value, node_field_data_created
ORDER BY node__field_release_date_field_release_date_value DESC, node_field_data_created ASC

```

Is it possible to get this type of result set with Drupal 8 views? If so, what settings do I need? Is there a module or extension I need to employ?

**Edit** User prkos suggested using an exposed filter, perhaps with the `better_exposed_filter` module. I've since gone down this alley, and it doesn't seem to meet the requirements. The basic problem is that, since views only looks at the entire date value, I can't specify a year to filter on at all (the interface and options for exposed filters is completely different from contextual filters). It also seems to run in to the problem that it can't auto-populate filter widgets with unique years, which is the issue I'm asking about in this question.

When I add an exposed filter, a "Single filter" type only allows entire dates, or relative dates:

When I hard-coded a value (2015) to test, as in the screenshot above, the view returned no results. This is because the filter is turning the year into a particular date in the query:

```
AND ((DATE_FORMAT(node__field_release_date.field_release_date_value, '%Y-%m-%d') = DATE_FORMAT('2019-05-07T20:15:00', '%Y-%m-%d')))

```

When I look at Group Filters, there seem to be two issues: 1. groupings must be manually specified, which is the sort of maintenance I'm looking to avoid, and 2. it still only accepts an entire date, and can't handle a year specification.

I also installed `better_exposed_filters`, but it doesn't seem to provide any of the features I'm looking for.

---

**Edit 2** Following the instructions in the first half of prkos' answer, I was able to get a list of unique year values:

But, I don't see how to use it as a filtering widget for end-users. The results are links, but they each only link to the `/press-releases` URL. Because I'm getting the contextual filter value from a query parameter, I need the links to look like `/press-release?year=2014`. But, because they are summary results from the contextual filter, and not fields, I can't re-write them.

So I guess this technically answers my question of how to get a view of unique years, but it doesn't give me something that I can work into a usable UI widget. I'm going to accept this answer, and ask about how to create the useable widget in another question.

---

**Edit 3**

As per prkos' suggestion, I looked at the summary results on the page, instead of just the view preview (I was pretty sure I had done this earlier, but of course you should always double-check your work).

I found that the links were not automatically populated with the value of the filter.

Here my mouse is hovering over the '2014' in FF. The screenshot doesn't capture the mouse cursor icon, but you can see which link is being hovered over, because its styled as a darker magenta color than the others:

Another test in Chrome, hovering over '2017':

So in the tests above, I was testing the summary view in the header of the press releases block. To make sure this wasn't a problem with a view-within-view, or anything, I copied the summary block display as a page. The page showed the same behavior:

Each of the above views have the same Base Path value, `/press-releases`. When I tried removing the Base Path value, then there were no results, summarized or other, as prkos warned.

I don't know why the summary links on the page display were going to `/year-filter-test`-- that's the path of that page display.

# Answer
> 1 votes
I may be misunderstanding what you're trying to achieve but looking at your screenshots I don't see why you wouldn't be able to achieve what you're after.

## Use the Summary option on the Contextual Filter

You mentioned you got the Contextual filter to take the year as an argument (in another question). All you have to do is use the Summary option of that filter to do it all for you.

It will "see" what years are present in your results for that particular field, list those years as links, you can even opt to show how many results there are under each year, and when you click through one of those links you'll see the results filtered for that year alone.

Here is what adding the Contextual may look like:

Here's how you configure it:

You *must* include the Base path if the Page display you're using isn't the first one in your Views, otherwise it won't work.

You can also set the `Specify validation criteria` further below to `Date format`, and some other options depending on your needs.

Here is what the results may look like:

## How to group Date ranges Filter

This isn't what you're after because it requires adding each year manually, but since you posted the screenshot I'll post what the correct configuration for that should look like:

You have to use `Is between` Operator, not the `Is equal to` one. The date you enter is in the **CCYY-MM-DD HH:MM:SS** format, so when you enter `2017` you're actually telling to show only nodes with that field set to `2017-01-01 00:00:00`.

You can omit the time if you set the correct dates for the In between, as I did, because of the assumed values.

Here is what the Exposed Grouped Date filter can look like:

The Better Exposed Filters was suggested to have more control over some Exposed filters, to show radio buttons/checkboxes instead of the Autocomplete field in some cases, since you wanted to be presented with options, instead of users typing them out on their own. You don't need it though when Contextual Summary is doing it for you.

# Answer
> 2 votes
I am going to go ahead and say **No, this feature is not available in Drupal 8 at at the time of this writing.**

Presently Drupal 8 views is not able to return unique year values of a date field. This is because the view selects the entire date of the date field, and then can only operate on those.

Also Exposed filters can only filter on a specific day date; it can't use an entire month or year (even though contextual filters has this ability, exposed filters does not seem to).

If this answer becomes outdated or is incorrect, please add the answer.

---
Tags: views
---


# Question
Title: Create a view on a entity using criteria on another entity
I'm trying to this done :

I have two entities

1) Listing Details 2) Listing Premium Settings. This entity references the first Listing Details entity.

In the second Entity I have referenced entity 1 Listing Details, added with fields for a StartDate and a EndDate.

I would like a view on Entity 1 where I will use the StartDatet and EndDate of Entity 2 as a filter.

I have tried contextual, I have tried Relationships, but I guess I do not graps the essences of both ... :-(

Anyone who can help me get this done ?

I use Drupal 8.7. I am a newbie.

Alex

# Answer
> 0 votes
A view of entity one in relation with entity 2 referenced field may work, but maybe you can try the other way around:

* Create a view of Entity 2 (Listing Premium Settings) with field titles or nid that you exclude from display (and maybe remove at the end)
* Create your filters at your convenience of time
* Define your relationship: content referencing the first entity
* Then add the fields of entity one you wish to display in your view, using the relationship in these fields.

In that sense it might give you more control on the filters which are attached to entity 2.
In the other sense (entity 1 relationship to entity 2) it gives you more control on the fields of entity 1 to display in case of multi-value field for example.

# Answer
> 0 votes
Your Listing Premium Settings is the "child" and the Listing Details is the "parent" through the ER (entity reference) relationship.

You want to create a list of "child" node information on the "parent" nodes. You do that with the help of a Contextual filter for the ER field that connects the two types.

## List "ER Child" info on "ER Parent" nodes

1. Create Views with Block display listing the "child" nodes (in your case it's Listing Premium Settings)
2. Add the Contextual filter for the ER field and configure it (*do not* use any Relationships if you have them added in Views): `When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Content**
**Listing Details**

Adjust other options to your needs/preferences.
3. Optional: If you need to show some "parent" information in this Views you will need to add the Relationship for the ER field, and then use that Relationship when adding new Fields from the "Parent", but this isn't likely in your case because you're goal is to show "Child" node info.
4. Place the Block on Listing Details nodes and adjust the `Node from URL` and other Block options.

Now you will see the Listing Premium Settings nodes on Listing Details nodes, but only the ones that reference the node you're currently viewing.

---
Tags: views, 8, entities
---


title: How to get text from radio option value

text:
# Question
Title: How to get text from radio option value
How do I get the option text from the submitted value of the radio field in Drupal 8 webform submission? I have written a rule action condition on webform submission where I am storing data in a middle table.

Based on screen I am looking for Option Text from webform field. Current version: Drupal 8.6.15 & webform 8.x-5.2

# Answer
> 0 votes
Assuming Drupal 8 (since you didn't give a version), there are two parts to this.

Imagine this element in the form:

```
$form['some_field'] = [
  '#type' => 'radios',
  '#options' => [
    'option1' => $this->t('Option 1'),
    'option2' => $this->t('Option 2'),
  ],
];

```

The submitted value can be retrieved from $form\_state in your submit handler:

```
$radio_value = $form_state->getValue('some_field');

```

You can then use the value to get the text of the radio, from the $form element:

```
$radio_text = $form['some_field']['#options'][$radio_value];

```

---
Tags: 8, webforms
---


# Question
Title: Is this the proper way to add a 'class' attribute to a form date element
```
$form['stop_date'] = array(
  '#type' => 'date',
  '#title' => t('Stop Date'),
  '#default_value' => date("Y-m-d"), // default to today
  '#id' => 'stop_date',
  '#attributes' => array('class' => array('dateSel-Fld')),
  '#required' => true,
);

```

When using the #attribute property the form is not being rendered successfully.

# Answer
In Drupal 8, you can try this if you want to add certain attributes to the views filter (in my case, it is a select dropdown)

Add this to your mymodule.theme file

```
    function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $form['field_month_target_id']['#attributes']['class'][] = 'GAEventTrack';
      $form['field_month_target_id']['#attributes']['eventcategory'] = 'Category';
      $form['field_month_target_id']['#attributes']['eventaction'] = 'Action';
      $form['field_month_target_id']['#attributes']['eventlabel'] = 'Label';
    }

```

Of course you can add a checking to fit your needs =)
> 1 votes

# Answer
Yep.

Here's the references:

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#attributes

And a usage example:

https://api.drupal.org/api/drupal/modules!search!search.module/7
> 0 votes

---
Tags: forms, 8, datetime
---


# Question
Title: Set and Get $form_state with ajax button submit function?
In my case, I need to get a list of config files to show in a form element. Extending from this Drupal Answers Q/A using form\_state-\>set() inside ajax callback but cannot get the value back outside the callback, I see a suggested way of calling a static function in the submit.

However, I am missing some understanding of how to properly execute.

```
$list = '';

$form['fieldset'] = [
  '#type' => 'fieldset',
  '#prefix' => '<div id="wrapper">',
  '#suffix' => '</div>',
];

$form['fieldset']['list'] = [
  '#type' => 'item',
  '#title' => t('List'),
  '#description' => $list,
];

$form['fieldset']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#submit' => [static::class, 'customFunction'],
  '#ajax' => [
    'callback' => '::customCallback',
    'wrapper' => 'wrapper',
  ],
];

public function customCallback(array &$form, FormStateInterface $form_state) {
  $list = $form_state->get('list');
  $form_state->setRebuild(TRUE);
}

public static function customFunction(array &$form, FormStateInterface $form_state) {
  $form_state->set('list', $li);
}

```

How does one get $form\_state value into a form element from an ajax button submit function?

**Update**:

Here is what I have working for this case thanks to @No Sssweat.

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

  $form['fieldset']['list'] = [
    '#type' => 'item',
    '#title' => t('List'),
    '#description' => '',
  ];

  $form['fieldset']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    '#submit' => [static::class, 'customFunction'],
    '#ajax' => [
      'callback' => '::customCallback',
      'wrapper' => 'wrapper',
    ],
  ];

}

public function customCallback(array &$form, FormStateInterface $form_state) {

  $values = $form_state->getValues();
  $li = [];
  $config_path = drupal_get_path('module', $values['fieldset']['module_name']) . $values['fieldset']['directory_path'];

  if (is_dir($config_path)) {
    if ($dh = opendir($config_path)) {
      while (($fileName = readdir($dh)) !== false) {
        if (pathinfo($fileName, PATHINFO_EXTENSION) == 'yml') {
          $fileName = str_replace('.yml', '', $fileName);
          $li[] = $fileName;
        }
      }
      closedir($dh);
    }
  }

  $markup = new TranslatableMarkup(
    '<ul>@li</ul>', [
      '@li' => t('<li>' . implode('</li><li>', $li) . '</li>'),
    ]
  );

  $form['fieldset']['list']['#description'] = $markup;
  return $form['fieldset'];
}

public static function customFunction(array &$form, FormStateInterface $form_state) {
  // Empty.
}

```

But this avoids the question as asked.

# Answer
> 2 votes
Should be:

```
public function customCallback(array &$form, FormStateInterface $form_state) {
  $list = $form_state->get('list');
  $form['fieldset']['list']['#description'] = $list;
  return $form['fieldset'];
}

```

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


# Question
Title: Drupal 8: Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans" error after update
after updating Drupal 8 from 8.6.14 to 8.6.15 (twig v1.40.1) I suddenly get this kind of fatal errors:

```
 Uncaught PHP Exception Twig\Error\SyntaxError: "An exception has been thrown during the compilation of a template ("Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans".")

```

It happens in my custom theme, but also in `core/themes/classy/templates/views/views-mini-pager.html.twig`

Do you know how to solve this or what the origin is?

# Answer
According to https://www.drupal.org/project/drupal/issues/3051269 this is now resolved by the drupal team. Whatever caused the error seems to be fixed now in drupal 8.7.0
> 0 votes

---
Tags: theming, updating
---


title: Clearing cache takes "long time"

text:
# Question
Title: Clearing cache takes "long time"
I am absolutely new in Drupal. I am trying to set up my first "Hello world" module and I am playing with it. Every time I clear cache using Drupal Console, it takes 15 seconds, which is an eternity for me.

Is this normal, or did I need to change setting?

This is the output of `drupal site:status`.

```
 Drupal                         8.3.2
 Access to update.php           Protected
 Configuration files            Protected
 Cron maintenance tasks         Last run 41 minutes 54 seconds ago
 Database system                MySQL, MariaDB, Percona Server, or equivalent
 Database system version        5.5.5-10.1.21-MariaDB
 Database updates               Up to date
 Drupal core update status      Not secure! (version 8.7.0 available)
 Entity/field definitions       Up to date
 File system                    Writable (public download method)
 GD library                     bundled (2.1.0 compatible)
 GD library PNG support         bundled (2.1.0 compatible)
 Image toolkit                  gd

 Module and theme update status Out of date

 Node Access Permissions        Disabled
 PHP                            7.1.1 (more information)
 PHP extensions                 Enabled
 PHP memory limit               128M
 PHP OPcode caching             Enabled
 Random number generation       Successful
 Search index progress          100% (0 remaining)

 Trusted Host Settings          Not enabled
 Unicode library                PHP Mbstring Extension
 Update notifications           Enabled
 Upload progress                Not enabled

Web server
 Hash salt                      6X0M4mm-6Ui1Sgovc-emqgqvm2nJ1Ug-fYQYnJfxPniHHwdYMMcBHRBt1xwRtGMRRg7XbK1G3A
 Drupal Console                 1.8.0

 Database connection
 Driver              mysql
 Host                localhost
 Database connection dru
 Port                3306
 Username            root
 Connection          mysql//root:@localhost:3306/dru

 Themes
 commands.site.status.messages.theme_default bartik
 commands.site.status.messages.theme_admin   seven

 Directories
 Site root directory      C:\xampp\htdocs\dru
 Site temporary directory C:\xampp\tmp
 Default theme directory  /core/themes/bartik
 Admin theme directory    /core/themes/seven

```

# Answer
Yes, WAMP is not a good environment for Drupal 8. Use a different OS in a virtual machine. Either a Linux VM built from scratch or by a tool like Drupal VM, or a docker based tool like DDEV, Docksal, and Lando.

Which one to choose would be opinion based. Consider not only performance, but also that debugging is most effective, when the dev environment is as close to production as possible.
> 2 votes

---
Tags: 8, console
---


# Question
Title: Permission denied for a route implemented by a custom module
Hello I have the same problem with the following code:

first\_module.routing.yml:

```
first_module.content:
  path: '/first'
  defaults:
    _controller: 'Drupal\first_module\Controller\FirstController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

```

and the Controller:

```
<?php

/**
 *  @file
 *  Contains \Drupal\first_module\Controller\FirstController.
 */

 namespace Drupal\first_module\Controller;

 use Drupal\Core\Controller\ControllerBase;

 class FirstController extends ControllerBase {

   public function content() {
     return array(
       '#type' => 'markup',
       '#markup' => t('Hello world'),
     );
   }
 }

```

And I receive the same "Access Denied" error every time I try to access this page.

# Answer
As suggested to me from @berramou the solution is:

> Add \ to Drupal\first\_module\Controller\FirstController::content like \Drupal\first\_module\Controller\FirstController::content and clear cash. – berramou 17 mins ago
> 0 votes

---
Tags: page-controller
---


# Question
Title: Commerce 2.x multicurrency / multiprice setting
Is it possible to set two prices each with its currency for the same product so that it appears in two stores with correct price? For example, I have set up two stores one for Czech Republic with CZK as a currency and second one for Germany with EUR as a currency. Now I want to create a product (for example t-shirt) that should appear in both stores but with price for each store different. I haven't found a way to do that, could somebody please shed some light on this problem, or at least point me in the right direction, I am kind of lost here.

Thanks.

\[edit\] Still not found the correct way of resolving this problem. I have created a search index and view based on the documentation, the view has two pages each for one store. If I create a product with just one variation, price and currency, then publish it in one of the stores it all works as it is supposed to, but if I create product with two variations and two prices with two currencies, publish it in both stores then it doesn't work.

# Answer
The https://www.drupal.org/project/commerce\_currency\_resolver module will help you do this.
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: When I POST an image file via rest, response is 201: Object Moved, status is temporary
I'm attempting to POST images to Drupal 8 via the REST api. The creation is successful (201) and the images appear in the files list. However, there are problems. I'm not sure if they are independent of one another of is they are related.

1.The images are created with a temporary status. Would prefer "permanent".

2.The MIME type is set to "application/octet-stream" and the images don't render. I've discovered that by chaning the "uri" in the json object I'm posting to be an explicit uri like "public://photograph.jpg", the MIME type gets set to image/\* and this work.

This is the code i'm using:

```
<script>
    function getCsrfToken(callback) {              //get token
        jQuery
            .get('http://vhscms/cms/rest/session/token')
            .done(function(data) {
                var csrfToken = data;
                callback(csrfToken);
            });
    }

    function postImage(csrfToken, image) {         //post image
        console.log(image);
        jQuery.ajax({
            url: 'http://vhscms/cms/entity/file?_format=hal_json',
            method: 'POST',
            headers: {
                'Content-Type': 'application/hal+json',
                'X-CSRF-Token': csrfToken
            },
            data: image,
            success: function(data) {
                console.log('postNode success');
            }
        });
    }

    $('#image-save').click(function() {         //attach fcn to button
        getCsrfToken(function(csrfToken) {
            var $img = $('img[alt="image1"]');  //grab first image
            var imgSrc = $img.attr('src');      //grad base64 source
            imgSrc = imgSrc.replace('data:image/jpeg;base64,',''); //clean
            var package = {
                "_links": {
                    "type": {
                        "href": "http://vhscms/cms/rest/type/file/image"
                    }
                },
                "filename": [{
                    "value": "joggers.jpg"
                }],
                "filemime": [{
                    "value": "image/jpeg"
                }],
                "type": [{
                    "target_id": "image"
                }],
                "uri": [{
                    "value": "public://joggers.jpg"  //forces mime type img
                }],
                "data": [{
                    "value": imgSrc
                }]
            };
            postImage(csrfToken, JSON.stringify(package));
        });
    });

</script>

```

# Answer
# Suggestions

* I think `filemime` is autogenerated depending on the file you're uploading.
* To make the file permanent, have you tried sending the property `status: [value: 1]`?
    + A `status` of `1` indicates that the file is permanent.
> 1 votes

---
Tags: media, 8
---


title: How do I list all the users?

text:
# Question
Title: How do I list all the users?
I would like to list information about all users using `drush`.

There is `user-information`, but it shows information only about single user.

Are there any other solution?

# Answer
> 7 votes
There is recent sandbox project: Drush User List (by John) which should work for Drupal 6 & 7 (see GitHub).

Usage:

```
drush user-list

```

For other workaround, the following command with process substitution syntax should help:

```
drush uinf $(drush sqlq "SELECT GROUP_CONCAT(name) FROM users")

```

However it could fail in some cases (when users have some special characters in their name).

# Answer
> 14 votes
For Drupal 8 you could run the following command:

```
drush uinf $(drush sqlq "SELECT GROUP_CONCAT(name) FROM users_field_data")

```

The output will loke something like the following:

```
 User ID       :  1
 User name     :  admin
 User mail     :  info@example.com
 User roles    :  authenticated
                  administrator
 User status   :  1

```

# Answer
> 9 votes
As kenorb pointed out, there is a workaround via SQL-query.

And with a minor change, it becomes more robust to special characters in names - by using "uid" (integer) instead of the user-names:

```
drush uinf $(drush sqlq "SELECT GROUP_CONCAT(uid) FROM users")

```

*PS: Confirmed for Drupal 7 only.<br>PPS: Sorry for adding another answer, I can not comment yet.*

# Answer
> 3 votes
For Drupal 8, there is a Drush 9 command on Packagist, e.g.

```
drush users:list

```

> List all Drupal users in a table format. See `drush users:list --help` for filtering options.

# Answer
> 0 votes
Sorry... wrote this script for Drupal 8 remote machines with aliases; easily adaptable to local if necessary.

```
if [ $# -lt 1 ]
then
        echo "Usage : $0 sitealias [all/disabled/enabled] [rolename]"
        echo "Note: this only runs on Drupal 8 schema"
        exit
 fi

 ARG1=$1
 ARG2=${2:-all}
 ARG3=${3:-nothing}

 if [ "$ARG3" != "nothing" ]
 then
    ROLEWHERE='AND user__roles.roles_target_id="'$ARG3'"'
 fi

 case "$ARG2" in
    enabled)
        WHERECLAUSE='WHERE users_field_data.status="1" '$ROLEWHERE
        ;;
    disabled)
        WHERECLAUSE='WHERE users_field_data.status="0" '$ROLEWHERE
        ;;
    all)
        WHERECLAUSE='WHERE users_field_data.status LIKE "%" '$ROLEWHERE
        ;;
    *)
        WHERECLAUSE=''
        ;;
 esac

 QUERY='SELECT users_field_data.uid,users_field_data.name,users_field_data.mail,from_unixtime(users_field_data.login) AS "lastlogin",user__roles.roles_target_id,users_field_data.status FROM users_field_data LEFT JOIN user__roles ON users_field_data.uid = user__roles.entity_id '$WHERECLAUSE

 drush $1 sqlq "$QUERY"

```

---
Tags: drush
---


# Question
Title: Unpublished taxonomy term keep showing in main menu and contextual filter
I'am creating a Drupal 8 multilingual side, i have a main menu and a contextual filter that uses taxonomy term. in english version i wont translate all those taxonomy, so i dont want theim to be displayed on the menu neither on the contextual filter.

i've tried to uncheck the button "this translation is published" for the translation but the taxo keep showning on the site :/

Any help please?

# Answer
It is my understanding the Drupal’s multilingual will fall back to the default language, meaning that if a translation is not available, the asset will be shown or rendered in the default language. I don’t think there is a workaround for that.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Adding a custom data-attribute to a field in Views
In a view I need to add a custom data-attribute to the row output (just like classes are added). Simply rewriting the output doesn't work because XSS attribute filtering strips the attribute. How can I accomplish this in a reasonable way? These answers are for D7 and do not quite cover dynamic output:

Custom attribute in views fields

How to add data attributes to view list \<li\> tags?

# Answer
> 1 votes
To summarize for future reference:

You **can** add data attributes using Rewrite in Views Fields.

If you added a custom data-attribute but something isn't working, the problem might be in the value ;)

---

What gets stripped by the `filter_xss_admin()` on Rewrite is most notably the `<object>` tag and `style=""` attribute because users can submit malicious code through those.

It seems Views for D7 will have that check removed in the next release: Remove filter\_xss\_admin() from result rewriting because views editors are already trusted admins

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


title: Search by reference field target ID

text:
# Question
Title: Search by reference field target ID
I have a *Project* content type, which has a reference field to a *Contact* entity that has a *Client* bundle.

I can get the reference target ID from the node. I want to find the nodes that contain a reference to *Client* entities.

How should I be able to search in the node reference field target IDs to find the similar?

# Answer
Use entityQuery to search for referenced entities.

Let’s illustrate a couple of examples of querying for node entities using this object.

A very simple query that returns the published nodes:

```
function ecc_general_node_update(Node $node) {
    // Find the project for current client that are actives
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type','project')
      ->condition('field_project_status', 'Active')
      ->condition('field_client', $node->field_client->target_id);
    $searchNodes = $query->execute();
    var_dump($searchNodes);
}

```

The out put looks like this, just the nodes IDs appears:

> array (size=2)
>
> 106 =\> string '101' (length=3)
>
> 109 =\> string '104' (length=3)
> 1 votes

# Answer
This is often achieved using Views with a Contextual filter that pulls in the current node ID and uses it as the "parent" to find the "children" of that Entity Reference field.

Here is a similar question/answer with all the steps how to set it up:
List "ER Child" info on "ER Parent" nodes
https://drupal.stackexchange.com/a/280876/52224

Using Views is often the more maintainable solution. Using custom queries is sometimes used when Views query performance isn't good enough and needs to be optimized.
> 1 votes

---
Tags: 8, entities, search
---


# Question
Title: Get node based target id from entity reference
We have an `Article` content type which has an Entity Reference field called `field_document` that is linked to the `Media` bundle type of `Document`. In `mymodule` we need to write a hook that will take the current `field_document.id` (which maps to `Document.mid`) and return all the `Article` pages where `field_document.target_id = mid`.

**Goal**

* Take the current node id and retrieve the `Document` entity that is linked to by accessing `field_document`
* Using the `field_document` value, return other `Articles` that have the same value for `field_document`
* Perform the query in a `hook_preprocess_node()` hook.

**Question**

1. How can we retrieve all the nodes based on the $mid?

**When we tried**

We were able to return all `Articles`. However when we add `->condition('field_document.target_id, $mid)`, we get zero results even though we know there are `Articles` where the `field_document.target_id = $mid`.

```
function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1);

  $and = $query->andConditionGroup();
  $and->condition('field_document', $linked_document_id, '=');
  $query->condition($and);
  $results = $query->execute();

  // returns zero
  ksm($results);
}

```

We also tried using `$and->condition('field_document.target_id', $linked_document_id, '=');`, but that did not return any results either.

Additional steps we tried, but with similar issue.

```
 function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1);
    ->condition('field_document', $linked_document_id, '=');
  $results = $query->execute();

  // returns zero
  ksm($results);
}

```

# Answer
We found the issue, it was both duplicate data issue and syntax errors mentioned by @berramou. The fix to the query was changing `->condition('status', 1);` line to `->condition('status', 1)`.

We found that the test data included duplicate `media` entities so when the `->condition('field_document', $linked_document_id, '=');` was added, there were no results because the `entities` we were expecting were not in the table.

Sample test data:

* media entity (id=1) name --\> foo
* media entity (id=2) name --\> foo
* media entity (id=3) name --\> bar
* Article-\>field\_document-\>target\_id = 1

I was expecting `foo (id=1)` to be returned but I was receiving `foo (id=2)`. We have a specific requirement that `media entities` should be unique so after we merged the duplicate ones, the issue resolved.

```
function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1)
    ->condition('field_document', $linked_document_id, '=');
  $results = $query->execute();

  // returns results now
  ksm($results);
}

```
> 1 votes

---
Tags: 8, nodes, database, hooks
---


# Question
Title: Acquia Dev Desktop MySQL database troubleshooting on Mac OSX 10.11
I changed the Acquia Dev Desktop configuration, then when Apache web server and MySQL were restarting MySQL never got back online.

I have enabled the debug option in Acquia Dev Desktop. The logs don't show any clues:

* `/Applications/DevDesktop/piscript.log`
* `/Applications/DevDesktop/mysql/data/mysql.err`

**Workaround**

I am using the MAMP mysql in the meanwhile, it has this convenient shell script:

`/Applications/MAMP/bin/startMysql.sh`

# Answer
Manually starting the MySQL server:

`/Applications/DevDesktop/mysql/bin/mysqld --defaults-file=/Applications/DevDesktop/mysql/my.cnf`

Viewing the log:

`tail -50 /Applications/DevDesktop/mysql/data/mysql.err`

If everything went right you should see the MySQL green dot in the Acquia Dev Desktop GUI.
> 3 votes

# Answer
After spending time on searching for the solution. Below solution worked for me.

Open my.ini (my.cnf on linux-based systems and Mac)

Look for \[mysqld\]

Just below \[mysqld\] insert innodb\_force\_recovery = 1

Start MySQL Service

Stop MySQL Service

Remove the line from my.ini (innodb\_force\_recovery = 1)

Start MySQL Service
> 1 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: how to add a "preview" button to a webform submission
I am using version 8x-5.2 of webform. I cant see an option to add a preview button. Can someone explain where to add this button, or do i have to use a later version of the webform module to get this ? thank you .

# Answer
> 0 votes
in the webform you go to "settings" "form" and at the bottom there is an option for "Form Preview Settings"

---
Tags: webforms
---


# Question
Title: Use computed twig to get last item in a multi value composite field
I want to use a computed twig element in a webform to give me the value of the last item in a multi value composite field. the name of the field is destinations, and it has a departure\_date field and a country field .

if I use `{{ data.destination_and_date[data.destination_and_data|length].departure_date }}`

it only gives me the first one.

# Answer
> 1 votes
I think you just need to use Twig's last filter.

Below is an example of getting the last value from a multiple select element. This example can also be applied to multiple value composite element.

```
select:
  '#type': select
  '#title': select
  '#multiple': true
  '#options': days
computed_twig:
  '#type': computed_twig
  '#title': computed_twig
  '#template': "Values<br/>\r\n<ul>\r\n{% for value in data.select %}\r\n   <li>{{ value }}</li>\r\n{% endfor %}\r\n</ul>\r\n\r\nLast<br/>\r\n{{ data.select|last }}<br/>"
  '#ajax': true

```

---
Tags: webforms
---


title: Search info_split is empty

text:
# Question
Title: Search info_split is empty
I need to customize the search results of a drupal 8 (8.7.0 currently) page a bit and need the node\_type for this. According to search-result.html.twig, this should be stored in `info_split.type`, but the whole variable is empty.

How can I get the node type inside the search-result.html.twig file?

# Answer
> 1 votes
Alright, so I'm still not sure why the fields are empty, but they the keys are certainly there. Either it is a bug in the core, or some weird behaviour of my installations.

I fixed it now manually by implementing the `preprocess_search_result` hook in `mytheme.theme`:

```
function mytheme_preprocess_search_result(&$variables) {

    $variables['type'] = $variables['result']['node']->get('type')->getString();
    $variables['nid'] = $variables['result']['node']->get('nid')->getString();

    switch ($variables['type']) {
        // some other adjustments based on the node tpye
    }
}

```

---
Tags: theming, search
---


# Question
Title: How can I create dynamic options based on the existing bundles from hook_drush_command()?
I want to create dynamic options based on the entity types (returned by `entity_get_info()` function) inside the `hook_drush_command()`. There's no bootstrapped Drupal available at all, so the `db_query()` `entity_get_info()` functions aren't available. How can `hook_drush_command()` get site information?

(The module is inside the ~/.drush/mymodule directory.)

# Answer
This should work. Drush bootstraps Drupal before discovering module commands, so the first step is to make sure your commands are defined in a `drush.services.yml` file as usual.

From there, you should be able to define dynamic options using hook options. Since Drush bootstraps Drupal prior to discovering module commands, you should find that the Drupal site is always bootstrapped when your hook is called. You can inject the services you need through your `drush.services.yml` file.

**EDIT** When I read through the comments I thought that you said this was working when you were using `hook_drush_command`, so I answered as if you were asking how to convert and do the same thing in Drush 9. I don't remember the internals of the convoluted Drush 8 bootstrap very well, but I'm not sure this is possible in Drush 8.
> 1 votes

---
Tags: 7, drush
---


# Question
Title: How to place a role-aware "Add new" link at the top of a Views listing of media
I've created a view that provides a listing of a particular media type on my site. I'd like to place an "Add new" link at the top of this view and have it visible only to users who can actually add new media of that type. Does anyone know a straightforward way of doing this?

What I've tried:

* Adding a View header component of type "Text area": Nope, can't restrict visibility
* Using the menu's Menu block and trying to insert that as a Views header component: Nope, can't restrict visibility
* Using the menu's Menu block and adding it to the Block layout with a specific "Show on this page" set to just the Views page I had created. This worked, but with several of these links to create, I would be unacceptably cluttering up my Block layout with one-off menu blocks.
* Creating a menu with one menu item and rendering it with the "Rendered entity: Custom menu item": Nope, can't restrict visibility AND it renders in a useless way (unformatted data)

I find it strange that you can't create a Views header/footer element and specify its visibility based on roles/permissions.

Any ideas/solutions that won't be duplicative or hard to maintain?

# Answer
> 0 votes
In the end, I followed a modified version of the answer Leigh Mason suggested:

1. Created a separate View (named "Add new links") that queries for Blocks (instead of content or media)
2. Created an "Embed" display on that view
3. Set its filter to query for Block ID 999999 (to ensure it never gets results)
4. Set its "No results" text to be the "Add new" link I want to display on my main view.
5. Set its access to the permission for "\[media type\]: Create new media"
6. Added the special view as a "View area" Header element on my main view. (Note that selecting it was a bit cryptic, as I had to choose my embed display, which was in the pick-list as "Embed\_1")

The advantages to this approach are:

* I only have to maintain the link HTML in one place
* I can reuse this same special view for creating all my "Add new" links by creating new Embed displays and modifying the "No results" text using an override for just that specific display. (I can even change the administrative name to help me figure out which displays contain which links)

The disadvantages to this approach are:

* It's a godawful hack that the next developer will curse me for
* It uses a strange quirk to ensure that no records get returned (the super-high Block ID in the filter)

# Answer
> 1 votes
A quick views only way you could:

Create an attachment with your link in a custom text or however you'd like to do it. Set the access permission for that attachment to your role and attach it to your main page display

If the user doesn't have that role the attachment should be empty/show the no results content

# Answer
> 1 votes
have you tried this module? https://www.drupal.org/project/views\_role\_based\_global\_text

I tried it, but it has some issues on D8.6 Can be a good starting point?

---
Tags: views, 8, security
---


# Question
Title: Can I remove the experimental module warning from /admin/reports/status?
My drupal 8 site is showing a experimental modules enabled warning under `/admin/reports/status`. I vaguely remember to have them enabled at a certain time, but I forgot where.

I don't use any of them, how can I remove the warning and disable the experimental modules again?

I have currently no experimental module enabled, but the warning is still displayed:

# Answer
There is an experimental module that it's not shown on the screenshot given in the question: the *Place Blocks* module. Its .info.yml file is the following one, on Drupal 8.7.x.

```
name: Place Blocks
type: module
description: 'Allow administrators to place blocks from any Drupal page'
package: Core (Experimental)
version: VERSION
core: 8.x
hidden: true
dependencies:
  - drupal:block

```

Since it contains the `hidden: true` line, it isn't shown in the list of available/installed modules, in the same way modules used for the tests aren't shown.

You could ask now how it is possible to install a module that isn't shown in the list of the modules. The answer is that on Drupal 8.3.x, the module was not hidden.

```
name: Place Blocks
type: module
description: 'Allow administrators to place blocks from any Drupal page'
package: Core (Experimental)
version: VERSION
core: 8.x
dependencies:
  - block

```

Drupal 8.4.x was the first Drupal 8 branch to hide it.

As for uninstalling it, you need to edit the *core/modules/block\_place/block\_place.info.yml* file, remove the `hidden: true` line, or change it to `hidden: false`, clear the cache, visit the *Extend* page, and uninstall it. Be careful of not changing the line indentation for that file, as a wrong indentation can cause issues.
Since it requires to edit a module file, it could be tricky to make Drupal notice the change. I normally visit the *Extend* page after I edited a module file as in this case, install a core module I don't need, uninstall it, visit another page, and go back to the *Extend* page. At this point, I am sure Drupal caught the change I done to the module file.
> 3 votes

# Answer
You can navigate to the **Extend** (`/admin/modules`) menu and look for the **Core (Experimental)** section, it lists all experimental modules. Note the modules, and head over to the **Uninstall** tab where you can disable the experimental modules you saw.

If it doesn't appear that any modules are enabled, you can inspect the critical code that triggers the alert. Namely, `system_requirements()` which is executing this block:

```
    // Warn if any experimental modules are installed.
    $experimental = array();
    $enabled_modules = \Drupal::moduleHandler()
      ->getModuleList();
    foreach ($enabled_modules as $module => $data) {
      $info = system_get_info('module', $module);
      if ($info['package'] === 'Core (Experimental)') {
        $experimental[$module] = $info['name'];
      }
    }
    if (!empty($experimental)) {
      $requirements['experimental'] = array(
        'title' => t('Experimental modules enabled'),
        'value' => t('Experimental modules found: %module_list. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', array(
          '%module_list' => implode(', ', $experimental),
          ':url' => 'https://www.drupal.org/core/experimental',
        )),
        'severity' => REQUIREMENT_WARNING,
      );
    }
  }

```

Use whatever REPL tool that works best for your workflow (e.g. `drush php`) to determine what/why the alert is being triggered.
> 0 votes

---
Tags: 8, updating
---