# Question
Title: How to make breadcumbs grab taxonomy terms and use tokens
I have tried about 4 different breadcrumb modules now and none of them seem to do what I want. I want them to act in a similar way to Pathauto whereby I can mix and match tokens. There seems not to be a way to do this, for some reason or another. Example, I have a school that belongs to a country name and city name. City and country are part of a taxonomy, so:

```
/united-states/los-angeles/school-name

```

I want this to be:

```
Home > Destinations > Parent Term > Child term > Node title

```

I even might want to add my own text for one of these breadcrumbs.

# Answer
> 1 votes
First of all if you have not tried Taxonomy Breadcrumb module yet, give it a try.

If you already have tried that module and had no success , you can write your own code.

the simplest solution can be achieved by implementing hook\_preprocess\_page, then you should check if there is a node and node is of a certain type used to store school type and then you can change `$variables['breadcrumb']` to modify breadcrumb as you wish.

in drupal 7 you also can use drupal\_set\_breadcrumb to change breadcrumb in a code and in drupal 8 you can implement hook\_system\_breadcrumb\_alter to make it done.

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


# Question
Title: How to restrict one exposed filter per content area?
On my Drupal 8 site a have a /search view page that contains two exposed filters. I would like to expose them in different areas, for example to use search bar in the navigation, and filter by content type in the "content" block. But if I pick in 'advanced' tab 'Exposed form in block' "Yes", then both my filters appear in the navigation bar.

How can I split my exposed filters into different areas?

# Answer
There is a module that seems to do exactly that: MEFIBS - More exposed forms in blocks.

Apart from that you could follow a workaround mentioned on that module project page where you clone your Views Display, don't change the Path, only change the Exposed settings. You will end up with two different blocks that can be placed in different regions, but working on the same Views page.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: ServiceProviderBase override "winner" - can this be done with module weight?
It is noted that modules implementing `ServiceProviderBase` to alter defined services can 'lose' to other modules overriding the same service as there is no way to know which one should overtake in that situation.

Is this 'fixable' by making your modules weight higher than the others?

# Answer
Yes, the serviceProviderClasses are discovered in `DrupalKernel::discoverServiceProviders()`, I've stopped the code there and the list was sorted by module weight and modules with the same weight alphabetically.
> 6 votes

# Answer
The answer by 4k4 is correct, I'd like to share some an additional note about changing the module weight...

If you add a `module_set_weight()` in a hook\_install() it won't have any immediate effect on the order inside `DrupalKernel::discoverServiceProviders()` (as this would have already run during the install process). You will need to clear Drupal cache's first.

Here's the hook\_install I'm using, with some code copied over from `drupal_flush_all_caches()` avoiding doing a second full cache clear in the same request.

```
/**
 * Implements hook_install().
 */
function mymodule_install() {
  module_set_weight('mymodule', 1);

  $module_handler = \Drupal::moduleHandler();
  $module_data = system_rebuild_module_data();
   // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
  // sufficient, since the list of enabled modules might have been adjusted
  // above due to changed code.
  $files = [];
  foreach ($module_data as $name => $extension) {
    if ($extension->status) {
      $files[$name] = $extension;
    }
  }
  \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);

}

```
> 0 votes

---
Tags: 8
---


# Question
Title: How to override form element templates from custom module
I have a custom field with some radio inputs and the following (widget-)output right now:

```
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form-element.html.twig' -->
<div>
  <input />
  <label></label>
</div>
<!-- END OUTPUT from 'core/themes/stable/templates/form/form-element.html.twig' -->

```

For every radio single radio input(In my case 5 times - back 2 back). Can I remove the outer `<div>` without actually touching any themes (neither the stable theme nor my custom theme) ?

# Answer
> 7 votes
Got it working. First you have to copy the default form element template into your module's `/templates` folder. For example:

```
$ mkdir -p modules/custom/MYMODULE/templates
$ cp core/themes/stable/templates/form/form-element.html.twig modules/custom/MYMODULE/templates/form-element.html.twig

```

Now rename it to something you want. For example:

```
$ mv modules/custom/MYMODULE/templates/form-element.html.twig modules/custom/MYMODULE/templates/form-element--foo.html.twig

```

Edit the file to match your needs. For example remove or change the `<div></div>` tags. Finally in your module's `MYMODULE.module` file add the following two hooks.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * This hook adds a new theme suggestion for all radio form elements.
 */
function MYMODULE_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {

  if ($variables['element']['#type'] == 'radio') {
    $suggestions[] = 'form_element__foo';
  }
}

/**
 * Implements hook_theme().
 *
 * This hook registers a new theme in your module. It will
 * automatically look for the template in your module's /templates folder.
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'form_element__foo' => [
      // base_hook is important!
      // Otherwise your template won't know what to render.
      'base hook' => 'form_element',
    ],
  ];
}

```

Only thing left, I find, is to have the form ID added to the template suggestion as well, so that we could target only this one form's elements. As now this template will be taken into account for all radio form element wrappers. Independent from what form they are in. But unfortunately I couldn't find the form ID inside the `form_element`'s `$variables`.

---

Hah, you simply could add a class to your radios and identify them by that later.

```
$form['radios'] = [
  '#type' => 'radios',
  // ...
  '#attributes' => ['class' => ['foo']],
];

```

And then the `hook_theme_suggestions_HOOK_alter` could look like that:

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

  if ($variables['element']['#type'] == 'radio' && in_array('foo', $variables['element']['#attributes']['class'])) {
    $suggestions[] = 'form_element__foo';
  }
}

```

Now the custom template would only be taken into account for your specific `radios`.

---
Tags: 8, theming
---


# Question
Title: What would cause contextual filter settings NOT to save?
I have a view in Drupal using a contextual filter. I save the changes about what to do when a value is passed. After I hit save, everything revers back as if nothing ever happened.

Has anyone seen this before? Any suggestions?

# Answer
In the end, the "simple" answer worked. I deleted the filter and added it back. I'm not sure if I configured it wrong to begin with or if something "bigger" was at play.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How do I add custom tab in the user profile page?
I need to add a custom tab in user profile page. I defined my route like below:

**mymodule.routing.yml**

```
mymodule.account:
path: '/user/{user}/custom'
defaults:
  _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
  _title: 'Custom Settings'
  user: \d+
requirements:
  _permission: 'access content'

```

**mymodule.links.task.yml**

```
mymodule.account:
  title: Mymodule Settings
  route_name: mymodule.account
  base_route: entity.user.canonical

```

**mymodule.links.menu.yml**

```
mymodule.account:
  title: My module Settings
  parent: entity.user.canonical
  route_name: mymodule.account

```

Then after clear cache tab is appearing in the profile page. But when I open the url **/user/1/custom** I see the page not found message.

# Answer
> 6 votes
Your problem is in the `mymodule.routing.yml` file, the big problem is the place of `user: \d+`, this line must be under the `requirements:` section, the other problem is the indentation. So the final code should be:

```
mymodule.account:
  path: '/user/{user}/custom'
  defaults:
    _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
    _title: 'Custom Settings'
  requirements:
    _permission: 'access content'
    user: \d+

```

And of course you need the form class definition in `src/Form/MyModuleUserSettingsForm.php`

```
<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class MyModuleUserSettingsForm.
 *
 * @package Drupal\mymodule\Form
 */
class MyModuleUserSettingsForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'simple_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#maxlength' => 64,
      '#size' => 64,
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
    ];

    return $form;
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {  }

}

```

And a `mymodule.info.yml` file to complete your module (in this case named mymodule)

```
name: My Module
type: module
description: 'My module'
core: 8.x
package: Custom

```

**Reference:** Structure of routes

# Answer
> 3 votes
There are two ways to load a form using a route. You can either load up a callback that loads a form and returns it as part of the build array, or you can load up the form directly by setting the \_form parameter under defaults.

You can search the codebase to find working examples, copy them into your mymodule.routing.yml, edit them to your needs and then rebuild the cache.

**Loading form from callback:**

There's a working example in the contact module:

/core/modules/contact/contact.routing.yml

```
entity.user.contact_form:
  path: '/user/{user}/contact'
  defaults:
    _title: 'Contact'
    _controller: '\Drupal\contact\Controller\ContactController::contactPersonalPage'
  requirements:
    _access_contact_personal_tab: 'TRUE'
    user: \d+

```

Then in /core/modules/contact/src/Controller/ContactController.php

you can see an example of how to load a form in the callback:

```
  public function contactPersonalPage(UserInterface $user) {
    // Do not continue if the user does not have an email address configured.
    if (!$user->getEmail()) {
      throw new NotFoundHttpException();
    }

    $message = $this->entityManager()->getStorage('contact_message')->create(array(
      'contact_form' => 'personal',
      'recipient' => $user->id(),
    ));

    $form = $this->entityFormBuilder()->getForm($message);
    $form['#title'] = $this->t('Contact @username', array('@username' => $user->getDisplayName()));
    $form['#cache']['contexts'][] = 'user.permissions';
    return $form;
  }

```

**Loading form directly from the route:**

If you would like to load the form directly using the \_form default, there's an example in the shortcut module at /core/modules/shortcut/shortcut.routing.yml

```
shortcut.set_switch:
  path: '/user/{user}/shortcuts'
  defaults:
    _form: 'Drupal\shortcut\Form\SwitchShortcutSet'
    _title: 'Shortcuts'
  requirements:
    _custom_access: 'Drupal\shortcut\Form\SwitchShortcutSet::checkAccess'
  options:
    _admin_route: TRUE
    user: \d+

```

In this case, the user is passed in as a parameter to the form, see /core/modules/shortcut/src/Form/SwitchShortcutSet.php

```
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {

```

# Answer
> 1 votes
A few things I can spot off hand...

You've got EVERYTHING named mymodule.account. I'd diversify that a bit. Consider going with this for the tasks page:

```
mymodule.account_tab:
  title: Mymodule Settings
  route_name: mymodule.account
  base_route: entity.user.canonical

```

I also do not believe you need anything in the menu either for this.

Between those two, you should be good to go! Feel free to reach out to me directly if you can't figure this out because I --JUST-- got this to work on my D8 port of Apply For Role!

# Answer
> 1 votes
In modulename.routing.yml you have to pass user argument like below

```
profile.user_information:
  path: '/user/{user}/profile'
  defaults:
    _form: '\Drupal\profile\Form\UserInformation'
    _title: 'UserInformation'
  requirements:
    _permission: 'access content'
  options:
    user: \d+

```

and in modulename.links.task.yml you have the code like below

```
profile.user_information:
  title: User profile
  route_name: profile.user_information
  base_route: entity.user.canonical

```

---
Tags: users, 8, routes
---


title: Calculating view field average

text:
# Question
Title: Calculating view field average
I have a custom comment type with a star rating field value. When people create a comment on a node type they can also select a rating. I need to create a way to get an average of the ratings from the comments for the node.

I have created a view block that has a contextual filter of Id from url that can be placed on a node and it will display all the rating fields for that node. I need to calculate the average of the values. The views aggregation is throwing up an error regarding (GROUP columns is illegal if there is no GROUP BY clause).

Is there a way to get the average ?

Update: I have sorted the problem with the averaging by adding a field that is used to group. Now having problems using the average as an outputted field in templates. The view is creating the average but the node ID is needed. How would I display the view average for each node on a list of nodes?

# Answer
> -1 votes
Used EVA module to output the views result.

---
Tags: views, 8
---


# Question
Title: How to create custom template suggestion, when there is no hook suggestion?
I would like to create different templates for different nodes, but I cannot see any hook suggestion with theme debug. This is the template from quiz module. So in theme debug it looks like that:

```
<!-- THEME DEBUG -->
<!-- CALL: theme('multichoice_alternative') -->
<!-- BEGIN OUTPUT from 'sites/all/modules/contrib/quiz/question_types/multichoice/theme/multichoice-alternative.tpl.php' -->

```

I was searching for the right answer, reading about template suggestions, trying different things, but without any luck so far. I know, that I can create custom template for the whole block, but is it possible to create that custom template for the element which doesn't have any hook suggestions? Thanks!

# Answer
You can do it this way

1. implement `hook_theme_registry_alter` like the following:

```

    /**
     * Implements hook_theme_registry_alter().
     */
    function YourCostumModuleName_theme_registry_alter(&$theme_registry) {
      // Defined path to the current module.
      $module_path = drupal_get_path('module', 'YourCostumModuleName') . "/templates";
      // Find all .tpl.php files in this module's folder recursively.
      $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
      // Iterate through all found template file objects.
      foreach ($template_file_objects as $key => $template_file_object) {
        // If the template has not already been overridden by a theme.
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
          // Alter the theme path and template elements.
          $theme_registry[$key]['theme path'] = $module_path;
          $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
          $theme_registry[$key]['type'] = 'module';
        }
      }
    }

```
2. Create Folder called `templates` inside your custom module folder.
3. Copy `contrib/quiz/question_types/multichoice/theme/multichoice-alternative.tpl.php` file into `templates` folder with the same name `multichoice-alternative.tpl.php`.
4. `Clear Cache`.
5. Now you have `$form` and `$fullOptions` variables.
> 1 votes

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


# Question
Title: How to remove field from form and configuration?
We have a custom module, `mymodule` that has a form, `mymoduleForm` with two fields: `enabled content types` and `urls`.

We no longer need the `enabled content types` field on the form and want to remove it from the form and configuration. We do not have either `config/install/mymodule.settings.yml` and `config/schema/mymodule.schema.yml` files.

**How can we remove the field (`enabled content types`) from both the form and configuration?**

`mymoduleForm.php` (all lines below we are thinking need to be removed related to `enabled_content_types`)

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');

  $types = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->loadMultiple();

  foreach($types as $type) {
    $content_types[$type->id()] = $type->label();
  }

  $form['enabled_content_types'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Enabled Content Types'),
    '#description' => $this->t('content types .'),
    '#default_value' => $config->get('enabled_content_types'),
    '#options' => $content_types,
  ];

  ...

  return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');
  $mymodule_config
    ->set('enabled_content_types', $form_state->getValue('enabled_content_types'))
    ->set('urls', $form_state->getValue('urls'))
    ->save();

  parent::submitForm($form, $form_state);
}

```

# Answer
> 2 votes
change this line

```
->set('enabled_content_types', $form_state->getValue('enabled_content_types'))

```

to

```
->clear('enabled_content_types')

```

In Drupal, go to config form and click save.

**Side Note:** Alternatively, you could also delete the config via Drupal Console or Drush as mentioned in the answers here, How do I remove a configuration object from the active configuration?

Now you may now remove the relevant code.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');

  $types = \Drupal::entityTypeManager() // remove
    ->getStorage('node_type') // remove
    ->loadMultiple(); // remove

  foreach($types as $type) { // remove
    $content_types[$type->id()] = $type->label(); // remove
  } // remove

  $form['enabled_content_types'] = [ // remove
    '#type' => 'checkboxes', // remove
    '#title' => $this->t('Enabled Content Types'), // remove
    '#description' => $this->t('content types .'), // remove
    '#default_value' => $config->get('enabled_content_types'), // remove
    '#options' => $content_types, // remove
  ]; // remove

  ...

  return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');
    ->clear('enabled_content_types') // remove
    ->set('urls', $form_state->getValue('urls'))
    ->save();
  parent::submitForm($form, $form_state);
}

```

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


title: "Page not found" with new content type

text:
# Question
Title: "Page not found" with new content type
I already have a custom content type (*jobs*). When I create jobs nodes, they are displayed. I have created a new content type (*ideas*). When I add an idea node, I get a *Page not found* error. Any new custom content type I create gives me the same error.

The nodes I created are published. I cleared the cache.

I tried re-building the node permissions here: https://www.foo.com/admin/reports/status

Which didn't work.

There does appear to be Experimental modules found: Content Moderation. This would no longer be experimental in 8.6, currently the site is running 8.2. Not sure if that upgrade would help or create more problems.

There is this error which is interesting:

Mismatched entity and/or field definitions The following changes were detected in the entity type and field definitions. Content The node.field\_recognition\_date field needs to be uninstalled.

But I am not sure how to uninstall that or how to fix this issue. Any help would be appreciated.

# Answer
Sound like you have removed a dependency from the codebase that a field a certain field depends on, usually it's a module. If that's the case you will need to reinstate it, then uninstall it. But also, you might want to try `drush entup` and `drush updb`

Also, it's a good idea to check the error reports for a more detailed explanation of what has happened
> 0 votes

---
Tags: nodes
---


# Question
Title: Why is my property being rendered when I don't call render?
I have a string property, and HTML is getting rendered instead of a string, even though I don't call render where the property is being accessed.

**Twig template**:

```
{{ attach_library('mymodule/video') }}

{% if content.video_url|render %}
  <video>
    <source src="{{ content.video_url }}" type="video/mp4">
  </video>
{% endif %}

```

As you can see, I'm specifying `src="{{ content.video_url }}"`, NOT `src="{{ content.video_url|render }}"`. Still, the rendered HTML is:

```
<div>

<video>
  <source src="            <div data-quickedit-field-id=" paragraph="" ex_video_url="" en="" default"="" class="field field--name-video-url field--type-string field--label-hidden field__item">video.mp4</video></div>" type="video/mp4">

```

Why is drupal rendering HTML instead of a string?

# Answer
`content.video_url` contains a build array of the field which Twig renders automatically, including the HTML markup of the field template.

To print the raw string value use the entity object which stores the field, `node` in node.html.twig

```
{{ node.video_url.value }}

```

or `paragraph` in paragraph.html.twig:

```
{{ paragraph.video_url.value }}

```
> 1 votes

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


# Question
Title: How can I "form alter" fields in a nested Paragraph, depending on where the field is used
I have these entity types:

* A node type: `nodepage`
* A Paragraph type: `pg_a`
* A Paragraph type: `pg_b`
* A Paragraph type: `pg_child`

I have a content model which is:

```
nodepage
  ->field_a
    Referenced bundles: pg_a
      ->field_child
        Referenced bundles: pg_child
  ->field_b
    Referenced bundles: pg_b
      ->field_child
        Referenced bundles: pg_child

```

You can see that `pg_a` and `pg_b` both have a field called `field_child` which allows a reference to `pg_child`. This has great semantic meaning to the site architecture.

Now something I would like to do is form alter pg\_child, but *only* when it is referenced from `pg_a` and not from `pg_b`.

In `hook_field_widget_form_alter`, where I *think* I should be doing my alters, I can do the following:

```
$field_definition = $context['items']->getFieldDefinition();

// Get the current field widget being built, eg `field_child_thing`.
$name = $field_definition->getName();

// Get the bundle, ie. `pg_child`
$targetBundle = $field_definition->getTargetBundle();

// Get the bundle that $targetBundle is attached to in this instance...
$instance = ???

```

I thought I could look further into the $context variable, but so far this has alluded me. The best candidate so far is `#parents` in the form, but when I only find a reference to `field_child` which is ambiguous.

I now suspect I can inject more $context from somewhere, maybe in the parent build.

# Answer
> 5 votes
In this scenario, we have `field_caption` being used in various places inside a `cta` paragraph. The business has asked to limit `field_caption` to 25 charaters, but only when it is being used in a node on an entity reference field called `field_foo_cta`.

First we add a #process callback to the widget based on whatever rule, by implementing `hook_field_widget_form_alter`:

```
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, &$context) {
  $field_definition = $context['items']->getFieldDefinition();

  if ($field_definition instanceof FieldConfig) {
    $config = $field_definition->id();
    list ($entity_type, $bundle, $field_name) = explode('.', $config);

    if ($entity_type == 'paragraph' && $field_name == 'field_caption') {
      $element['#process'][] = ['\Drupal\mymodule\BusinessRules', 'alterFieldCaption'];
    }

  }
}

```

Then we create a new class in `src` directory of the module.

```
namespace Drupal\mymodule;

class BusinessRules {

  public static function alterFieldCaption(array &$element, FormStateInterface &$form_state, array &$complete_form) {

    // Use whatever logic to target instances of `field_caption`.
    if (reset($element['#parents']) == 'field_foo_cta') {
      $element['value']['#maxlength'] = 25;
    }
    return $element;

  }

}

```

Thanks @larowlan for help on this.

# Answer
> 0 votes
> I thought I could look further into the $context variable, but so far this has alluded me. The best candidate so far is #parents in the form, but when I only find a reference to field\_child which is ambiguous.

Is the entity object available in $context? If not it may be inside $form\_state somewhere.

Once you got the Paragraph entity you can get its parent using `Paragraph::getParentEntity()` and from there the type of the parent.

---
Tags: 8, paragraphs
---


title: sites.php setup

text:
# Question
Title: sites.php setup
I am trying to do multi-site the following way:

http://domain.com/site1

http://domain.com/site2

sites.php:

```
 $sites['domain.com.site1'] = 'default';
 $sites['domain.com.site2'] = 'site2';

```

I then went into my drupal root and did:

```
ln -s . site1
ln -s . site2

```

Is this the correct way of doing this? It appears to work, but I am not sure if symlinking is the proper way.

# Answer
> 3 votes
Yes- you did this right :)

cp example.sites.php as sites.php, set the sites array, set the symlink, and you're set!

# Answer
> 1 votes
You can set the sites array in sites.php as:

```
$sites['multi.devs'] = 'multi.dev';
$sites['sub1.multi.devs'] = 'multi.devs';
$sites['sub2.multi.devs'] = 'multi.devs';

```

and in your hosts file you can set the hostname as

```
127.0.0.1       multi.devs
127.0.0.1       sub1.multi.devs
127.0.0.1       sub2.multi.devs

```

Also need to entry them in httpd-vhost.conf file. Like:

```
<VirtualHost *:80>
    DocumentRoot "projects/drupal_multi/"
    ServerName   multi.devs
    ErrorLog    "logs/error.log"
    CustomLog   "logs/access.log" common
</VirtualHost>

```

You need to do this for each of sub site. DocumentRoot will be the same the server name will be change for each of them.

---
Tags: multi-sites
---


title: Error message in checkout step

text:
# Question
Title: Error message in checkout step
I'm getting the following error on the return page of my off-site payment:

```
#1 ... /httpdocs/core/modules/editor/editor.module(554): _drupal_error_handler(4096, 'Argument 1 pass...', '... /httpdocs/ ...', 554, Array)
#2 ... /httpdocs/core/modules/editor/editor.module(384): _editor_get_file_uuids_by_field(NULL)
#3 [internal function]: editor_entity_update(Object(Drupal\commerce_order\Entity\Order))
#4 ... /httpdocs/core/lib/Drupal/Core/Extension/ModuleHandler.php(402): call_user_func_array('editor_entity_u...', Array)
#5 ... /httpdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(169): Drupal\Core\Extension\ModuleHandler->invokeAll('entity_update', Array)
#6 ... /httpdocs/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(730): Drupal\Core\Entity\EntityStorageBase->invokeHook('update', Object(Drupal\commerce_order\Entity\Order))
#7 ... /httpdocs/modules/contrib/commerce/src/CommerceContentEntityStorage.php(88): Drupal\Core\Entity\ContentEntityStorageBase->invokeHook('update', Object(Drupal\commerce_order\Entity\Order))
#8 ... /httpdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(470): Drupal\commerce\CommerceContentEntityStorage->invokeHook('update', Object(Drupal\commerce_order\Entity\Order))
#9 ... /httpdocs/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(615): Drupal\Core\Entity\EntityStorageBase->doPostSave(Object(Drupal\commerce_order\Entity\Order), true)
#10 ... /httpdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(395): Drupal\Core\Entity\ContentEntityStorageBase->doPostSave(Object(Drupal\commerce_order\Entity\Order), true)
#11 ... /httpdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php(820): Drupal\Core\Entity\EntityStorageBase->save(Object(Drupal\commerce_order\Entity\Order))
#12 ... /httpdocs/core/lib/Drupal/Core/Entity/Entity.php(391): Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object(Drupal\commerce_order\Entity\Order))
#13 ... /httpdocs/modules/contrib/commerce/modules/checkout/src/Plugin/Commerce\CheckoutFlow\CheckoutFlowBase.php(130): Drupal\Core\Entity\Entity->save()
#14 ... /httpdocs/modules/contrib/commerce/modules/payment/src/Controller/PaymentCheckoutController.php(88): Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowBase->redirectToStep('complete')
#15 [internal function]: Drupal\commerce_payment\Controller\PaymentCheckoutController->returnPage(Object(Drupal\commerce_order\Entity\Order), Object(Symfony\Component\HttpFoundation\Request))

```

(any stack beyond this is, afaik, Drupal boiler plate)

Digging into editor.module, obviously the `original` property of my order entity is NULL, and that causes the error.

Does this indicate that my order has not been updated, and does not need saving? As in, I should just patch the CheckoutFlowBase class to check if the `original` property is set, and if so, save?

Or is the fix going to have to be more complicated?

# Answer
That error most commonly occurs if an order is being double-saved, by calling $order-\>save() within a hook\_entity\_presave() or a matching event, including pre/post transition events.

If you need to modify the order during a state transition, do it in a pre-transition event and let the system take care of the rest.
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: Using hook_form_alter() to add the "None" value in the select list of a required field
When a field is required, Drupal removes the default "-None-" value. However, also for a required field, "-None-" is very valuable as it requires the user to make a deliberate selection (put the first value on the select list as default doesn't force a sloppy user to make a selection).

I need to:

* Have "-None-" as default value in the select list of a required field
* Not accept "-None-" as field value when the form is submitted

How can I achieve this with `hook_form_alter()`?

# Answer
> 2 votes
By default, the label for the first default option is automatically set to "- Select -" for a required field and "- None -" for an optional field. To force the `#empty_option` to also show "- None -" for a required field, assign it with something like:

```
"#empty_option" => t('- None -'),

```

This will keep everything else intact and will do exactly what you want. See `class Select`.

---
Tags: forms, hooks
---


# Question
Title: How to create user programatically if not exist?
I am using this code to create user.

```
  if(user_validate_name('czxc') != ""){
        $user = User::create([
                'name' =>'czxc',
                'mail' => 'user@gmail.comgczxcdfa',
                'pass' => 'password',
                'status' => 1
             ]);
            $user->save();
            drupal_set_message($user->id());

    }else{
        drupal_set_message('Already exist user');
    }
   This code works only one time for me.

```

# Answer
The `user_validate_name` function from Drupal only verifies the syntax of the given name.

It does not validate whether the username exists or not.

You could replace the function call, like so:

```
$uids = \Drupal::entityQuery('user')
  ->condition('name', 'czxc')
  ->execute();
if (count($uids) > 0) {
  $user = User::create([
    'name' =>'czxc',
    'mail' => 'user@gmail.comgczxcdfa',
    'pass' => 'password',
    'status' => 1
  ]);
  $user->save();
  drupal_set_message($user->id());

} else {
  drupal_set_message('Already exist user');
}

```
> 3 votes

---
Tags: 8, users
---


# Question
Title: Which permission should I use for a role to see a shortcut to Custom Block Library?
I have a custom block that is a site-wide announcement. I have a role, "Announcement Editor", for those people who I want to edit that message.

Most of our users have restricted permissions, and don't have access to the "Structure" menu, etc. We use shortcuts to allow them to see items they can't navigate to through menus. This was set up by a developer who is no longer here.

I want to add a shortcut, "Blocks", linking to `/admin/structure/block/block-content` to these users' menu. I have added it to the default shortcuts for the site. It shows up for Admin users:

However it doesn't show up for other users:

What permission(s) do I need to add for users to see this shortcut?

**Edit** Authenticated users have the permission `use shortcuts` already:

# Answer
> 1 votes
The permissions defined for the module are:

```
administer shortcuts:
  title: 'Administer shortcuts'
customize shortcut links:
  title: 'Edit current shortcut set'
  description: 'Editing the current shortcut set will affect other users if that set has been assigned to or selected by other users. Granting "Select any shortcut set" permission along with this permission will grant permission to edit any shortcut set.'
switch shortcut sets:
  title: 'Select any shortcut set'
  description: 'From all shortcut sets, select one to be own active set. Without this permission, an administrator selects shortcut sets for users.'
access shortcuts:
  title: 'Use shortcuts'

```
1. To see the shortcuts you need the permission **Use shortcuts**.
2. To see the shortcuts in the toolbar you need the permission **Use the administration toolbar**
3. To see the shortcut for the page **/admin/structure/block/block-content** you need the permission **Administer blocks**

---
Tags: 8, users
---


# Question
Title: search_api_solr with accurate radioactivity sorting in views
We're using Views to display our search\_api\_solr results. We'd like to be able to show these results by radioactivity (popularity) sort order.

The radioactivity field is one of several fields indexed by Solr so that it can be used by the Solr views for sorting.

The problem is, the radioactivity value that gets indexed by solr only gets updated when the entity gets indexed. The entity only gets indexed when it gets changed (node\_update), or when the Solr index is cleared and everything is reindexed again. Having an entities radioactivity energy adjusted by visiting the entity, does not trigger solr to reindex the entity - and probably rightly so.

I've tried adding a relationship in the Search View to node, but that isn't available as a "search index" view type.

Does anyone have any other suggestions for solving this? There doesn't seem to be a radioactivity hook that lets you execute your own code, i.e. update search\_api\_item table to say its changed.

# Answer
As you say there's no API, so you're probably going to have to resort to patching the module.

There are at least two places you'll need to make additions as far as I can tell:

* `_radioactivity_update_energy()`
* `radioactivity_cron()`

I would suggest adding your own hook which gets fired whenever an entity is updated in either of those functions, and perform the search indexing there.

You should have a good think about the values you use for half lives/Solr processing delays if you choose to implement it like this. If your values for those settings aren't sensible you could end making the changes without actually seeing any effect. Also, depending on the amount of traffic the site receives, you could slow your server down quite a bit doing this.
> 0 votes

# Answer
If you want to add a single entity, then following code can be helpful:

```
search_api_track_item_change('node', array($entity_id));
$index = search_api_index_load('SEARCH_API_INDEX_NAME');
$indexed = search_api_index_specific_items($index, array($entity_type.'/'.$entity_id));

```
> 0 votes

---
Tags: views, search
---


# Question
Title: Interface translation conflict / same EN word, different translations
I've created a custom module, that uses templates with hard coded strings. I've created the `.pot` and `.po` files and included them my module's YML file. The Twig tempatles translate those strings using the `|t` operator. This works fine.

Now I've run into a problem: My module offers button to `book` an accommodation, which clashes with Drupal's `book` (to read) module. In the german translation those two words are completely different.

I've got two questions:

1. How to I provide a translation for the `book` verb in my module, in a way that it doesn't clash with the book module.
2. How to I use the tell Twig to use the correct `book` string from my module?

E.g. this template code
`First I want to {{ 'book'|t('context_accomodation') }} a hotel room and when I arrive I want to read a {{ 'book'|t('context_reading') }}`

should render in english
*First I want to `book` a hotel room and when I arrive I want to read a `book`*

and should render in german
*First I want to `buchen` a hotel room and when I arrive I want to read a `Buch`*

# Answer
Drupal does have an answer to this problem, at least if it's your own code where you need to make that distinction. It's called context.

In the PO file, add a `msgctxt` line

```
# an explanatory comment line for your translator
msgctxt "Accomodation"
msgid "book"
msgstr "buchen"

```

In PHP, it works like this:

```
<?php
t('book', [], ['context' => 'Accomodation']);
?>

```

In twig, it should go like this:

```
{{ 'book'|t({}, {'context': 'Accomodation'}) }}

```

The problem with this approach is that the developer needs to be aware that a certain word might have a multiple context specific translations in another language that he most likely doesn't know. But for your specific scenario, it should work fine.
> 4 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: use taxonomy term for reservations how to prevent overlapping
I have a drupal site where reservations are available. We use fullcalendar module to visualize the room reservations. For a reservation the user needs to add a new content. The content uses taxonomy terms as rooms. Now I'd like to achive that once the user creates a new booking content and chooses the room, when it is not available, the user should be warned. I mostly use rules and i am a bit unexperienced with drupal, now I'm trying to learn.

# Answer
> 0 votes
There are a number of ways to achieve the booking features in Drupal, try comparing here: Comparison of Booking System modules

One way that comes to mind for your specific case is using Flag module because you can set a Flag to be global, once an entity is marked as "occupied" that status is valid across the site. It's well integrated with Views and Rules, so you could probably do a lot there.

Another way might be to use Views Entity reference display for the Field widget when the user is creating a reservation. The Views would make sure to exclude all the terms for the Vocabulary that are already being used, so only "free" terms would show up when creating a new booking.

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


title: Drush documentation

text:
# Question
Title: Drush documentation
I'm curious if anyone else noticed how difficult it is to get drush working based on the available documentation? Drush is a great command line tool, and it's a pity that the **official drush install docs page** doesn't bubble to the top in Google searches.

I realize that we're a community powered project, so there's paid staff. Nevertheless, it seems we've overlooked some of the edge cases, such as 'installing Drush after the fact,' 'adding drush to the .bashrc file' and/or 'what if you're installing onto Ubuntu 18.04 with PHP7.1' scenario.

I realize that with the sheer number of available options out there (Mac, Ubuntu 14, 16.04, 18.04, CentOS, Red Hat, Postgresql, MySQL, Mariadb, virtual machines, etc. ad infinitum) there may simply be too many edge cases to account for every possible situation -- it just (anecdotally) seems to me that it's always a non-simple task to install and then run drush.

Is there someone I can send $10 to?

NOTE: I'm fully mentally preparing for my question to be flagged for deletion for not being general enough / specific enough, off topic, too short, too long, not enough reputation points, etc. I am posting this on SE after, all, right? ;)

# Answer
If you visit the Drush project on GitHub, the first link in the Resources section points to the Installation documentation. This same link also appears front-and-center on drush.org. This installation page is for Drush 9. If you don't want Drush 9, there is a link to the Drush 8 documentation on the top of the Drush 9 installation page.

The recommended way to install Drush 9 is as a site-local install as part of the drupal-composer/drupal-project. If you use this project, Drush is automatically installed (along with Drupal Console).

The recommended way to install Drush 8 is to download the phar from GitHub.

It is a non-goal of the Drush project to attempt to enumerate all of the possible installation methods for Drush. If you stick with the recommended methods, then you should have an easy enough time. If you have any suggestions on how to improve the documentation for the recommended installation methods, please submit a pull request.

The Drush maintainers have never attempted to collect donations because most people's idea of a reasonable value for Drush is so low that it seems unlikely that any such efforts would recoup the cost to collect it. Instead of your cash, please contribute to the project, or hire a contractor to contribute to the project if you cannot contribute directly yourself.
> 1 votes

---
Tags: 8, drush
---


title: Dont save webform data to database

text:
# Question
Title: Dont save webform data to database
For SPECIFIC webforms, how can I make it not save data to the database, but just send the email? It should however still save the files and link to them in the email.

Idk if I can use something like this: https://www.drupal.org/project/webform\_clear since this seems to work on all webforms, while I wanna use it only on specific ones.

Thanks

# Answer
> 0 votes
What files are you referring to?

If there are files being generated from webform node content then the data probably has to be saved first in order to generate the files. In this case you should target to delete the nodes once the email has been sent (while allowing for them to be created at first). You can look into Rules module for that.

Webforms all have separate email settings so I'd expect the webform\_clear to also offer per-form settings.

---
Tags: 7, database
---


# Question
Title: Why are the edit/delete/reply links missing in the Comment module?
I'm using 8.6.0 core's Comment module. I can add comments, but I can't edit or delete them. I also can't reply to anyone else's.

Permissions have been set that all authenticated roles can edit. I'm even an admin and nothing.

I even looked at the `comment.html.twig` template. I don't see any of those links. The only link showing is `{{ permalink }}`. The variables also don't supply any of the links I require.

I looked around and can't find anything related to Drupal 8.

# Answer
> -1 votes
It ended up being layout builder. Enabled full content and layout builder, cleared cache and it worked.

---
Tags: 8, comments
---


# Question
Title: How do I change the Default Query of a Views Exposed Filter with hook_form_alter()?
I searched for an entire day on this issue and found no working solutions that affect the "initial query" of an exposed form in Drupal 7.

I have a simple checkbox exposed as a select list; the options are All, 1, or 0. It defaults to All on default. I'm trying to change it to 0. With that said, I was able to successfully set the default value of my exposed form (doesn't affect the initial query) and rename the options with a custom module:

```
function MODULE_form_alter(&$form,&$form_state,$form_id) {
//dpm($form);
  if($form_id == 'views_exposed_form') {
    $form['field_checkbox']['#default_value'] = '0';
    $form['field_checkbox']['#options']['All'] = t('Both');
    $form['field_checkbox']['#options']['0'] = t('Unchecked');
    $form['field_checkbox']['#options']['1'] = t('Checked');
  }
}

```

I tried to interpret merlinofchaos' advice in the only relevant advice I could find on this (9 year old thread) and might not even be relevant to D7.

```
function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
    //print $form['#id'];
    if($form['#id'] == 'EXPOSED_FORM_NAME') {
        if (!isset($_GET['EXPOSED_FILTER_NAME']))  {
            $form_state['input']['EXPOSED_FILTER_NAME'] = '0';
        }
    }
}

```

Though the above code changes the `$form_state['input']['EXPOSED_FILTER_NAME']` variable from "All" to "0", it doesn't change the default query. I have dpm'd both `$form` and `$form_state`, but I don't know what needs to be changed. Any advice would be extremely appreciated!

# Answer
Try this out with hook\_views\_pre\_build

```
/**
 * Implements hook_views_pre_build().
 */
function MODULE_NAME_views_pre_build(&$view) {
    if ($view->name == 'VIEW_MACHINE_NAME') {
        //- Set the exposed filter to new value
        $view->filter['EXPOSED_FILTER_NAME']->value = '0';
    }
}

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to give a roll only access to add a certain content type?
In D8: I have a content type call fooCT. I have a role called: "fooRole"

I give fooRole the following permissions:

* fooCT: create fooCT
* use simple editor

So the checkbox: View published content is not checked

A person with this role cannot do anything in the system anymore.

How to give this person only access to add a a fooCT?

I tried several options but do not get the desired result.

Any suggestion?

# Answer
> 1 votes
The Permission `View published content` is very important, without the users of that role won't be able to see Published content. What do you mean by "cannot do anything in the system anymore"?

Do you want that Role to be able to create new nodes of that type, but not to be able to View those nodes once they're created?

You should look into the `Editorial` Workflow, and Content Access module.

# Answer
> 0 votes
My first question is why can they NOT access published content. All users need that to view the node. It maybe interesting to start enabling access to this user to get a better understanding of each permission.

---
Tags: 8, users
---


# Question
Title: How to set custom access for a custom page?
For example, there is a page on the site, created before.

I need to set custom permission for it.

Par example, if a user doesn't have a photo in his profile, he shouldn't have access to page "/forum".

On Drupal 7 it was possible via hook\_menu\_alter and set access control there.

Could you clarify me, how can I it on Drupal 8 ?

# Answer
Here's an example which prevents anonymous users from resetting their password.

services.yml:

```
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\MymoduleRouteSubscriber
    tags:
      - { name: event_subscriber }

```

src/Routing/MymoduleRouteSubscriber.php:

```
<?php

namespace Drupal\mymodule\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('user.pass')) {
      $route->setRequirement('_custom_access', '\Drupal\mymodule\Access\ResetPasswordAccessCheck::access');
    }
  }

}

```

src/Access/ResetPasswordAccessCheck.php:

```
<?php
namespace Drupal\mymodule\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

class ResetPasswordAccessCheck {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(AccountInterface $account) {

    return $account->isAnonymous() ? AccessResult::forbidden() : AccessResult::allowed();

  }

}

```

I've updated the documentation to clarify what return value is expected: https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

**Forum access example**

You only need the route subscriber in services.yml:

```
services:
  yrv_page_access.forum_route_subscriber:
    class: Drupal\yrv_page_access\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

RouteSubscriber:

```
<?php

namespace Drupal\yrv_page_access\Routing;

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

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection){
    if ($route = $collection->get('forum.index')){
      $route->setRequirement('_custom_access', '\Drupal\yrv_page_access\Access\ForumAccessCheck::access');
    }
  }
}

```

Access check:

```
<?php

namespace Drupal\yrv_page_access\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

/*
 * Custom access to the forum page
 */
class ForumAccessCheck {

  public function access(AccountInterface $account){
    return AccessResult::forbidden();
  }
}

```
> 5 votes

---
Tags: 8, users
---


# Question
Title: Header and many components missing in Open Social
Just installed Open Social: https://www.drupal.org/project/social

The problem is that there is no content on the front page. No header or other blocks. I have reviewed videos of installation on YouTube, and notice that there is a header, and many other blocks available by default immediately after installation. Why does my new instance of Open Social have nothing on the home page?

I followed the install instructions on the module page: https://www.drupal.org/project/social

# Answer
Generating demo content is optional but recommended. Follow these instructions on generating demo content (Drush support only for now). Still stuck? Explore the thorough guide to installing and updating which includes help for working with Docker.

OR

drush command to add demo content

```
drush demo-content-add file user group topic event event_enrollment comment post like

```
> 0 votes

---
Tags: installation
---


title: EntityFieldQuery order by title

text:
# Question
Title: EntityFieldQuery order by title
I'm getting an error when using this entity field query, the error says that that the field title cannot be found but I'm only querying the basic node table.

```
$product_query->entityCondition('entity_type', 'node')->entityCondition('bundle', 'product')->fieldCondition('field_line', 'tid', $selected)->fieldOrderBy('title', 'DESC');

```

# Answer
The node title is a *property*, not a field:

```
$product_query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product')
  ->fieldCondition('field_line', 'tid', $selected)
  ->propertyOrderBy('title', 'DESC');

```
> 7 votes

# Answer
```
                $queryst = new EntityFieldQuery();
                $queryst->entityCondition('entity_type','node');
                $queryst->propertyCondition('status', 1);
                //$queryst->propertyOrderBy('nid','DESC');
                $queryst->fieldOrderBy('field_sort_order', 'value', 'ASC');
                $queryst->entityCondition('bundle','bill_status');
                $result_st = $queryst->execute();

```
> 0 votes

---
Tags: database
---


# Question
Title: How limit access to a paragraph type by role, like it is for content types?
The permissions page at `/admin/people/permissions` provides very fine grain control over which actions people can do with specific content types. How can I add all **paragraph types** under this permission system? We have a paragraph type that is reserved only for special cases, and we don't want anyone but a certain custom editor role creating/editing them.

I've searched for a few contrib modules, but many are not updated (or just plain abandoned) with little documentation.

# Answer
> 8 votes
Simply enable the *Paragraphs sub-module* **Paragraphs Type Permissions**. It provides CRUD permissions per Paragraphs Type.

http://cgit.drupalcode.org/paragraphs/tree/modules/paragraphs\_type\_permissions/paragraphs\_type\_permissions.info.yml?h=8.x-1.x

> Allows users to configure permissions for individual Paragraphs types.

# Answer
> 0 votes
I haven't used it personally, but there is a module that I believe should solve your problem:

https://www.drupal.org/project/paragraphs\_access

> Manage access and restriction to edit and view paragraphs.
>
> This module provides a node access type api to allow restriction of access to paragraph items. Companion modules provide access rules, and grants which are verified when rendering the entities.

---
Tags: 8, users, paragraphs
---


title: Map JSON data to relevant fields

text:
# Question
Title: Map JSON data to relevant fields
I have to display some data from a CRM system. I need it like following.

Let suppose I have a content type "Cars" which have following fields

```
Car ID,
Car Name,
Car Model,
Car Price

```

I am creating a node from Cars content type and want the above fields to grab data from CRM. So if Car ID is 1 then Car Name, Car Model and Price will be fetched from the CRM system.

I want to know if the data from the CRM could be available as JSON, how can we map that with these fields?

# Answer
> 1 votes
You can do this with the Drupal 8 Migrate API, which allows for setting up mappers from JSON: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview

---
Tags: 8
---


# Question
Title: Why do so few code examples use the ::load($id) method for loading entities?
Over at How to get term name from a tid? the accepted answer for "how do I get the name for a Term" is this:

```
use Drupal\taxonomy\Entity\Term;
...
$term = Term::load($tid);
...

```

That's really nice, easy to read code (and very easy to remember). It's also, as it turns out, applicable to all entity types in Drupal (just substitute the Term class for the type of entity you want).

Why then, do the overwhelming majority of the code examples and tutorials published around the place seem to advocate this monstrosity? ...

```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

```

That approach bakes in one of my \[many\] grievances with PHP in general - it's full of magic strings! How the hell am I supposed to know at "compile time" whether 'taxonomy\_term' is the right argument to `getStorage()`?? There's not a PHP IDE in the land that'll catch me sticking 'taxonomy' in there instead.

Looking at the contents of that ::load method (which is defined in \Drupal\Core\Entity\Entity and shared by all Drupal entities), it's got all the dependency-injection cleverness of that second-approach - plus it fills in the right argument to `getStorage()` for you automatically!

So why does more of the Drupal community not use it? Is there something I'm missing? Or is it just to teach us "first principles" so that we can write shared code that works with any entity type? (you'd need the long-hand way in a hook that was intended to work across all entity types).

# Answer
There is actually an issue about adding this info to the docs.

In short, the long winded version is unit test friendly.

A comment by one of the Core's contributors fully detailed explains why. Just to highlight the main point:

> If we call `Node::load()` in OO code we are breaking this principle (dependency inversion), because we are hardcoding the specific implementation (`\Drupal\node\Entity\Node::load()` to be exact). This code path is hard coupled to `\Drupal::entityManager()` which is hard coupled to `\Drupal::$container`. So now our code becomes impossible to run outside of Drupal.
>
> Furthermore, since code that uses the dependency inversion principle is fully standalone it is very easy to unit test it by mocking the dependencies according to the requested interfaces. If we introduce `Node::load()` then it becomes really hard to "properly" unit test the class, since it will start polluting the test environment with external code, and the dependency injection container is not available in unit tests.

Now if you wonder then why does Entity::load exists

> There were many loud voices at the time that D8 was going to be a DX disaster, that the OO approach was too difficult to understand and write, that it would never get adopted by the wider community. There was a huge push going on to make D8 more DX friendly, mainly driven by the Backdrop fork that was announced a few months earlier.
>
> So we created these static methods that wrap the loading of the entity manager from the container, and can be called directly from the procedural side. It was great, since it offers a drop-in replacement that works and looks very much like the original code. This made porting of procedural D7 code vastly easier:
>
> ```
> // Original D7 procedural code.
> $node = node_load($nid);
>
> // New D8 procedural code.
> $node = Node::load($nid);
>
> ```
> 7 votes

# Answer
I think this is about the target audience of the code example. If it is for a hook, then I agree, use the first more easy to read approach.

If it is for a service, then the correct approach would be to inject the entity type manager and use it instead of the static `\Drupal` wrapper.

```
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);

```

Now the question is what if you want to provide a more universal code example, then

```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

```

is probably the best approach, because it works in procedural code if you copy and paste it and can be easily adapted for a service where you want to inject the dependencies.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Setup custom required field validation for a field in custom form
How can I setup custom required field validation message for a text field in my custom form. I tried below code. But it is not working. It always showing 'Please fill out this field'.

```
$form['first_name'] = [
  '#type' => 'textfield',
  '#title' => $this->t('First Name'),
  '#default_value' => $this->store->get('first_name') ? $this->store->get('first_name') : '',
  '#required_but_empty' => $this->t('Please enter First Name'),
  '#required' => TRUE,
];

```

# Answer
> 0 votes
How do I add a custom validation to an existing form/field?

If you want to add your custom validator in addition to the default, you will have to add something like this in hook\_form\_FORM\_ID\_alter (or similar):

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

# Answer
> 0 votes
Set the property "required\_error" to form element. This is available in Drupal 8.6. For ex-

```
$form['name'] = [
  '#type' => 'textfield',
  '#size' => 60,
  '#default_value' => $form_state->getValue('name', ''),
  '#required' => TRUE,
  '#required_error' => t('Please select something.'),
];

```

To make this work, firstly you will have to disable HTML 5 validation on the form.

```
$form['#attributes']['novalidate'] = 'novalidate';

```

The property *#required\_but\_empty* is set automatically during validation when the required field is empty. This is an internal property and is not set manually. It allows #element\_validate handlers to set a custom required error message, but without having to re-implement the complex logic to figure out whether the field value is empty.

---
Tags: 8, forms
---


title: Create a Term Queue on views

text:
# Question
Title: Create a Term Queue on views
I have a views showing some selected terms of a vocabulary. The Views block is created using Taxonomy Terms as content(show). It showing order by the terms tree. But my client want to sort it as their business policy(most popular on top).

Is there any way to sort the terms like custom way as node queue. Please suggest me any module, hooks or other custom solutions. Here is my views settings :

Thanks in advance.

**Note that I want to sort the terms Not the entities tagging with it.** I have installed nodequeue and smartqueue but unable to achieve the requirment.

# Answer
Yes, you can add a sort option for Taxonomy term (weight), then they can reorder the terms on the taxonomy's overview page, e.g. `/admin/structure/taxonomy/manage/VOCABULARY_ID/overview`), or, if that's not sufficient, there's the Entityqueue module.
> 0 votes

# Answer
## Views Aggregation to count nodes tagged by terms

You can use Views Aggregation to count the number of nodes that each tag is assigned to, and use that as the Sort criteria.

1. In the Views of type `Taxonomy term` filter all the terms you're interested about. Add a Name Field to show the term name (you probably already have that covered)
2. Add a Relationship to the content that the terms are related to **Content using field\_yourname**
3. Turn on Aggregation (Under Advanced, third column)
4. Add a `Sort criteria` **Content: Title**, (it will automatically use the Relationship from above), **Sort descending** and adjust its Aggregation settings to **Count DISTINCT** (if you allow nodes to use multiple terms then `Count` will count them more than once)

Your terms list will be sorted by the number of nodes tagged by each term in your Views results.

## Views Summary for single value fields

If your Taxonomy term reference Field allows for only one value you can use Views summary in a Contextual filter to count the nodes tagged with a term.

You can do it from Taxonomy term Views or Content Views.

1. If starting from Taxonomy term Views you can use the above steps,
2. only instead of using Aggregation add a new Contextual filter `Name` from `Taxonomy term` Category and configure it to display a Summary:

`When the filter value is NOT available`
**Display a summary**
Sort order **Descending**
Sort by **Number of records**
`Format` **List**
`Base path` (you *must* enter the Page path if this isn't the first Page Display in your Views)
**Display record count with link**

This way you get a list of Taxonomy terms with node count next to them. When you click on them you go to another page listing the actual Fields you set up in Views (you'll probably want to list Content: Title here).

It's a similar procedure to do that from Content Views type.

1. You'll want to add a Relationship to the relevant Taxonomy field (Taxonomy term referenced from field\_yourname),
2. then add a Contextual filter for `Taxonomy term: Name`, use the Relationship and configure it to display as a Summary.
> 1 votes

# Answer
To sort Category terms list created using views. We can use EntityQueue.

To do that We need to install the EntityQueue module. Then add a entity Queue for taxonomy terms from : `admin/structure/entityqueue`

Then add term items to the queue as we want to sort.

From here we can shuffle the queue or change the sorting. After that we need to add an Entityqueue relationship to our view, and adding a sort for Entityqueue position. That way we can achieve the sorting as provided on entity queue.

Note that: We need to make sure the term on the queue list is exist on output of the view.
> 0 votes

---
Tags: views, taxonomy-terms, queue, nodes
---


# Question
Title: How to add a title text input to an image field node form widget
If you have an image field widget in a Drupal node form you can automatically edit the image alt text in there, but is it also possible to add a title text field?

When I install the File Entity module I can add title text to images by editing them from admin/content/files but it doesn't make sense to tell clients to use this admin page to finish authoring their content.

Just to be clear, I don't want to have to make every image into a node, I just want to add form input fields to the image field widget so that the file entities can get a title text in the node form.

# Answer
> 1 votes
You have to enable the title field on your image field in the manage field tabs, at the bottom of the field form. for example at example.comadmin/structure/types/manage/example\_content\_type/fields/node.example\_content\_type.field\_example\_field

Found the answer after landing here: https://www.drupal.org/project/drupal/issues/2303765

---
Tags: 8, forms, files, media
---


# Question
Title: How to call module function in template file?
I have one custom function in .module file. Need to call that function .template file. Below is my code snnipet:

```
function non_login_preprocess_page(&$vars) {

  if(module_exists('test') && function_exists('test_get_rnd_data')){
    $vars['rnd_data'] = test_get_rnd_data();
    print_r("callled"); exit;
  }
}

```

the function exists does not return true. Is anything thing missing?

# Answer
Please try bellow code and use module\_load\_include() function.

```
function non_login_preprocess_page(&$vars) {

  module_load_include('module', 'module', 'test');   // **add this line**

  if(module_exists('test') && function_exists('test_get_rnd_data')){
    $vars['rnd_data'] = test_get_rnd_data();
    print_r("callled"); exit;
  }
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Why do the facets display the wrong amount of results ?
I have two facets that are bound to the **Content Type** and the **Publish Status** of my content.

When I do simple keywords search, it works properly, the amount of result corresponds to the real results displayed.

However, when I use double quotes to narrow down the search, the search works as expected, but the amount of result is completely messed up.

The search yielded only one result, but the amount of result is not correct.

All the indexes were rebuilt, the caches were cleared, but the issue remains. Where could this issue come from ?

I'm using Solr Version: 8.x-2.2 and Facets Version: 8.x-1.1

# Answer
All that time, I was using the default Search bar from Drupal 8 (which comes with the Search API module).

The thing is, the results in the facets were the ones that were given after **Solr** handled the search, and not the **Search** module from Search API.

For basic requests like a few keywords, both search engines yielded the same results, so the facets corresponded to the result, but my configuration of Solr didn't seem to handle double quotes.

In short : Search API handles the double quotes and displays the good results, but Solr didn't handle the double quotes so the facets results were wrong.
> 0 votes

---
Tags: search
---


# Question
Title: Modify text of error message for required field
I have a checkbox with a link in its title text. This is a required field and the error message references the title including the link. How can I modify the error message to remove the link from the error message text?

`hook_field_validate()` appears not to be called; that was my first attempt after doing some searching.

# Answer
Quick and easy fix is to use the String Overrides module. Here is a quote about it (from the module's project page):

> Provides a quick and easy way to replace any text on the site.
>
> Features:
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 3 votes

# Answer
You can try to override the strings or theme the message as has been mentioned already. Another option is to override the validation function for that form or that field, and raise the error yourself with the message you want.

You can use hook\_form\_alter in various ways. You could simply replace the #validate function on the submit button on the form, and thus provide your own validation function. In that function call form\_set\_error to raise the validation problems.

If you want to keep the core validation for most fields and just override the validation for one field you could set #limit\_validation\_errors to the submit button. This allows you to define which part of the form should have errors validated (and thus, which ones should not). You'll still want to add your own validation function for the form elements you've just ignored - so add it to the functions in the #validate of the submit button.
> 2 votes

# Answer
If a field is required then the validation check for an empty value is done inside Drupal's form handling and it'll never reach your custom code.

If you were to write a custom implementation of theme\_form\_element() in your theme or module you could add an extra data member say `#display_title` with your link in it and show that as the label text in the form if present. Forms validation would then use the regular `#title` value for messages.
> 1 votes

# Answer
If this is the only thing you want to change, you can override strings in your settings.php file. Check out the default.settings.php file for examples on how to do this. For only changing a string or two, this is better than adding the overhead of another module.
> 1 votes

# Answer
In Drupal 8, you can alter the messages in the hook\_preprocess\_HOOK. Example here: How to remove status messages from admin theme?

I am not sure whether you can do the same in Drupal 7, but you could apply the same logic in the theming layer, see: function theme\_status\_messages
> 0 votes

---
Tags: 7, forms
---


title: Override user edit page title

text:
# Question
Title: Override user edit page title
By default, the user form title is the user's username which looks a little ugly if you're using the email registration module. In Drupal 7 I used to solve this problem using the title override module which is not ported do Drupal 8.

I would like to change the user form title to "Login details". Is this possible using a hook? If so: how do I do this?

# Answer
The title override module utilizes `drupal_set_title()` to do this in Drupal 7. This function is deprecated in Drupal 8. The D8 equivalent here is to alter the `_title_callback` for the `entity.user.edit_form` route.

This is done by using an event subscriber to alter the `RoutingEvents::ALTER` event. This can be done through a custom module that:

* Registering a new service class in **mymodule.services.yml** that is tagged with `event_subscriber` (see d.o. documentation example).
* Defining the new service class to extend `RouteSubscriberBase` (see d.o. documentation example).
* Implementing the `alterRoutes(RouteCollection $collection)` method within the service class to alter the `entity.user.edit_form` route (see example below).
* A class/method that defines the title callback (see `UserController::userTitle()` as an example).

Within your route subscriber class:

```
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Retrieve the user edit form route.
    if ($route = $collection->get('entity.user.edit_form')) {
      // Your module will need a controller class/method defined in
      // src/Controller/CustomUserController::userTitle
      // see core/modules/user/src/Controller/UserController.php to see how this
      // is implemented by default
      $route->setDefault('_title_callback','Drupal\mymodule\Controller\CustomUserController::userTitle');
    }
  }

```
> 11 votes

# Answer
In drupal 8 you can hide the title block :

```
/admin/structure/block/manage/pagetitle

```

for the :

```
user/* pages

```

Then create a block that display what you want for the

```
user/* pages

```

.

It can also be dynamic if you create a view block with a contextual view displaying other user fields.
> 0 votes

---
Tags: users, hooks
---


# Question
Title: Webform Fields not hidden anymore after update to 8.x-5.0-rc19
After updating to Webform 8.x-5.0-rc19 fields that should be visible only after filling another field, are instead always visible. I guess this has something to do with "Elements, containers, and pages that are hidden using conditional logic will have their submission data cleared when a webform is submitted" (https://www.drupal.org/node/2956589), but I do not understand how.

# Answer
Please see #states breaks when OR is used
> 2 votes

---
Tags: 8, webforms
---


# Question
Title: Is there a REST endpoint for getting the logout token?
So I know the logout\_token is generated along with the csfr\_token during the POST to /user/login?\_format=json.

You can get a copy of the csfr\_token for the session at any time by calling a GET on /session/token. Is there a way to get the logout token outside of the user logging in? So is there a path that once logged in will provide you with the logout\_token? I'm looking for a way to clear a cookie that gets stored beyond the initial session.

# Answer
> 4 votes
It appears this does not currently exist. I just created a patch for core. Please review it and make suggestions if you have a chance. https://www.drupal.org/project/drupal/issues/3004421

I will edit this answer if any progress is made with the patch.

---
Tags: 8, users
---


title: REST logout without logout_token

text:
# Question
Title: REST logout without logout_token
I have a small app I'm working on and after I created a new build I'm unable to login or logout. This seems to happen because drupal thinks I'm logged in but my app doesn't have the user details in local storage. So I don't know the `logout_token` needed to logout from app.

Is there a way I can fix this?

# Answer
> 1 votes
Marius,

When you login using rest api, csrf and logout tokens are generated. use the logout\_token generated to logout form your app. Make a post request to

```
/user/logout?_format=json&token={logout_token}

```

Sample code to logout from your app will be similar to

```
 var xhr = new XMLHttpRequest();
 xhr.withCredentials = true;

 xhr.addEventListener("readystatechange", function () {
   if (this.readyState === 4) {
     console.log(this.responseText);
   }
 });

 xhr.open("POST", "http://example.com/user/logout?_format=json&token=logout_token");
 xhr.setRequestHeader("content-type", "application/json");

 xhr.send(data);

```

Hope that helps.

# Answer
> 1 votes
If you are using cookie based login you can go into the Application tab then on the left hand side Cookies \> your-site-name in the dev console and delete the cookie that starts with SESS. This will log you out. To the best of my knowledge there isn't a way to request a logout\_token after it is initially created during /user/login. So in your case if you still have an active session (using cookies) you are sort of stuck. I just submitted a patch for review in core which addresses this. I'd kindly ask that review it and make suggestions if you have a chance. https://www.drupal.org/project/drupal/issues/3004421

---
Tags: 8
---


title: Show full query for anonymous user

text:
# Question
Title: Show full query for anonymous user
I'm currently troubleshooting an issue where anonymous users and certain roles see a different set of results from a view than administrators and roles with more permissions do. The view is supposed to have two node results, but for anonymous and others, there is only one.

I am trying to get the full SQL of the final query that's creating the anonymous pages. I'm using `hook_views_query_alter()`, and I can get the full query using `dpq($view->query->query());` when I'm logged in as an administrator.

However, when I'm an anonymous user, or one of the other roles encountering the bug, I get SQL like this: `((taxonomy_index.status = :db_condition_placeholder_7) AND (node_field_data.type IN (:db_condition_placeholder_8)))`.

I tried getting the placeholder values from a technique I used in drupal 7, using the `arguments()` method, but apparently that doesn't exist in Drupal 8.

But moreover, I would like to avoid matching up the string `db_condition_placeholder` manually, because I could make a mistake, and misdiagnose what the source of the problem is. I want the full query string that drupal sends to the database, so that I can debug it directly with the MySQL server.

I tried other techniques listed here, such as `->addTag('debug')`, which apparently did nothing, and `kint($view->query->query());`, which only returns output for administrator users.

How can I get the full query string from a view executed for anonymous users?

# Answer
Note: This does not answer the question of "trying to get the full SQL of the final query that's creating the anonymous pages", but answers the underlying issue.

**tl;dr Checking the Advanced Settings \> Query \> Disable SQL Rewriting option will allow views to return consistent results.**

### Explanation

The views module (contrib and core) configures views with restrictive entity access enabled by default. This sends the query object through `hook_db_rewrite_sql` (6), `hook_query_TAG_alter` (7, 8). Nodes for instance will add in joins to the `node_access` table, which can be prohibitively expensive on queries.

**This is important** for sites that use complex entity access where one node may be hidden from view based on node grants/access rights.

However query results will be different when querying entities (such as nodes) depending on if you are logged in. This can be frustrating when building a view as a site builder - what you see is not what you get.

It may not necessary to use SQL rewriting because a view has other access restrictions. **Checking the Advanced Settings \> Query \> Disable SQL Rewriting option will allow views to return consistent results.**

This is usually the first thing I do when creating a view unless I specifically need the extra access checks because

1. It improves performance significantly.
2. I create selective and filtered views that naturally restrict data using filters, contextual filters and view access restrictions.

### Update 2019.06

Note that the views module changed the label for this setting from "Disable SQL Rewriting" to "Disable Access Checks".
> 2 votes

---
Tags: views, 8
---


# Question
Title: Is it possible to replace page arguments with new ones in a view exposed filter?
I'm creating a views filter with the exposed form.

After its submitting a new page is loaded with arguments like these (I use the Acquia Dev desktop)

```
http://pal.dd:8083/en/cities?country_id=2&region_id=4

```

I want to make the string shorter, for example, like this

```
http://pal.dd:8083/en/cities?geo=2_4

```

And in the query() method transcribe this argument and get country and region value from it.

I'm wondering, is it possible to do it inside the view filter class?

I tried to manipulate with the values of the exposed form in the submitExposed function, but I didn't manage to achieve the positive result.

Has anybody run into it?

# Answer
You can adjust the default `Filter identifier` for each Exposed Filter in its settings. The Description:

> **Filter identifier**
> _
> This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("\_"), and tilde ("~") characters are allowed.

In your case you can chage the first one to `geo` and the other to `_`. That way you get the output:

`cities?geo=2&_=4`

although you'd probably name the second one to something more meaningful, like `region`:

`cities?geo=2&region=4`

For full control use the module Query Parameters To URL (Drupal 8 version Needs work).
> 1 votes

---
Tags: views, 8
---


# Question
Title: How can I get the active menu trail for the current page?
If I use Drupal::menuTree() to load a menu it seems to always have inActiveTrail set to FALSE for all my items.

As an example consider the following code:

```
$menu_tree = Drupal::menuTree();
$parameters = new MenuTreeParameters();
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

```

That code returns the top level of the main menu with inActiveTrail = FALSE for all items regardless of what page I am on.

I believe MenuTreeParameters::setActiveTrail() is meant to help here but then I have to pass in an active trail.

How do I get the active menu trail for the current page load so I can then pass it in?

# Answer
> 7 votes
`MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters()` is what you want. To use the example above:

```
$menu_tree = Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters('main');
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

```

The resulting menu tree should have `inActiveTrail` flagged.

# Answer
> 3 votes
Use the active menu trail service, `menu.active_trail`, returns `\Drupal\Core\Menu\MenuActiveTrailInterface`. You can then use it to identify the active trail(s), and then retrieve it from the menu tree(s). Saves a foreach loop over the various menu items and testing for `inActiveTrail`.

`$ids = $this->activeTrail->getActiveTrailIds('main');
$parameters = (new MenuTreeParameters())->setActiveTrail($ids);
$tree = $this->linkTree->load('main', $parameters);
$active = $tree[reset($ids)]; // There may be more than one...`

---
Tags: 8
---


title: Display node with mixed languages

text:
# Question
Title: Display node with mixed languages
My nodes, with entity translation enabled, need to be able to handle a node where the content of the node is displayed differently regarding the labels and menus.

Let's say I am on a french page, displaying a list of all nodes, translated into french or not. If I click on a non-translated projects url I need the node to be displayed in a french environment (menus and labels in french) but displaying the node in its original language.

Any idea how to achieve this?

# Answer
> 1 votes
This is more or less the default behavior, depending on your Languages Detection and selection configuration.

In Drupal 7 every translation of a node is a new node, with its own node ID. So when you call for that node it will be displayed (call it by node/\[nid\] or a path alias).

Interface language (menus etc) is calculated separately from content, by the Detection and selection settings (`/admin/config/regional/language/configure`).

The most common setting is to only enable the `URL` Detection method and configure your default language not to use the `Path prefix language code` or `Language domain` and set one for all the other languages.

This way if you have an English node and you want to open it with a French interface the link should be constructed as:

`/fr/node/[englishID]`

or

`/fr/[french-path]/[english-title-pattern]`

So whatever method you're using to display node lists you have to adjust their URLs output to follow that logic.

---
Tags: 7, entities, nodes, i18n-l10n
---


title: Redirect user on specified route

text:
# Question
Title: Redirect user on specified route
I know we can easily redirect a path to another path with Redirect module, but what I want to do is more complicated, my condition is when the user has a specified IP and the route is matched with to a specified path redirect it.

Pseudo code what I'm looking for is

```
if $path='xxxxx' and $user_ip = 'yyy.yyy.yyy.yyy' redirect to 'zzzzz'

```

how I can implement this, what I need is where is the best place to implement this?

# Answer
> 1 votes
You can alter the routes (conditionally based on IP) by creating an event subscriber or by using a RouteSubscriber. You should also look at altering existing routes.

---
Tags: redirection, services
---


# Question
Title: Create view of child terms below parent term and how many nodes are tagged with those child terms
I have a content type called 'schools' and I have a vocabulary called "destinations" that contains:

```
-USA
-- New York
-- Miami
-UK
--London
--Manchester

```

I have 2 school nodes that are tagged with "New York" and "Miami", respectively. So:

```
School 1: Terms tagged with from "Destinations" vocabulary: "USA",  "Miami"
School 2: Terms tagged with from "Destinations" vocabulary: "USA",  "Miami"
School 3: Terms tagged with from "Destinations" vocabulary: "USA",  "New York"

```

I want to show a view on the top country level page. So on the USA page I want to show:

City: New York No of Schools: 1 Name of School: School 3

City: Miami No of Schools: 2 Name of School: School 1, School 2

I know how to create a view to show me the city name using a contextual filter: Taxonomy term: Parent term. But is there a way I can get the other two things to show: count of schools and name of schools? In the same view..

# Answer
> 0 votes
The problem with your question is that you want to use both Aggregated and Grouped data in the same Row.

Additionally you want to show more than one School in the same Views row, while the Title isn't a multi-value field, you're not linking Schools from Terms but Terms from Schools.

You can use an additional module to achieve that: Views Field View, although it may be performance heavy.

You can easily create a View that would display either one or the other case:

> City: New York No of Schools: 1
> City: Miami No of Schools: 2

To achieve that see my answer here: Create a Term Queue on views only instead of adding a Sorting criteria you add **Content: Title** under Fields and set it to Count Distinct under Aggregation settings.

Or this case:

> City: New York Name of School: School 3 City: Miami Name of School: School 1, School 2

To achieve that follow that same procedure only don't use Aggregation and under Format select the City field as a Grouping field. You can achieve many different layouts with clever Format settings and overrides.

To combine these two views use the Views Field View module to insert the second View into the First one and use the City field as an argument that you pass to the second View.

So the first View would have a Contextual filter for the Country (the first level of Taxonomy), and the second View would have a City Contextual (second level) or something along those line, depending on your particular configuration.

You should first aim to build those Views separately and make the Contextual filters work, then use the Views Field View to combine them.

Another way to go about solving this is mentioned in the Answer I linked to: Use Views Summary to display Terms with node count, then when you click on the term it takes you to actual Views results page showing nodes for that term. This is a two-step process but it may be acceptable to your visitors and it's easy to set up.

---
Tags: views
---


title: Breadcrumbs for some content types

text:
# Question
Title: Breadcrumbs for some content types
I'm using breadcrumbs generally throughout my Drupal 7 site and all working well.

However, for news articles, I don't want to have to add each into the menu structure as over time, this will be a little out of control.

I'd like content of the type = news to have

Home \> News \> Title

with an active link back to my /news page.

Is this possible whilst still using the normal breadcrumb for other content?

# Answer
> 0 votes
Just for the record, if you want to do this with Crumbs:

Go to /admin/structure/crumbs/entity-parent. For content type "News", enter "news" as parent path.

Likely it already works now. If not, check the order and status of plugins on /admin/structure/crumbs. Also check /admin/structure/crumbs/debug, where you can simulate breadcrumb-building for specific pages.

---
Tags: 7, nodes, breadcrumbs
---


# Question
Title: How to create a unit test for a class which uses a trait?
Simple as this:

```
class A {
  use StringTranslationTrait;

  public function something() {
    $b = 1+2;
    $this->t($b);
    return $b;
  }
}

```

I would like to unit test the `something()` method, but I can't since the `StringTranslation` trait uses a static container call:

```
Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$containe is not initialized yet. \Drupal::setContainer() must be called with a real container.

```

What do you suggest?

# Answer
> 7 votes
StringTranslationTrait also has a setStringTranslation() method so you can inject a string translation mock for exactly that purpose.

# Answer
> 10 votes
Following on Bedir's answer, here is an example.

I have a test that is using the class DurationService. DurationService uses the StringTranslationTrait as follows:

```
class DurationService implements DurationServiceInterface {
  use StringTranslationTrait;
  ...

```

To test this, I am doing the following (note, using a class that extends UnitTestCase):

```
$duration_service = new DurationService();
$duration_service->setStringTranslation($this->getStringTranslationStub());

```

This calls StringTranslationTrait::setStringTranslation() passing it the response from UnitTestCase::getStringTranslationStub().

# Answer
> 1 votes
Here is how I solved it, note your test must extend Drupal\Tests\UnitTestCase:

```
  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();
    $container = new ContainerBuilder();
    \Drupal::setContainer($container);
    $container->set('string_translation', self::getStringTranslationStub());
  }

```

# Answer
> 0 votes
By implementing the ContainerFactoryPluginInterface you can use dependency injection to fake the string translation service.

```
class A implements ContainerFactoryPluginInterface {
  use StringTranslationTrait;

  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, TranslationInterface $string_translation);
    $this->stringTranslation =$string_translation;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('string_translation'));
  }

  public function something() {
    $b = 1+2;
    $this->t($b);
    return $b;
  }
}

```

# Answer
> 0 votes
Just take a look at the FormValidatorTest:

For the class

```
/**
 * Provides validation of form submissions.
 */
class FormValidator implements FormValidatorInterface {

  use StringTranslationTrait;

  public function __construct(RequestStack $request_stack, TranslationInterface $string_translation, CsrfTokenGenerator $csrf_token, LoggerInterface $logger, FormErrorHandlerInterface $form_error_handler) {
    $this->requestStack = $request_stack;
    $this->stringTranslation = $string_translation;
    $this->csrfToken = $csrf_token;
    $this->logger = $logger;
    $this->formErrorHandler = $form_error_handler;
  }

```

This is the test

```
  /**
   * Tests the 'validation_complete' $form_state flag.
   *
   * @covers ::validateForm
   * @covers ::finalizeValidation
   */
  public function testValidationComplete() {
    $form_validator = $this->getMockBuilder('Drupal\Core\Form\FormValidator')
      ->setConstructorArgs([new RequestStack(), $this->getStringTranslationStub(), $this->csrfToken, $this->logger, $this->formErrorHandler])
      ->setMethods(NULL)
      ->getMock();

    $form = [];
    $form_state = new FormState();
    $this->assertFalse($form_state->isValidationComplete());
    $form_validator->validateForm('test_form_id', $form, $form_state);
    $this->assertTrue($form_state->isValidationComplete());
  }

```

You can use as constructor param `$this->getStringTranslationStub()`

---
Tags: 8, testing
---


# Question
Title: The PHP version is not correctly detected
I'm running Drush on a host that has multiple versions of PHP installed. By default, `php --version` would give you 5.2.x, but php53 and php54 are also available. So in my .bash\_profile I have `alias php='php53'` (`php --version` = 5.3.13), which makes Drush work for some commands.

However, I still get "Your command line PHP installation is too old. Drush requires at least PHP 5.3.2" messages for some very useful commands.

A couple of really annoying instances:

* `drush pm-update` will report that it has backed up and then updated all modules and core successfully, then return the PHP version error and restore all backups. In verbose mode, the command that comes before the error is: `php /home/[username]/drush/drush.php --backend=2 --verbose --root=/home/[username]/webapps/drup --uri=http://[domain name] pm-updatecode-postupdate 2>&1`
* `drush archive-dump` will immediately return the PHP version error

The other commands I have tried so far work fine. I'm not sure why this would be, if Drush is sometimes using the php53 binary, and other times not, or if it just has trouble detecting the version correctly, but some very important features are broken for me.

# Answer
> 21 votes
Drush doesn't use just php directly as a command, but need the full path. With the last version of Drush, you can add the following line in your `.bash_profile` to set which PHP you want to use.

`export DRUSH_PHP=/Applications/MAMP/bin/php/php5.3.14/bin/php`

Here is just an example of MAMP, but you can change it as well with your own path.

# Answer
> 2 votes
Here's another solution:

1. Create a symbolic link to the desired version of php (php5.4 in my case) ln -s /usr/local/bin/php54 ~/bin/php
2. we need to change precedence of ~/bin in $PATH so that it appeared before /usr/local/bin (where original php interpreter sits) find ~/ -name .bash\_profile | xargs sed -i 's/\\$PATH:\\$HOME/bin/\\$HOME/bin:\\$PATH/g'
3. reload .bash\_profile source ~/.bash\_profile

sourced from: http://webiga.com/2013/06/22/change-default-version-of-php-at-webfaction/

# Answer
> 1 votes
The problem for me was that drush was not working with the correct PHP version, I think the problem was that it was using PHP 7, and I needed PHP 5.6. So I ran in the console:

> whereis php

And the result was (see the PHP path for 5.6):

Then I went to my ~/.bashrc file and added one line that sets PHP path for drush (and save):

> export DRUSH\_PHP=/usr/bin/php5.6

Then I updated .bashrc with the following (don't miss the point in the start of the command):

> . ~/.bashrc

And that's it! Hope that helps!

# Answer
> 0 votes
I just ran into this after upgrading Drush on Windows. The server has an older version of PHP running and it wasn't picking up the version of PHP that came with Drush.

I was able to fix it by specifying the path to php.exe in the drush.bat file, located at

c:\documents and settings\all users\application data\drush\drush.bat

I just added the full path to PHP by changing this line:

@php.exe "%~dp0drush.php" --php="php.exe" %\* to this:

@"c:\program files\drush\php\php.exe" "%~dp0drush.php" --php="php.exe" %\*

# Answer
> 0 votes
Assuming you installed drush with composer and you want to run your command using php 7 (this works for acquia cloud envs too)

/usr/local/php7.1/bin/php ../vendor/drush/drush/drush.php --php=/usr/local/php7.1/bin/php \[your\_drush\_command\_here\]

---
Tags: drush
---


# Question
Title: how to post an article by jquery using REST service of Drupal?
i want to create an article by rest services of drupal ? as given in the documentation on Drupal Post docs link

but it gives an error `Reference error : Drupal is not defined`

in the following line of code `jQuery.get(Drupal.url('rest/session/token'))`

here is my code based on docs

```
function getCsrfToken(callback) {
  jQuery.get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://localhost/dr/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken

    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  _links: {
    type: {
      href: 'http://localhost/dr/rest/type/node/article'
    }
  },
  type: {
    target_id: 'article'
  },
  title: {
    value: 'Example node title'
  }
};

getCsrfToken(function (csrfToken) {
  postNode(csrfToken, newNode);
});

```

# Answer
> 0 votes
You need to enclose your javascript

```
(function ($, Drupal) {

  ...

})(jQuery, Drupal);

```

to access `Drupal` and the usual `$` for jQuery.

---
Tags: javascript
---


# Question
Title: Block above content should be simple however
I have a site where they are wanting to have a block above various pages without having a ton of blocks on the blocks layout page. For example they want a block above the login form on the user login page with a welcome message and or instructions that they can easily edit. They also want another "description block" above other pages that we cannot easily add blocks to without giving them admin access such as editing views etc. Does anyone have suggestions as to a way for me to go? I originally thought of using page manager however page manager does not let you use the main content block within itself when you override the path of an existing page.

# Answer
> 0 votes
There is a number of Block related access modules that can help you:

Block Access allows you to set individual Block permissions. So after you create those Blocks, allow the specific user Role to edit only those particular blocks above Login and other pages.

You might also create a special Region within your theme just for this purpose, and set permissions for that Region blocks with Block Region Permissions.

You can set finer control over the Admin Block pages with Block Content Permissions.

# Answer
> 0 votes
You might take a look at the Block field module. Nomen est omen: You can add blocks to page and display them just like any other (entity reference) field. With this solution blocks will be rendered inside the main `{{ page.content }}` region

---
Tags: 8, users, blocks
---