# Question
Title: Sorting a view on a taxonomy term with entityqueue
I'm trying to use an entity queue on a taxonomy to create a new sort order for an existing view. But I'm having trouble configuring it.

I've created a dummy website with a fantasy role-playing game theme. I have a content type "Monster" with a taxonomy term "difficulty".

Monsters can have several difficulty tags, but I've created an entityqueue for the subset of tags that I want to sort on:

Finally, I've created the view for monsters, with what I believe are the properly relationships to join in the entityqueue for sorting. Starting with the Monster content type, I've added a relationship to the Difficulty taxonomy term, then another relationship for the Monster Difficulty entityqueue.

Finally, I added the entityqueue as the first sort criteria:

However, the results of the view are still sorting on the title field, "Name", meaning that the sort order of the entityqueue is either not making it in or being respected:

How do I sort a view based on a taxonomy entityqueue?

**Edit** I removed the sort for the title, as per hotwebmatter's suggestion, but that didn't cause it to sort by the entityqueue.

The order should go Big boss, boss, mini-boss, etc., but it doesn't.

Here are the configuration export ymls of those files different from a vanilla install: https://pastebin.com/r4A94QJ5

# Answer
I think that the **Queue Position** sort is being overridden by the **Title** sort. (In other words, the **Title** sort may be applied *after* the **Taxonomy term Queue Position** sort, making it appear as though the queue is not respected.)

If that's the case, then removing the **Title** field from the Sort criteria should be enough to get this working.

In case that's not sufficient, here's a good video tutorial on Entityqueue.
> 0 votes

---
Tags: views, queue
---


# Question
Title: How to move block from a region inside of hook_preprocess_node?
I have added `mycustomblock` to the `header` region in our settings `(/admin/structure/block)`. We are using the standard `content` block and displaying that in the `Content` region, which is displayed below the `Header` region.

For just our `Basic Page` content type, we would like to move the `mycustomblock` to display below another field. We tried using the `mymodule_preprocess_node` hook to move the block below one of the fields (i.e. `field_categories`). However, we don't know how to move the block.

**How would we move the block inside the `hook_preprocess_node`?**

Setup:

`Basic Page content type`

* Title
* Categories (field\_categories)
* Tags (field\_tags)
* Image (field\_image)

`node--page--full.html.twig`

```
{{ label }}
{{ content.field_image }}

/* I want to display the block here, using some variable */
{{ mycustomblock_variable }}

{{ content.field_categories }}
{{ content.field_tags }}

```

Regions (order displayed: top down)

1. header
2. content
3. footer

We tried the following but it didn't work

```
function mymodule_preprocess_node($variables) {
  $node = $variables['elements']['#node'];

  if($node->bundle() == 'page') {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(123456);// BLOCK_ID
    $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'mycustomblock');
    $variables['mycustomblock_variable'] = $block_view;
  }
}

```

# Answer
> 1 votes
I think you should send render of the block not an array of block entity.
View Method return an array.

Try with `renderer` service like the following:

```
/**
 * Implements hook__preprocess_HOOK().
 */
function mymodule_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  if ($node->bundle() == 'page') {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(12345);//BLOCK_ID
    $block_view = \Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
     // Change here default by your block view mode
      ->view($block_entity, 'default');
    $variables['mycustomblock_variable'] =\Drupal::service('renderer')->renderRoot($block_view);
  }
}

```

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


title: voting entity reference field

text:
# Question
Title: voting entity reference field
I have two content types, game and player. Each game can have a number of players assigned to it. I would like to have the capability to give votes to each player in a game. What are some ways to do this? Is there documentation, or blog posts with detailed examples?

# Answer
> 0 votes
It's hard to recommend something without more specifics. How are you imagining the way people can vote? Are they voting for their favorite player for that game, and can only vote for one player per game? Do they give "thumbs-up" to as many players as they want? Do they assign X out of 5 stars to a player?

The Fivestar module is very popular, and has pretty good documentation.

The Rate module is also popular, has a lot of different ways of voting, and there is a YouTube video showing how to use it.

---
Tags: 7
---


# Question
Title: How do I programmatically delete a node by internal url alias?
How do I programmatically delete a node with a specific internal url alias?

Background: We are trying to delete this node so that it can be replaced during an update hook.

# Answer
After some digging around through the available services and core classes, I have determined you need to get the *nid* through the *path.alias\_manager*. Additionally you need to wrap everything in a couple of conditions or you will throw errors if the path does not exist. (eg. if you are trying to roll this change out to a fleet of sites that might or might not have this path already)

Below is my example code:

```
  // Check the path is valid before proceeding.
  $pathIsValid = \Drupal::pathValidator()->isValid('/blog');

  if ($pathIsValid) {
      $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/blog');
      $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
      // Get nid.
      $nid = $params[$entity_type];
      $node = Node::load($nid);

      // Check if node exists with the given nid.
      if ($node) {
      $node->delete();
    }

```
> 2 votes

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


# Question
Title: How can I have Devel generate nodes with different terms and not always the same term?
I am using the Devel module to generate content (nodes) as a test. The content type has a field referencing a vocabulary that has terms already added to it. When 1000 nodes are generated, Devel assigns the same term to every node (the first term in the vocabulary). Is it possible to have Devel assign different terms at random to different nodes? How about setting one term as the default value for the field?

# Answer
This happens when you have a default term chosen for the content type.

If you remove the default, it will then randomly choose terms that already exist (if they exist) or randomly generate terms if the vocabulary allows it.
> 3 votes

---
Tags: taxonomy-terms
---


title: Why doesn't the batch process start?

text:
# Question
Title: Why doesn't the batch process start?
I've created a class that extend the 'FormBase' class to create a form where I can upload a XLSX file to import into custom DB table.

To process the import I would use the 'Drupal batch process' to show to the user the progress of import.

These are the methods I wrote.

```
    class CommissionerImportUmpiresListForm extends FormBase {

      public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
        $form_file = $form_state->getValue('my_file', 0);
        if (isset($form_file[0]) && !empty($form_file[0])) {
          $f = File::load($form_file[0]);
          $f->setPermanent();
          $f->save();
          $this->setSheetData($this->commissioner_read_file($f->getFileURI()));
          $orig = $this->getSheetData();
          $clean = array_shift($orig);
          $this->setSheetData($orig);
          $operations = [];
          $c = count($this->getSheetData());
          foreach ($this->getSheetData() as $row) {
            $operations[] = [
              ['Drupal\commissioner\Form\CommissionerImportUmpiresListForm', 'batch_run'],
              [$row, $c],
            ];
          }

          $batch = [
            'title' => t('Importing the umpires list...'),
            'operations' => $operations,
            'finished' => ['Drupal\commissioner\Form\CommissionerImportUmpiresListForm', 'batch_finished'],
            'init_message' => t('Importing is starting.'),
            'progress_message' => t('Processed @current out of @total.'),
            'error_message' => t('Importing has encountered an error.'),
          ];
          batch_set($batch);
          batch_process('admin/config/content/umpire_list');
        }
      }

      private function commissioner_read_file($file) {
        $sheetData = [];

        try {
          $real_path = \Drupal::service('file_system')->realpath($file);
          $inputFileType = IOFactory::identify($real_path);
          $reader = IOFactory::createReader($inputFileType);
          $spreadsheet = $reader->load($real_path);
          $sheetData = $spreadsheet->getActiveSheet()->toArray(NULL, TRUE, TRUE, TRUE);
        }
        catch (Exception $catch) {
          \Drupal::messenger()->addMessage($catch->getMessage(), \Drupal\Core\Messenger\MessengerInterface::TYPE_ERROR);
        }

        return $sheetData;
      }

      public static function batch_run($row, $count, &$context) {
        if (empty($context['sandbox'])) {
          $context['sandbox']['progress'] = 0;
          $context['sandbox']['max'] = $count;
        }

        $context['sandbox']['progress']++;
        $context['sandbox']['current_umpire'] = $row;

        // Do something with the row.
        $result = \Drupal ::database()
          ->insert('mytable')
          ->fields([
            'cognome' => $row['A'],
            'nome' => $row['B'],
            'categoria' => $row['Z'],
            'qualifica' => $row['AA'],
            'livello' => $row['AB'],
            'comitato' => $row['AC'],
            'email' => $row['T'],
            'cell' => $row['S'],
          ])->execute();

        $context['results'][] = $row;
      }

      public static function batch_finished($success, $results, $operations, $elapsed) {
        if ($success) {
          $message = \Drupal::translation()
            ->formatPlural(count($results), 'One umpire imported.', '@count umpires imported.');
        }
        else {
          $message = t('Finished with an error.');
        }

        \Drupal::messenger()->addMessage($message, \Drupal\Core\Messenger\MessengerInterface::TYPE_STATUS);
      }
    }

```

I tried executing the form, but after the initial XLSX reader, that created the array with the rows in the file, the batch process doesn't start.

What's wrong? Why doesn't the batch process start?

# Answer
Check out the example on Batch operations. And remove `batch_process()` from your code. Since you are starting the batch in a form submit handler `batch_process()` is interrupting that. Just `batch_set()` and Form API takes care of the rest.

> ```
> // Only needed if not inside a form _submit handler.
> // Setting redirect in batch_process.
> batch_process('node/1');
>
> ```
> 1 votes

---
Tags: 8, forms, batch-operations
---


# Question
Title: How can we check whether block is enabled or disabled in .theme file?
I am displaying a block in twig and i am passing twig variable from `hook_preprocess_page`. But the issue when i disable the block from backend still its showing up in frontend. Im not able to get status of the block. Can anyone help me. Below is my code:

```
$lang_block = Block::load('dropdownlanguage');
  //if (!empty($lang_block)) {} also i tried.

  if (isset($lang_block)) {
    $content = \Drupal::entityTypeManager()->getViewBuilder('block')->view($lang_block);
      $variables['language_block'] = $content;
  }

```

In **.twig file** :

```
{%  if language_block %}
   {{ language_block }}
{% endif %}

```

# Answer
Use ConfigEntityBase::status:

```
if (isset($lang_block) && $lang_block->status()) {
  // block is enabled
}

```
> 0 votes

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


# Question
Title: How to know a user can access node/{nid} and node/{nid}/latest in fastest way
I have a view displaying list of latest node revisions.

The view has `title` field.

The website gives users permissions to access `node/{nid}`(shows latest revision if published default revision doesn't exist) and `node/{nid}/latest` (shows latest revision if defaut revision and latest revision is different) depending moderation state and user groups.

I want to override the view's title field according to the rules below:

* if current user can access `node/{nid}/latest` the title links to the page
* else if current user can access `node/{nid}` the title links to the page
* else show only title text

Dozens or hundreds of people may simultaneously access the view so I want to keep it fast to display. What is the fastest way to check those?

edit: I searched about `hook_node_grants` but it only supports view/update/delete operations so I think it can't hold data for `node/{nid}/latest`. Should I store every pattern in table just like `node_access` table does and look up on it when view is updated?

# Answer
> 3 votes
If you know the route name you can check access in PHP. For the second link you can use this route:

`\Drupal::service('access_manager')->checkNamedRoute('entity.node.canonical', ['node' => '1']))`.

You can find the first one with the help of the Devel module when you click on *Current Route Info* while displaying the content and look for `[_route]`.

I would put the nid into the title field and override the field content in a preprocess hook. Display the link for each route if the access check returns true. Caching is no problem because caching is by default permission based.

---
Tags: 8
---


# Question
Title: Twig template print all comments but not the comment form
For context: in my template file node--some-node.html.twig i have a grid of items which have a custom comment form on them. The form creates a comment through an API. The form passes the ID of the grid item it is under to the API and the created comment then has a field\_profile\_id with the item's id in it. Now, in the template file I need to output JUST the comments that belong to that grid item.

When I write this into the template file: `{{ content.field_comments }}` i get the output of all the comments that belong to this node and underneath I get the comment form (which I don't need). Ideally I would like to do everything in the same template file, so I could do something like this: `{% if entity.nid.value == content.field_comments.someComment.field_profile_id %}
{# output the comment here #}
{% endif %}`

Here the `entity.nid.value` is the node id of the grid items I was talking about earlier.

EDIT: Theoretically what I need to do is:

* Iterate through all possible comments for this node.
* Check if comment has some ID value (that a grid item might have)
* If the IDs match, print out the comment, if it doesn't skip it

# Answer
> 1 votes
You must add a file to your template called

**field--comment.html.twig**

Use the following code.

```
{#
/**
 * @file
 * Theme override for comment fields.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 * @see comment_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'comment-wrapper',
  ]
%}
{%
  set title_classes = [
    'title',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}
<section{{ attributes.addClass(classes) }}>
  {% if comments and not label_hidden %}
    {{ title_prefix }}
    <h2{{ title_attributes.addClass(title_classes) }}>{{ label }}</h2>
    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}
    <h2 class='title comment-form__title'>{{ 'Add new comment'|t }}</h2>
    {{ comment_form }}
  {% endif %}

</section>

```

# Answer
> 0 votes
So the node in question had a field field\_comments, from which I was trying to access the comments. I found a different way of doing that - I created a MYMODULE\_preprocess\_template function, loaded all comments of the node in that function, created a variable "comments", where I stored the comment data I needed and passed it on to the twig template. Here's the code in MYMODULE\_preprocess\_template function:

```
$node = \Drupal::routeMatch()->getParameter('node');

$user_comments = [];
  $entity_manager = \Drupal::entityTypeManager();
  try{
    $storage = $entity_manager->getStorage('comment');
    $comment_field = $node->get('field_comments');
    $comments = $storage->loadThread($node, $comment_field->getFieldDefinition()->getName(),\Drupal\comment\CommentManagerInterface::COMMENT_MODE_FLAT);
    if(empty($comments)){
      return;
    }
    foreach($comments as $comment) {
  $user_comments[] = [
    'cid' => $comment->id(),
    'user_id' => $comment->get('field_prf')->value,
    'comment' => $comment->get('field_comment')->value,
    'alias' => $comment->get('field_alias')->value,
    'rating' => $comment->get('field_rating')->value
  ];
}

  } catch (\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException $e) {
  } catch (\Drupal\Component\Plugin\Exception\PluginNotFoundException $e) {
  }
  $variables['user_comments'] = $user_comments;

```

---
Tags: 8, theming, comments
---


# Question
Title: How do I get paragraph fields text data without the <p> tags?
I am trying to pass my paragraph field data from Drupal to a component that I have created in Twig. My component echos out data like so:

```
<p class='my-custom-class'>{{ my_var }}</p>

```

In my template file, I am passing data to the component like so:

```
{% include '@components/my-component-name.twig' with {
   my_var: content.field_my_var_name.0
   ...
} %}

```

However, when this loads in my browser, what I am getting is:

```
<p class='my-custom-class'></p>
<p>The contents of my var.</p>

```

How can I load the contents of `my_var` into my `<p>` tag without getting another tag injected?

# Answer
> 3 votes
Does your field contain other `<p>` tags you want to preserve? Or just this one in the beginning and end? If you don't need to preserve other `<p>` tags, you could simply use Twig's `|striptags` filter.

```
<p class='my-custom-class'>{{ my_var|striptags('<p>') }}</p>

```

Or as @Hudri suggested in the comments under your question you may change the field type to something other than formatted text. Or maybe try changing the text format to plain.

---
Tags: 8, paragraphs
---


# Question
Title: How to provide a filter based on json:api for referencing nodes with a term reference field?
I am working with the Entity Share module to synchronize content between Drupal instances and I need a filter to define which content can be shared.

My use case is almost identical to the one mentioned in this support issue. The only differences being that the content type is a basic page and the term reference field is called `field_share_to` which in turn references a taxonomy vocab called `Sites`. I also have only two sites; 1 server and 1 client.

I am struggling to configure the correct path for term reference field and value for the term ID(64)

> Enter the machine name of the field / property you want to filter on. You can reference field / property of a referenced entity. Example: uid.name for the name of the author.

So. How to define the machine name for the jsonapi property that would return nodes filtered by term id 64?

I ask this question as a site builder rather than someone who spends a lot of time working with code.

# Answer
The module maintainer was able to provide with the answer.

field\_share\_to.entity.tid = 64

And also with a link to further reading
> 0 votes

---
Tags: 8
---


# Question
Title: how to create view that display just 2 level of taxonomy vocabulary
i have a vocabulary that contain plus of 5 level descendant, i need to create the view to display the first 2 levels and grouping by the first one, i do this:

1. **FIELDS**: (Parent) Taxonomy term: Name - Taxonomy term: Name
2. **FILTER CRITERIA**: Taxonomy vocabulary: Machine name (= All Type Announce)
3. **SORT CRITERIA**: (Parent) Taxonomy term: Weight (asc)
4. **RELATIONSHIPS**: Taxonomy term: Parent term

and i get all list of taxonomy for this vocabulary grouping by parents, how to set only 2 levels?

# Answer
> 1 votes
It's simple. In fact, there is no need to add any relationship in the Views. Just create the taxonomy term view and add a filter criteria of **Taxonomy term: Parent term**. (see screenshot) Then set the value to be equal to `''`. This will fetch you all the parent terms as they don't have any parent! (`''`)

# Answer
> 0 votes
You should be just fine by introducing 2 chained parent relationships. Setting the criterion where parent of the parent is NULL should work. Well, this is a purely UI way of doing that, which is a pro. The con is that queries with nested relations might become heavy at some point, therefore consider turning on Views cache when you deploy the site.

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


# Question
Title: Different CSS file when in development mode
Using Gulp I create two css files. One style.css and one style.min.css. Is it possible to load the style.css when developing (locally) and the style.min.css when in production (remote)?

# Answer
> 3 votes
You can specify two different libraries in mymodule.libraries.yml. Then in your mymodule.module file attach the one that matches your current deployment env:

```
function mymodule_page_attachments(array &$attachments) {
  if (PRODUCTION) {
    $attachments['#attached']['library'][] = 'mymodule/lib_prod';
  } else {
    $attachments['#attached']['library'][] = 'mymodule/lib_dev';
  }
}

```

I am using code like this to decide on which deployment level I am:

```
  public static function getDeploymentStage() : string {
    // lazy cache
    static $ds = null;

    if (null == $ds) {
      if (isset($_SERVER['SERVER_NAME'])) {
        switch ($_SERVER['SERVER_NAME']) {
          case 'anwalt-seiten.de':
          case 'www.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_PROD;
            break;
          case 'stage.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_STAGE;
            break;
          default:
            $ds = AsdentBaseService::DS_DEVELOPMENT;
            break;
        }
      } else {
        $ds = AsdentBaseService::DS_DEVELOPMENT;
      }
    }

    return $ds;
  }

```

Note that any drush command will run in dev-mode here. You can also use $settings from settings.php or any environment variable instead.

---
Tags: 8
---


# Question
Title: How to change the date format in the date field as a select list?
On user registration page, I have added a date field in select list.

In the manage form display tab, I can set the order of the dropdown fields like day/month/year or month/day/year But I am unable to change the format of the date.

Currently in the day dropdown, it is displaying like `1, 2, 3` and I want to change it to `01, 02, 03`. Similarly in the month dropdown, it is displaying like, `Jan, Feb` and I want to display it like `January, February`.

Is this possible?

# Answer
> 1 votes
If you want to alter the way this component is shown globally, you can implement hook\_preprocess\_datetime\_form(), eg. like this:

```
function mymodule_preprocess_datetime_form(&$variables) {
  // Ensure there's a month field and it's a select.
  if (isset($variables["content"]["month"]) && $variables["content"]["month"]['#type'] === 'select') {
    foreach ($variables["content"]["month"]['#options'] as $monthNum => $label) {
      if ($monthNum) {
        // Convert month number to unabbreviated name.
        $dateObj = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F');
        $variables["content"]["month"]['#options'][$monthNum] = $monthName;
  }
}

```

}

The code for the day select will be similar.

# Answer
> 0 votes
Use `hook_form_FORM_ID_alter()`:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function <your_module>_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // your custom code here
}

```

You'll need to set the `#date_format` for your custom date field in the form array.

This entry in the Drupal.org community documentation might help you with that.

The PHP documentation for date formats may also be helpful here.

---
Tags: 8, datetime
---


# Question
Title: Is there any convention about the form IDs?
Is there a convention for the form IDs?

I see that core sometimes uses *module\_name.form\_name* and sometimes *module\_name\_form\_name*.
In my case, I'm using *module\_name.form\_name*.

# Answer
> 6 votes
Drupal core doesn't use the dot in the form IDs because, as the documentation for `FormInterface::getFormId()` says, the form ID should be a unique string that can be a valid PHP function name, since it's used in hook implementation names such as `hook_form_FORM_ID_alter()`.

The form IDs Drupal core uses follow the `<module name>_<form name>` schema, so you will find form IDs like the following.

* user\_admin\_settings
* action\_admin\_manage
* layout\_builder\_add\_block

As long as the form ID is unique, any scheme would work. The convention to prefix an ID with the module name (i.e. the module machine name) has been used from Drupal since many years.

---
Tags: 8, forms
---


# Question
Title: Why is the --uri option needed to return absolute URLs?
I want to execute a View and export the JSON file to the files directory. I am using Views Data Export and VDE drush add-on modules. My view has a file/PDF field and I want to provide a direct link to the PDF file. So I added a Views relation for the field and a file URI formatter field. When I go to see the output the View creates at the Path. The URL is an absolute link directly to the PDF file. The URL includes the domain name when viewing it on development or production instances. And this is what I want. This is the correct URL path in the JSON:

```
href=\u0022http:\/\/mysite.com\/files\/Allergens.pdf

```

But when I use this Drush command below provided by `views_data_export` or `vde_drush`

```
drush vde myview myviewid myfile.json

```

the domain name is stripped out like this:

```
href=\u0022http:\/\/default\/files\/Allergens.pdf

```

Why is this happening only when using the Drush command? I found I can fix it by adding this at the end of the command

```
--uri=mysite.com

```

So my new drush command looks like this:

```
drush vde myview myviewid myfile.json --uri=mysite.com

```

But doing this will hardcode the domain name into the URL. I want the URL to work on development, production and on my local. Thank you for any help you can provide.

# Answer
You can set the default uri by adding the following file. Then if you don't provide `--uri` it'll use the default.

`sites/all/drush/drush.yml`

```
options:
  uri: "https://your-site.domain"

```
> 3 votes

---
Tags: drush, uri
---


# Question
Title: How to repair "Mismatched entity and/or field definition" when "drush entity-updates" fails?
I'm developing a site in Drupal 8 in Acquia Dev Desktop 2 on Windows 10. After updating to 8.5.0-beta1 I noticed this error on my status page (although it may have been there earlier in 8.4.4):

```
ENTITY/FIELD DEFINITIONS
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Custom menu link
The menu_link_content.field_most_common_name field needs to be updated.

```

It's possible this error came from the Menu Item Extras module, which I had installed a couple of months ago, but since deleted.

Following popular advice, I ran `drush entity-updates`. That did not cure the problem. The output (typed manually) from my CMD window is below:

```
menu_link_content entity type :
  The menu_link_content.field_most_common_name field needs to be updated.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while
performing a schema update. SQLSTATE[42522]: column not found: 1054 unknown
column   [error]
'field_most_common_name_argument' in 'where clause': SELECT 1 AS expression
FROM
{menu_link_content__field_most_common_name} t
WHERE (field_most_common_name_target_id IS NOT NULL) OR
(field_most_common_name_display_id IS NOT NULL) OR
(field_most_common_name_argument IS NOT NULL) OR
(field_most_common_name_title IS NOT NULL) OR
(field_most_common_name_data IS NOT NULL)
LIMIT 1 OFFSET 0; Array
(
)
 in Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException()
(line 1535 of C:\Users\Nick\Sites\devdesktop\drupal\core\lib\Drupal
\Core\Entity\Sql\SqlContentEntityStorage.php).
Failed: Drupal\core\EntityStorageException: !message in
Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException()
(line 1535 of
C:\Users\Nick\Sites\devdesktop\drupal\core\lib\Drupal\Core\Entity
\Sql\SqlContentEntityStorage.php).   [error]
Cache rebuild complete.   [ok]
Finished performing updates.   [ok]

```

Based on the 2nd answer here and this reference, I have made a custom module called "Database Fix" with the following content in the `database_fix.module` file. I am not a coder, so there is plenty of guesswork involved here:

```
<?php

/**
 * Fix database by updating menu_link_content.field_most_common_name field
 *
 */
function database_fix_update_8501() {
    $manager = \Drupal::entityDefinitionUpdateManager();
    if ($field = $manager->getFieldStorageDefinition('field_most_common_name', 'menu_link_content')) {
      $manager->updateFieldStorageDefinition($field);
    }
}

```

I enabled the module, refreshed pages and ran `update.php`, but it didn't work.

# Answer
> 4 votes
Although this question is quite old and no longer relevant for Drupal 8 as drush no longer has entity-updates, I believe people would still be landing on this page with Pending Entity Updates messages in the Status Report. I ran into the same scenario and wanted to address that issue.

The message is shown when the definition of the entity in the database is different from the definition of the entity in the file because of deleting or adding a field in the entity. That is something that is going to happen a lot when you are developing the module and the entity definition keeps evolving.

Uninstalling and installing the module will solve the problem because you are recreating the entity again.

I ran into this same problem and thought I should get to the bottom of this as it was not possible to keep uninstalling and installing the module.

Drush used to have entity-updates as a feature that would allow entity definitions to be updated on the fly. However this was removed from Drupal core in 8.7.0 (Support for entity updates removed from core)

The work around is to install Devel Entity Updates module and run the dentup alternative

If you are using composer

`composer require --dev drupal/devel_entity_updates`

`drush en devel_entity_updates`

`drush dentup`

That should address this problem. The devel entity updates module is to be used in develpment environments only and in higher environments you are expected to push changes to your entities through `hook_updates`

---
Tags: 8, database, updating
---


# Question
Title: How can I display a paragraph field excerpt in a search result view?
I've spent all day and night battling with Search API (with and without Apache Solr) in Drupal 8.

Does anyone know if you can use Search API to index paragraph content and then in a search views result, get back the "excerpt" of highlighted text from within a paragraph + the title of the node the paragraph is used in?

# Answer
> 0 votes
If you add the specific fields within your paragraphs to search\_api fields it will generate excerpts for them. If you just have 'Rendered HTML' of the entire page, it will not create excerpts of paragraph text.

---
Tags: 8, search, paragraphs
---


# Question
Title: How do I show multiple values from an entity reference?
I have a content *A* that uses reference from users. Users, basically, have more than a content *A*.
I have view that shows users and adds a relationship from the field used in content *A*. I added a field to show the title of content *A* related to the user.

I can show it, but if users have more than one content *a*, it shows multiple rows for the same users, instead of showing a single row listing all the referenced content *A*.

How can I achieve this?

# Answer
> 1 votes
Under multiple field settings, chekmark display all values in the same row

---
Tags: views
---


# Question
Title: Display success message after submitting form
I am try to display an success message after submitting my form and redirect to next page. The code I am using is the following.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

```

It doesn't work for me.

Is there any alternate way to do it? What code should I use to display a success message?

# Answer
The code you are showing is the same code Drupal core uses, for example in `BanDelete::submitForm()`.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->ipManager->unbanIp($this->banIp);
  $this->logger('user')->notice('Deleted %ip', [
    '%ip' => $this->banIp,
  ]);
  drupal_set_message($this->t('The IP address %ip was deleted.', [
    '%ip' => $this->banIp,
  ]));
  $form_state->setRedirectUrl($this->getCancelUrl());
}

```

As `drupal_set_message()` is used from Drupal core in `submitForm()`, that is expected to work. I cannot say why it doesn't work in your case, since you don't show the full class code. It could also be there is a module that is interfering.

For more OOP code, `drupal_set_message()` has been replaced with a service in Drupal 8.6. The code I showed (which is for Drupal 8.4) has been changed to the following. (See `BanDelete::submitForm()`.)

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->ipManager->unbanIp($this->banIp);
  $this->logger('user')->notice('Deleted %ip', [
    '%ip' => $this->banIp,
  ]);
  $this->messenger()->addStatus($this->t('The IP address %ip was deleted.', [
    '%ip' => $this->banIp,
  ]));
  $form_state->setRedirectUrl($this->getCancelUrl());
}

```

`$this->messenger()` returns an instance of the messenger service, the service that replaced `drupal_set_message()` in Drupal 8.
> 5 votes

---
Tags: 8, forms
---


title: Change Dropdown to checkbox in View

text:
# Question
Title: Change Dropdown to checkbox in View
I'm using

```
Content: Translation language (exposed)

```

in my code, And I Have two Options \- autocomplete \- dropdown

I'd like to have Checkbox, How Can I enable it?

I'm using Drupal 8

# Answer
> 3 votes
Not sure where you're trying to do this, but if it's a node edit form, you can just change the widget to "Check boxes/radio buttons" on Manage Form Display (`admin/structure/types/manage/<content_type>/form-display`). Make sure the Options module is installed.

For an exposed filter in a View, say, you can use a `hook_form_alter` to change the `#type` to whatever you want; e.g.:

```
function YOUR_MODULE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_your_field']['#type'] = 'checkboxes';

  // If there's no user input (code not shown), rebuild the form.
  $form_state->setRebuild();
}

```

Only makes sense if `#multiple` is set to `TRUE` of course.

UPDATE: Added the call to `setRebuild()`.

# Answer
> 1 votes
On Drupal 8.7.8 it is nearly the same.

Edit your themes/YOURTHEME/YOURTHEME.theme file and add

```
function YOURTHEME_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['field_your_field']['#type'] = 'checkboxes';
}

```

The setRebuild() call breaks the functionality on my system.

field\_your\_field is the system name of the field you want to change, either find it by using browser development tools or the field config of your respective content type.

---
Tags: views, 8
---


# Question
Title: How can I pass an array from a controller to a template?
I want to render array to twig file I am able to render variables but not array.

My php file :

```
  public function build() {

    $vid = 'Sectors';
    $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')-
 >loadTree($vid);
    foreach ($terms as $term) {
     $term_data[] = array(
      'id' => $term->tid,
      'name' => $term->name
     );
    }
    // echo "<pre>";
    //  print_r($term_data);
    //  die;
    // return $vid;

  // do something
    return array(
      '#theme' => 'mdoner_custom_block',
      'title' => 'MDoNER custom Block',
      //'#test' => array('key'=>$term_data),
       'testmenu' => $term_data,
    );

  }

```

My array:

```
Array (
       [0] =>
          Array (
               [id] => 1
               [name] => Climate Change
           )
        [1] =>
           Array (
                [id] => 5
                [name] => Ecotourism
          )
    )

```

.module file:

```
function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' => [
      'variables' => ['title' => NULL],
      'test' => array(),
    ],
  ];
}

```

Twig file:

```
<!-- dump(content) --> // get array of all the content
{% for key, value in testmenu %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

```

How can I pass the `testmenu` variable to twig.

# Answer
> 5 votes
You have to add the `testmenu` variable to the hook\_theme implementation, like this:

```
function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' => [
      'variables' => [
        'title' => NULL,
        'testmenu' => [],
      ],
    ],
  ];
}

```

Then you have to pass it to the render array in your `build()` function like this:

```
return array(
  '#theme' => 'mdoner_custom_block',
  '#title' => 'MDoNER custom Block',
  '#testmenu' => $term_data, // #testmenu refers to the testmenu variable you set in hook_theme().
);

```

Now you should be able to iterate over the items in the `testmenu` variable like this:

```
{% for key, value in testmenu %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

```

---
Tags: 8, theming
---


# Question
Title: Cache-Control response header includes "private"
Why does a vanilla Drupal 8 site add `cache-control: must-revalidate, no-cache, private` to all the pages?

A Drupal 7 site adds `cache-control: must-revalidate, no-cache`.

Is that addition of `private` for Drupal 8 somehow configurable? I'd like to not have it there.

It turns out that this response header in Drupal 8 is sent when `system.performance:cache.page.max_age` is set to 0. Setting it to anything greater than 0 (e.g 123) gives me `max-age=123, public`. The question still remains: Is there a way to get `must-revalidate, no-cache`?

The reason I want `must-revalidate, no-cache` without `private` is that I want browsers to always make requests for pages, and my cache server (fastly) to cache the content. Having `private` in the response headers bypasses fastly as per their documentation: https://docs.fastly.com/en/guides/cache-control-tutorial#do-not-cache

# Answer
This is caused by symfony. `private` is added via `vendor/symfony/http-foundation/ResponseHeaderBag.php` and as far as I understand it's not possible to not have it when `system.performance:cache.page.max_age` is set to 0:

```
protected function computeCacheControlValue() {
  // ...
  if (!isset($this->cacheControl['s-maxage'])) {
    return $header.', private';
  }

```

Since I don't want to hack symfony, I can remove `private` via apache mod\_header:

```
Header edit Cache-Control "(, )?private" ""

```
> 1 votes

---
Tags: 8, caching
---


title: Array not displaying in twig template

text:
# Question
Title: Array not displaying in twig template
Custom twig template is just this:

```
<ul id="rows">
  {% for product in products %}
    <li>{{ product.title }} <a href="{{ product.image }}">Image</a> {{ product.description }}</li>
  {% endfor %}
</ul>

```

My custom module sends an array of products, which are something like this

```
array(1) { [0]=> array(3) { ["title"]=> string(9) "Product 3" ["image"]=> string(56) "/sites/default/files/2019-11/128px-Small_Storage_Box.png" ["description"]=> string(22) "Description 3" } }

```

And I am sending it from a controller like this:

```
return array(
  '#title' => t('Return products list'),
  '#products' => $products,
  '#theme' => 'return-products',
);

```

In my .module file I've defined hook as:

```
<?php
function return_products_theme($existing, $type, $theme, $path) {
  return array(
    'products' => [
      'variables' => [],
    ]);
}

```

I know data is there in an array, it just doesn't go inside twig template. Even if I type some

Test it won't be shown.

# Answer
Several things are wrong here.

Your `hook_theme` must return:

```
return [
  'return_products' => [
    'variables' => [
      'products' => NULL,
    ]
  ]
];

```

Now you have a template called `return_products` with a variable called `products`.

In your controller you must then use `'#theme' => 'return_products',` instead of `'#theme' => 'return-products',`.

Then create a template in `mymodule/templates/return-products.html.twig`.

Notice how your theme name must be with `_`(underscores) when referred to in PHP, but the file name must be with `-`(dashes).
> 3 votes

---
Tags: 8, theming
---


# Question
Title: How can I change the items order in a pulldown list of filter in views?
Hello Drupal community.

I have a question about Views. I have a “People” view with a role filter and the pulldown list for this filter look like this:

* Administrator
* Editor
* Approver

I would like to know if it is possible to change the order of items in the pulldown list to make it look, for example, like this:

* Administrator
* Approver
* Editor

Thank you.

# Answer
> 1 votes
I guess you could probably change the roles order in People\>Permissions\>Roles (simple drag and drop) and the Views filter will use it by default.

---
Tags: views
---


title: SASS for module CSS?

text:
# Question
Title: SASS for module CSS?
I have worked in Drupal projects where SASS was used to generate CSS files in a theme (with gulp or compass).

I have also worked in Drupal projects where a lot of the CSS (without SASS) was living in custom modules, to style Drupal components (views plugins, ds layouts, field formatters, etc).

I am now wondering what would be the best way to combine both worlds:

* Have SASS sources distributed in distinct (custom module) directories, and some in the theme.
* Allow to include sources from other modules. Of course dependencies must be declared accordingly.
* Allow contrib modules, or "corporate" modules that are meant to be reused, to ship with SASS sources.
* Watch the entire tree with gulp or compass, without watching the toplevel dir.
* Generate the CSS files in a common directory, or in distinct directories, I don't care that much.
* Have some way to control which generated CSS file is included on a page.

The main limitation of SASS seems to be that it is limited to one directory, where you keep all the source files and that you watch with gulp or compass, and one output directory for the finished CSS files(s). At least this seems to be how it is commonly used. This is not ideal if I want to distribute the CSS across module directories.

For now the question is quite open-ended, perhaps someone already did this and can describe a workflow / architecture.

## Platform

The project I am asking this for is currently on D7, but will move to D8 soon. I would be interested in both, but will mark it as "8", and hope I can then apply a similar technique to D7.

## Theme CSS vs module CSS?

Some developers have quite strong opinions about the location of CSS files, accepting only the theme as a valid place for anything front-end related. You are free to share such opinions, but please don't make this the only part of the answer!

## Is this a Drupal question?

Perhaps the individual technical obstacles are not specific to Drupal. But my use case is, and I am hoping that someone else had a similar scenario.

# Answer
By concept a contrib module will hardly ever be able to use SASS, because SASS simply is not part of Drupals distribution. But that doesn't mean your local environment cannot use shared SASS resources for custom themes *and* custom modules.

E.g. in all our projects, the project-specific theme is a sub-theme of a shared, immutable base theme providing defaults and mixins. We are compiling with a bash script using standalone SASS with the `--load-path` argument:

```
sass ./web/themes/custom/PROJECT/scss/THEME.scss ./web/themes/custom/PROJECT/css/THEME.css --load-path ./web/themes/custom/SHARED_BASETHEME/scss

```

in `./web/themes/custom/PROJECT/scss/THEME.scss`

```
@import "default_settings"; /* lives in SHARED_BASETHEME, bunch of $variables with !default */
@import "settings"; /* lives in PROJECT, partially overrides default_settings */

```

I'm quite certain there is something similar for the Node-Version of SASS (or in Gulp). With a black belt in in Bash-Fu (or in your case: Gulp-Fu) this can be extented to any custom module and any custom theme and vice versa.

Example with multiple themes:
We had one project using Domain access module and one sub-theme per sub-domain and we handled bulk theme compiling with a bash script:

```
for D in ./web/themes/custom/*/;
do
  if [ -d "${D}" ] && [ "${D}" != "./web/themes/custom/SHARED_BASETHEME/" ] && [ "${D}" != "./web/themes/custom/EXCLUDE_ME_2/" ]; then
    echo "Creating sub-theme ${D}"
    sass ${D}scss/THEME.scss ${D}css/THEME.css --style expanded --load-path ./web/themes/custom/SHARED_BASETHEME/scss
  fi
done

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Redirect from route when the controller has been changed
I'm trying to redirect to an external URL in a custom controller whenever I land on the 404 page.

Right now I alter the controller destination in a route subscriber like this:

```
public function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('system.404')) {
    $route->setDefaults([
      '_controller' => '\Drupal\test\Controller\TestController::test',
    ]);
  }
}

```

This is my controller:

```
public function test() {
  return new TrustedRedirectResponse('https://google.com', 307);
}

```

Right now my controller redirects to the frontpage when I try to redirect.

I could fix this problem by calling `$response->send()` but that is not a good idea since I'm bypassing the http-kernel call stack that way.

How can I redirect from the 404 page?

# Answer
With the help from @4k4 I found a solution.

I created an event subscriber that extends the `HttpExceptionSubscriberBase` class. There I created the redirect like this:

```
public function on404(GetResponseForExceptionEvent $event) {
  $response = new TrustedRedirectResponse('https://google.com', 307);
  $event->setResponse($response);
}

```
> 1 votes

---
Tags: 8, redirection
---


title: Setting up multilingual nodes

text:
# Question
Title: Setting up multilingual nodes
I am trying to set up a D8 (8.7.9 to be precise) multilingual site and hitting some weird bug.

I have a node type `basic page` consisting of the title field and a body text field.

Initially I create the page in German (title: "test page de" / content "test content de"), then click Translate to add an english version, save it. So far, so good - the german page pops up at /de/node/12, the english one at /en/node/12, the language switcher works fine.

Then, I edit the German page to say "test page de-1"/"test content de-1", and submit. The German page shows the proper content, as does the English one, but now, when I edit the English page, I suddenly get the title set to "test page de-1" and the body to "test content de-1". What is going on here?

# Answer
> 0 votes
Found the issue: I had the language detection under `/admin/config/regional/language/detection` messed up - content language detection was identical to UI language detection (which was User account first, URL second). Used URL only for content language detection and now it works.

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


# Question
Title: How to theme the taxonomy add/edit term form?
I would like to change the design of the taxonomy add/edit term form, how do you create a template for the taxonomy "Add Term" / "Edit Term" just like creating a node form template? Not creating a custom module because I already have some custom fields for my term.

As of now this is the code on my template.tpl

```
'admin/structure/taxonomy/type_of_category/add' => array(
        'arguments' => array(
            'form' => NULL,
            ),
       'template' => 'templates/type-of-build-your-event-category-taxonomy-form-term', // set the path here if not in root theme directory
       'render element' => 'form',
    )

```

These are the filenames I've tried for my template file:

* taxonomy-term--type\_of\_category-taxonomy-form-term.tpl.php
* type\_of\_category-taxonomy-form-term.tpl.php
* taxonomy-form-term.tpl.php
* type\_of\_category.tpl.php

None of it works.

Does anyone have any suggestion on how to make this work?

Thank you in advance!

# Answer
Use `hook_theme()` inside your theme's template.php file to set a custom template file (tpl.php) for the taxonomy `add` and `edit` forms. However, **your theme needs to be set as the Administration Theme**, even if `Use the administration theme when editing or creating content` is not checked.

The `taxonomy` module implements only one form template file for the taxonomy `add` and `edit` forms for all vocabularies. In other words, the taxonomy module does not provide, on its own, a way to have a different taxonomy form template file for a specific vocabulary. However, it is possible for you to add this capability by implementing `hook_form_alter()` within your theme's `template.php` file (explained below).

**PSA: clear your site's cache after making changes to your templatate.php file.**

This is what would be in the `template.php` file for the `theme_name` administration theme if you wanted to theme the taxonomy add and edit forms for all vocabularies:

```
/**
 * Implements hook_theme().
 */
function theme_name_theme($existing, $type, $theme, $path) {
  $items['taxonomy_form_term'] = array(
    'render element' => 'form',
    'template' => 'taxonomy-form-term',
    'path' => drupal_get_path('theme', 'theme_name') . '/templates',
  );
  return $items;
}

```
* `$items['taxonomy_form_term'] = array(...`: The key `taxonomy_form_term` indicates the values inside the array are to theme the taxonomy `add` and `edit` forms. This key is defined by the taxonomy module.
* `'render element' => 'form'`: `$form` will be the variable that holds the renerable form array. Note that the words "render path" are separated by a space, and not an underscore.
* `'template' => 'taxonomy-form-term'`: The name of the template file without the extension. When the extension is added, the name of the file will be `taxonomy-form-term.tpl.php`.
* `'path' => drupal_get_path('theme', 'theme_name') . '/templates'`: The template file will be in the `templates` sub-directories within the `theme_name` theme's path. You are not required to use this exact directory, and can omit `path` from the array if you place the template file directly inside the theme's default path.

When you implement a theme hook, you will also have a preprocess function that you can implement in your theme's template.php file for that theme hook:

```
function theme_name_preprocess_taxonomy_form_term(&$variables){}

```

Create a file named `taxonomy-form-term.tpl.php` in the templates sub-directory of your theme, e.g. `sites/all/themes/theme_name/templates/taxonomy-form-term.tpl.php`. Use the `$form` variable for rendering the form.

```
// Move the Relations fieldset to the top of the form.
print render($form['relations']);
print drupal_render_children($form);

```

You can use `hook_form_alter()` to define keys for `hook_theme()` to theme the forms for specific vocabularies, specific terms, and/or for just the `add` (or `edit`) form. You add the keys to the `$form['#theme']` array. You can name them whatever you want, but the order that they appear in the array matters. Keys at the beginning of the array take precedence over others, so add them starting with the most specific keys first. `taxonomy_form_term`,and possibly other keys, will already be in `$form['#theme']`, so you will need to prepend your keys to the beginning of the array.

```
/**
 * Implements hook_form_alter().
 */
function theme_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $term = $form['#term'];
    $vocabulary = $term['vocabulary_machine_name'];
    $tid = $term['tid'];

    $theme_keys = array();
    if (!$tid) {
      // Key to theme the 'add' form for this vocabulary.
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_add';
      // Key to theme the add form for any vocabulary.
      $theme_keys[] = 'taxonomy_form_term_add';
    }
    else {
      // Key to theme the 'edit' form for this term using its term id.
      $theme_keys[] = 'taxonomy_form_term_edit_' . $tid;
      // Key to theme the 'edit' form for this term for this vocabulary, using
      // the term's name (after replacing non-alphanumeric characters with "_").
      $term_name = preg_replace('/[^a-z0-9]+/', '_', strtolower($term['name']));
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_edit_' . $term_name;
      // Key to theme the 'edit' form for this vocabulary.
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_edit';
    }
    // Key to theme the add/edit form for this vocabulary.
    $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term';

    // Add the theme keys to the beginning of the #theme array so they have
    // precedence over any preexisting ones.
    $form['#theme'] = array_merge($theme_keys, $form['#theme']);
  }
}

```

Implement the new theme hooks in your `hook_theme()`. For example, if you wanted to theme the `edit` form for the `my_vocabulary` vocabulary:

```
$items['taxonomy_form_my_vocabulary_term_edit'] = array(
  'render element' => 'form',
  'template' => 'taxonomy-form-my-vocabulary-term-edit',
  'path' => drupal_get_path('theme', 'theme_name') . '/templates',
);

```

You will also have a new preprocess function that you can implement in your theme's template.php file:

```
function theme_name_preprocess_taxonomy_form_my_vocabulary_term_edit(&$variables){}

```

Create the `taxonomy-form-my-vocabulary-term-edit.tpl.php` file in the templates sub-directory of your theme, and use the $form variable to render the form.
> 1 votes

# Answer
You can try this from drupal document https://www.drupal.org/docs/7/theming/advanced/theming-forms-in-your-theme
> 0 votes

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


# Question
Title: Views rewrite results texfield to uppercase
I need to display text field to Uppercase, using Rewrite Results in Views. For example from the text value "paper Title" to "PAPER TITLE".

How to transform the text to uppercase in Rewrite Results?

# Answer
One solution is to rewrite with inline CSS styling. For example:

```
<span style="text-transform: uppercase;">[my_field]</span>

```

Depending on your design needs you might want use CSS classes instead.
> 2 votes

# Answer
I don't see this question specifically tagged as D7, so if someone is using D8 and sees this question, Twig would be an easy way to accomplish this:

```
{{ my_field|upper }}

```
> 2 votes

# Answer
Thx @Waluyo

Needed to deal with URLs in taxonomy term names for a CSV data export, so this worked great for the output to create lowercase and insert the dashes:

```
<?php echo strtolower(str_replace(' ', '-', $row->name)); ?>

```

(Value code for my situation was $row-\>name)
> 1 votes

# Answer
A possible solution is to use the views feature "rewrite result", combined with Views PHP module.

**Note**: this module only has an alfa version as of today, but it's used in over 71K sites anyway.
> 0 votes

---
Tags: views
---


title: How to get a node by its url alias?

text:
# Question
Title: How to get a node by its url alias?
I know I can load a node by its title with the `node_load()` function. Is it possible to load a node by its URL alias?

# Answer
You want to investigate menu\_get\_object and drupal\_lookup\_path.

Something like this would do what you want:

```
$alias = "some/path/to/a/page";
$path = drupal_lookup_path("source", $alias);
$node = menu_get_object("node", 1, $path);

```
> 61 votes

# Answer
For somebody looking to find how to do this in Drupal 8 here is the corresponding question and answer

How can I get the node ID from a path alias?

```
use \Drupal\Core\Url;

$alias = \Drupal::service('path.alias_manager')->getPathByAlias('/etapes-de-la-vie');
$params = Url::fromUri("internal:" . $alias)->getRouteParameters();
$entity_type = key($params);
$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);

```

For **Drupal 9** use `\Drupal::service('path_alias.manager')` instead of `\Drupal::service('path.alias_manager')`
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to correctly access entity elements in a twig template
I have an array of entities that i would like to render in a list.

```
$ids = \Drupal::entityQuery('chemical')
  ->condition('tid', $tid)
  ->execute();
$controller = \Drupal::entityManager()->getStorage('chemical');
$entities = $controller->loadMultiple($ids);

$chemicals = [];
foreach ($entities as $entity){
  $chemicals[] = ['id' => $entity->id(), 'label' => $entity->label()];
}

$output[] = [
  '#theme' => 'chemical_taxonomy',
  '#chemicals' => $chemicals,
];
return $output;

```

The twig template then creates the unordered list of URLs using the array of `{{ chemicals.label }}` and `{{ chemicals.id }}`. However, I should be able to just pass `$entities` to the template instead of extracting the id and label and building a new array, shouldn't I?

If I replace `'#chemicals' => $chemicals` with `'#chemicals' => $entities` I receive an error:

```
Uncaught PHP Exception Exception: "Object of type Drupal\\Core\\Field\\FieldItemList cannot be printed." at /var/www/Drupal_Sites/console/core/lib/Drupal/Core/Template/TwigExtension.php line 443,

```

# Answer
As the exception explains, you tried to print an object that is not renderable and cannot be converted to a string. In this case it was `Drupal\Core\Field\FieldItemList` which is the object returned by drupal entities when you ask for a field (`{{ entity.id }}` / `{{ entity.label }}`).

To get the actual value you need to call to methods of your entity (the actual value of the fields is protected from outside access).

The long way:

```
{{ entity.get('id').get(0).get('value').getValue() }}

```

The above is the actual path you need to take to get from the entity object to the value of the id field.

However drupal supplies shortcuts through what is known as magic properties. The short way

```
{{ entity.id.value }}

```
> 19 votes

# Answer
To get the full objects in your twig file, you could have done this:

```
$ids = \Drupal::entityQuery('chemical')
  ->condition('tid', $tid)
  ->execute();
$controller = \Drupal::entityManager()->getStorage('chemical');
$entities = $controller->loadMultiple($ids);

$output[] = [
  '#theme' => 'chemical_taxonomy',
  '#chemicals' => $entities,
];
return $output;

```

Then, in your twig file just do:

```
<ul>
{% for chemical in chemicals %}
  <li data-id="{{ chemical.id() }}">{{ chemical.label() }}</li>
{% endfor %}
</ul>

```
> 2 votes

# Answer
You have to implement `function template_preprocess_chemical_taxonomy(&$variables)` where you prepare you variables for your template.

As an example have a look in core regarding function `template_preprocess_item_list(&$variables)` for `item-list.html.twig`.
> 0 votes

# Answer
You have to render the entity before passing it to twig.

```
$render_controller = \Drupal::entityManager()->getViewBuilder('chemical');

foreach ($entities as $entity){
  $chemicals[] = $render_controller->view($entity);
}

```

Of course, this means creating a custom viewbuilder for your entity, if you haven't already, which may be more work, but would a nicer solution than creating a custom array each time you want to render your entity.

You could copy another view builder, such as core/modules/node/src/NodeViewBuilder.php

move it into your project and alter it to work with your custom entity.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Filter on boolean with NULL (unset) value
Client wants to hide some published content from specific Views displays.

Unpublishing the content is not an option: it needs to remain accessible.

I added a boolean `exclude_from_view` field to several content types.

I planned to add a boolean filter to exclude content from the necessary displays if this field's value was `TRUE`, but I was surprised to find that when I did so, Views returned no results at all. Setting the boolean filter to `NOT FALSE` had the same result.

This is happening because the field has been added to the existing content without a default value, so the field returns `NULL`, which is neither `TRUE` nor `FALSE`. (In PHP, `NULL` is a "falsy" value, but apparently not to Views.)

A little research reveals that a lot of other people have complained about this problem.

Some of them think that boolean fields not set on entities should be considered `FALSE`, not `NULL`.

Others wish that `NULL` fields could be treated as `TRUE`.

Still others think that Views UI should offer filtering options for "Treat `NULL` as `FALSE`" or "Treat `NULL` as `TRUE`." (This is a cool idea but it requires patching core, which I'm not necessarily opposed to if it is the best way forward.)

What should I do?

**UPDATE 2019-11-13:**

Kudos to @no-sssweat for coming up with a viable workaround, which I upvoted below.

I'm still hoping for a better answer because I'm not satisfied with the user experience of the "checkboxes/radio buttons" field widget.

If I just use one value, it shows up as two radio buttons, for **N/A** and **Yes**. Adding a **No** option doesn't make it much better:

I think the client would really prefer a boolean checkbox, so I'm holding out for an answer that will give me that.

# Answer
> 1 votes
Just for posterity, here's the approach I ended up using:

The Field Defaults contrib module allowed me to set all `null` values for the new field in pre-existing content, so I was able to use the boolean checkbox I wanted.

There's no need to patch core to deal with this, because it won't happen again with newly-created content. As soon as the node is saved, the field has a sensible default value.

# Answer
> 0 votes
Interesting problem, I was able to replicate the issue.

> Some of them think that Boolean fields not set on entities should be considered FALSE, not NULL.
>
> Others wish that NULL fields could be treated as TRUE.

Seems like patching core catered towards your needs would make some people unhappy. Unless you add, a new option, an *Is Empty (NULL)* to it.

---

A work around solution is to use List (text) OR List (integer) I set mine to `1 | yea`

You could make it a select box by switching the field widget from list to checkboxes

Then in Views filter you just set to *is none of* and it will return all nodes that are not set to "yea".

---

OR better yet you can select *Is Empty (Null)*

---
Tags: views
---


# Question
Title: How to get the alt tag from an image field in twig?
I have a page of field images which are coming out quite weirdly when I kint their values. I can't seem to get the image url and the alt tag.

The code in the twig file looks like this:

`field--field-staff-gallery.html.twig`

```
{% for item in items %}
    {{ kint(item) }}
{% endfor %}

```

It's output looks like this:

Now I can easily get to the url by doing:

```
{% for item in items %}
    {{ file_url(item.content['#markup']) }}
{% endfor %}

```

So how can I get the alt tag?

# Answer
You can get the alt of image with:

```
item.content['#item'].value.alt

```
> 3 votes

---
Tags: 8, theming
---


# Question
Title: How do you deploy a change to a main menu?
We have a small D7 site. We want to deactivate a main menu item. On dev server I was able to deactivate it in /admin/structure/menu/manage/main-menu

I believe The menu is stored in the DB, right. Also in a config file? So you only need to deploy those two things and it is done.

Is that correct? If not, what are the steps to deploy a main menu change?

# Answer
> 2 votes
Menu items are saved in the DB, therefore you must update them using update hooks.

Something like this should work:

```
function MODULE_NAME_update_N() {
  $menu_link_id = 1;
  $menu_link = menu_link_load($menu_link_id);
  $menu_link['hidden'] = 0;
  menu_link_save($menu_link);
}

```

# Answer
> 0 votes
Menu items are stored in the database.

You are still able to export the menu using a contrib module.

# For Drupal 7

You can achieve that by using Menu Export/Import contrib module.

# For Drupal 8 & 9

You can achieve that by using Menu Import and Export. The module will give you the ability to exports the menu entity as config YAML and will be imported on subsequent instances.

# Answer
> 0 votes
You can use Features Module.

1. Create another feature for menus.
2. Push your new module to your server.
3. Enabled it in the new server.

`drush en your_feature`
4. Revert your feature

`drush fr your_feature`

---
Tags: 7, navigation, deployment
---


# Question
Title: Where is the node created timestamp stored in the database?
I need to create an SQL query that finds all nodes of a certain type created X days ago, so I can get their IDs. Due to the massive number of nodes in the database, I would prefer to use a direct SQL query, rather than entityQuery. I was warned entityQuery can be slow if working with large volumes of data.

Anyway, I need to find where is the node created timestamp stored in the database. In Drupal 7, it is stored directly in the node table, but not in Drupal 8.

# Answer
> 7 votes
The created date is stored in the `node_field_data` table as a UNIX timestamp in a cloumn called `created`.

Here's the code you would use to fetch the nodes that has been created X days ago, using a direct select query.

```
$day = 86400; // One day in seconds.
$days = 3; // The amount of days ago to fetch from.

$nids = \Drupal::database()->select('node_field_data', 'n')
  ->addField('n', 'nid')
  ->condition('n.created', \Drupal::time()->getCurrentTime() - $days * $day, '>')
  ->execute()
  ->fetchField();

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

```

Make sure to inject the `database` and the `entity_type.manager` services (if possible) when implementing the code yourself.

# Answer
> 3 votes
If you go into your Drupal database you should find a table called 'node\_field\_data'. In this table there is a column labeled 'created'. That will be your Unix timestamp for when the node was created.

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


# Question
Title: Saving a webform programmatically in a custom webform handler throws "Entity validation was skipped."
I am trying to save a webform submission inside the postSave in a `CustomWebformHandler` class.

```
class CustomWebformHandler extends WebformHandlerBase {
[..]
     public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
        $data = $webform_submission->getData();
        $data['ssa_attachment'] = $doc_id; //doc_id is retrieved with a query
        $webform_submission->setData($data);
        $webform_submission->set('in_draft', TRUE);
        $webform_submission->save();
     }
}

```

I get the following exception.

> Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Entity validation was skipped."

I tried to validate before saving and I get this exception.

> Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "SQLSTATE\[HY000\]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: SELECT w.next\_serial AS next\_serial\nFROM\n{webform} w\nWHERE webform\_id = :db\_condition\_placeholder\_0 FOR UPDATE;

How can I trigger the validation before saving?

# Answer
The WebformSubmission::resave() method prevents the `::save` and `::postSave` recursion issue from occuring.
> 4 votes

---
Tags: 8, webforms
---


# Question
Title: MiniOrange SAML SSO Drupal Module – Multilanguage Support
This is my first post at Drupal StackExchange. Please feel free to redirect it to the proper forum if this is the incorrect one.

How do I configure Apache Server so that MiniOrange SAML SSO Drupal module does not conflict with my Drupal multilanguage settings?

**Here is my problem:**

I determine the language from the URL as a Path prefix:

URLs like https://example.com/en/contact set language to English (en) - Default

URLs like https://example.com/fr/contact set language to French (fr)

My default language is English.

If I configure my Drupal multilanguage settings to other detection methods such as session, user, browser then the SAML SSO Drupal module works fine but some (not all) of my Clean URLs no longer work with my current modified Drupal and Apache settings. I’d like to retain my multilanguage settings.

All this happens because of the SAML Drupal module **ACS, Recipient and Destination** URLs are configured in such a way that the language negotiation happens before reaching the ACS, Recipient and Destination URLs.

ACS URL https://example.com/?q=samlassertion

Recipient URL https://example.com/?q=samlassertion

Destination URL https://example.com/?q=samlassertion

Drupal then prepends the default language code, English (en) in my case, to the **ACS, Recipient and Destination** URLs as follows breaking the module.

ACS URL https://example.com/en/?q=samlassertion

Recipient URL https://example.com/en/?q=samlassertion

Destination URL https://example.com/en/?q=samlassertion

I know Apache Server 2.4 very well but by no means I’m an expert. I strongly believe this issue can be fixed with a simple and magic Apache configuration set of rules.

What I've done to fix all these issues is by restructuring my existing Drupal Clean URLs to work with the SAML module by using other detection methods such as session, user, browser and by creating rewrite rules to redirect existing URLs to the new structure. I wish I could say that I have completely and 100 % fixed all the problems. But that’s not the case. As I mentioned, some of my URLs break.

Any help is greatly appreciated.

Thanks,

# Answer
> 0 votes
I figured it out.

The solution to this problem is so simple that i feel a bit embarrassed posting the solution. However, here it goes for those who may stumble upon it. This only needs to happen during the initial configuration and revert back once this step is completed (Based solely on my experience).

1. Drupal cache for anonymous users needs to be disabled during initial IdP and SP metadata and certificate negotiation
2. Drupal language negotiation needs to be turned off during initial IdP and SP metadata and certificate negotiation

Victor "Patience and perseverance have a magical effect before which difficulties disappear and obstacles vanish"

---
Tags: 7, i18n-l10n, path-aliases
---


# Question
Title: How can get the current region inside the 'hook_preprocess_block'?
How can I get the current region name inside the `hook_preprocess_block()`?
I tried the following code, but it seems something is wrong.

```
function ThemeName_preprocess_block(&$variables) {
  if ($variables['elements']['#region'] == "nav") {
    $variables['attributes']['class'][] = 'SomeStyle';
  }
}

```

# Answer
> 1 votes
As described in the documentation for `template_preprocess_block()`, `$variables['elements']['#block']` is available, and it contains the Block object. With that, you can get the region to which the block is assigned with `Block::getRegion()`.

```
function ThemeName_preprocess_block(&$variables) {
  if (isset($variables['elements']['#block']) && $variables['elements']['#block']->getRegion() == 'nav') {
    $variables['attributes']['class'][] = 'SomeStyle';
  }
}

```

That is slightly different from Drupal 7, where `hook_preprocess_block()` would get the region assigned to the block from `$variables['block']->region`, or from `$variables['elements']['#block']->region`. See `template_preprocess_block()` (Drupal 7).

```
  $block_counter = &drupal_static(__FUNCTION__, array());
  $variables['block'] = $variables['elements']['#block'];
  // All blocks get an independent counter for each region.
  if (!isset($block_counter[$variables['block']->region])) {
    $block_counter[$variables['block']->region] = 1;
  }

```

# Answer
> 1 votes
It seems that something has changed and `variables['elements']['#block']` is not available anymore.

Here is what worked

```
function ThemeName_preprocess_block(&$variables) {
  $block = entity_load('block', $variables['elements']['#id']);
  $region = $block->getRegion();
  if ($region == 'nav') {
    $variables['attributes']['class'][] = 'SomeStyle';
  }
}

```

---
Tags: theming, blocks
---


# Question
Title: How to fix 'Call to undefined function node_load() in menu.inc' fatal PHP error?
Copied my live site to my local computer. From Windows server 2008 to Windows 7. Took a backup of the database via `mysqldump`. Restored the database on the dev-db-server. Now I'm trying to get my local copy up-n-running. Browsing index.php gives me

```
Fatal error: Call to undefined function node_load() in C:\inetpub\wwwroot\my_drupal\includes\menu.inc on line 577

```

My hunch is that I have missed some web server settings allowing parent path or similar?

I have installed PHP and 5.3.13 and URL Rewriter via Web Platform Installer. According to `CHANGELOG.TXT` I'm running Drupal 7.0

However `phpinfo();` works fine.

Edit / Update: I tried to narrow down the error. Following code fails on line 3. If I change the path on line 2 to something wrong the require\_once will fail. Apparently IIS is able to find `bootstrap.inc`, but `bootstrap.inc` cannot find `user_access()`

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

# Answer
Problem was the file encoding from mysqldump. My solution: Downloaded the sql file to my local computer. Saved it in UTF-8 with Sublime Text 2. Run the script. And things worked fine with the original drupal files copied from web server. Did not need to run registry\_rebuild etc.
> 3 votes

# Answer
Here are few tips:

* Make sure your Drupal core has all the files in the right place (especially the Node module)
* Upgrade your Drupal core to the latest version (`drush fr && drush up drupal`)
* Clear all your caches (`drush -y cc all`), including your memcached (`killall memcached`)
* Rebuild your registry by using Registry Rebuild
* If you're using modules which are implementing `drupal_bootstrap()` (such as Secure Site), disable them
* Try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem
* Test it in a different environment/machine
* Check your database collation (it should be case insensitive, e.g.: `general_ci`).
* Eventually restore your database from the point where it was working before.
> 1 votes

# Answer
I have also encountered the same error. Even if I export using UTF-8 charset the problem was there.

The problem was with HeidiSQL (version 8.3) for me. When I imported it using mysql command everything started working fine.
> 0 votes

# Answer
Had same issue, due to a silly typo mistake in settings.php

As you see in the wrong example below

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

```

... once moved the comma in the right place,

```
'username' => 'dbusername',

```

my Drupal 7 came back to life
> 0 votes

# Answer
I had this error appear rather suddenly on one of our Drupal 7 sites. Went through a lengthy verification process of other things listed, but in the end, all I did was flush my cache manually as described here.

MySQL:

```
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_token;
TRUNCATE TABLE cache_update;

```

SQL Server:

```
DELETE FROM cache;
DELETE FROM cache_block;
DELETE FROM cache_bootstrap;
DELETE FROM cache_field;
DELETE FROM cache_filter;
DELETE FROM cache_image;
DELETE FROM cache_menu;
DELETE FROM cache_page;
DELETE FROM cache_path;
DELETE FROM cache_token;
DELETE FROM cache_update;

```
> 0 votes

---
Tags: 7
---


# Question
Title: How do I include a twig file in a custom block type module?
I've created a custom module that creates a jumbotron custom block type. The module has an empty .module file and a dir config/install with many .yml files. This works great when I install and create blocks. I can even place my block--bundle--jumbotron.html.twig in the templates folder of the theme and styling works great! I would like this twig file included in the module and many tutorials explain how to do this if you have a build function in your module, I do not. The module is just creating a block type for me.

# Answer
Create a theme hook with the template name by replacing dashes with underscores:

*mymodule.module:*

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__bundle__jumbotron' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}

```
> 1 votes

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


# Question
Title: How can I copy theme configuration when copying a site?
I have written a script that copies a drupal 8 site. The steps go something like this:

1. dump old site database into file
2. replace old site name with new site name in said file
3. create a new database using that file
4. Copy all files from the old directory into the new directory
5. Modify sites.php and settings.php to contain the new site's configuration.

This works (I've debugged the script quite a bit) except for theme settings are not transferred over. Are the theme settings stored in the database? If so, why are my settings not transferred over? If not, where are they stored?

Assuming access only from a command line, how can my script copy theme settings from one Drupal 8 installation to another using the same theme?

# Answer
> 0 votes
Using `drush cex` and `drush cim` to try and transfer settings failed because there were errors in the database. So, if the database transfer did not work, then importing configuration settings would also fail.

It turns out the problem was step 2 (replacing the URL in the database dump). Apparently

```
sed -i -e "s|$oldURL|$newURL|g" $databaseDump

```

was causing problems in the database. When it operated on binary lines, stuff broke (I have no idea why). I tried the same thing with `perl` and `bbe` but the result was the same. What eventually worked was changing the sed command to:

```
sed -i -e "/binary/!s|$oldURL|$newURL|g" $databaseDump

```

This is not without its own problems; any instance of the URL on a binary line will not be replaced. An example I ran into was accessing images from the 'asset\_injector' module since the URL for the images is not replaced. But it works!

# Answer
> 1 votes
Theme settings are stored in the database. However, Drupal 8 has configuration management. You can export the configuration to yml files. Theme configuration is included.

1. You can download the yml files at /admin/config/development/configuration/full/export
2. Or you can export it to the configuration folder by

`$ drush config-export sync`

---
Tags: 8
---


# Question
Title: drush migrate-upgrade "[debug] key_value table not found. Database may be empty."
I am trying to migrate a D7 site to D8 following the steps found here .

Once I can manage it and make sure I have all the PHP components, Drupal modules and etc. I have 4 sites to update, and one that I suspect is going to be very difficult.

I installed and used Composer to make a Drupal 8 site off my /home directory with the intent to move the files over the existing website. Plus it seems the migrate-upgrade needs to reference the D7 site via http.

When I run the following command to migrate the old (D7) site to this new D8 site it fails.

```
drush migrate-upgrade --legacy-db-url=mysql://user:password@server/db
--legacy-root=http://example.com --configure only

```

with the following parameters for my specific environment

* user = user the site uses to connect to the database
* password
* server = localhost
* db = database name
* http://example.com = URL for the website

When it fails, it cites **\[debug\] key\_value table not found. Database may be empty. \[0.1 sec, 9.59 MB\]** and when I check the MySQL database I find there is no table name ***key\_value***.

I could create the table, if I know the requirements for the table (field names, field type, sizes, PK/FK, etc.). Or is there some other means to create this table.

Previously I did everything manually.
I thought since the update steps found in this Guide had the overall process involve making a D8 site and migrating the data over that I should use Composer and/or Drush.
This is my first time getting Composer and Drush working for me.

Any help would be greatly appreciated.

Thank you.

---

I get the following output when I run the whole **drush migrate-upgrade** command:

> Drush Launcher Version: 0.6.0 ROOT: /home/akwashnak/ctdollarsandsesne DRUSH VERSION: 9 DRUPAL ROOT: /home/akwashnak/ctdollarsandsesne COMPOSER ROOT: /home/akwashnak/ctdollarsandsesne VENDOR ROOT: /home/akwashnak/ctdollarsandsesne/vendor \[preflight\] Config paths: /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/drush.yml \[preflight\] Alias paths: /home/akwashnak/ctdollarsandsesne/drush/sites,/home/akwashnak/drush/sites \[preflight\] Commandfile search paths: /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/src \[debug\] Bootstrap further to find migrate-upgrade \[0.08 sec, 8.02 MB\] \[debug\] Trying to bootstrap as far as we can \[0.08 sec, 8.02 MB\] \[debug\] Drush bootstrap phase: bootstrapDrupalRoot() \[0.08 sec, 8.02 MB\] \[debug\] Change working directory to /home/akwashnak/ctdollarsandsesne \[0.08 sec, 8.02 MB\] \[debug\] Initialized Drupal 8.7.9 root directory at /home/akwashnak/ctdollarsandsesne \[0.08 sec, 8.15 MB\] \[debug\] Drush bootstrap phase: bootstrapDrupalSite() \[0.09 sec, 8.5 MB\] \[debug\] Initialized Drupal site default at sites/default \[0.09 sec, 8.67 MB\] \[debug\] Drush bootstrap phase: bootstrapDrupalConfiguration() \[0.09 sec, 8.67 MB\] \[debug\] Add service modifier \[0.1 sec, 9.17 MB\] **\[debug\] key\_value table not found. Database may be empty. \[0.1 sec, 9.59 MB\]** \[debug\] Bootstrap phase bootstrapDrupalDatabase() failed to validate; continuing at bootstrapDrupalConfiguration() \[0.1 sec, 9.59 MB\] \[debug\] Done with bootstrap max in Application::find(): trying to find migrate-upgrade again. \[0.1 sec, 9.59 MB\]
>
> In Application.php line 239:
>
> \[Symfony\Component\Console\Exception\CommandNotFoundException\] Command migrate-upgrade was not found. Drush was unable to query the database. As a result, many commands are unavailable. Re-run your command with --de bug to see relevant log messages.
>
> Exception trace: at /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/src/Application.php:239 Drush\Application-\>bootstrapAndFind() at /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/src/Application.php:192 Drush\Application-\>find() at /home/akwashnak/ctdollarsandsesne/vendor/symfony/console/Application.php:236 Symfony\Component\Console\Application-\>doRun() at /home/akwashnak/ctdollarsandsesne/vendor/symfony/console/Application.php:148 Symfony\Component\Console\Application-\>run() at /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/src/Runtime/Runtime.php:118 Drush\Runtime\Runtime-\>doRun() at /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/src/Runtime/Runtime.php:49 Drush\Runtime\Runtime-\>run() at /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/drush.php:72 require() at /home/akwashnak/ctdollarsandsesne/vendor/drush/drush/includes/preflight.inc:18 drush\_main() at phar:///usr/local/bin/drush/bin/drush.php:141 require() at /usr/local/bin/drush:10

# Answer
"Drush was unable to query the database" tells you that your issue isn't a missing table, but a configuration issue.

You do need to start with an empty but working D8 site before you try running the migration. I'm thinking you didn't initialize your site after downloading the code with composer?

To be clearer: composer is a tool for managing code, not for managing the site as a whole. After using composer to download the code, you still need to create your database and use drush or the web interface to actually "set up" your site. Only at that point can drush migrate can start doing its thing.
> 2 votes

---
Tags: 8, drush, migrations, composer
---


# Question
Title: Display alternate content after webform submission
Is there a way to display an alternate content once user submits a webform?

For example user submits "Email Sign Up" form on the homepage, and the next time they visit the page containing that form they would see a different message.

Thanks!

# Answer
You'll notice that for anonymous visitors, webform does store a cookie so that it knows if you've submitted a particular form (assuming a default webform configuration). So in theory, you could hook into that with some custom code to display and/or hide content.
> 1 votes

---
Tags: webforms
---


title: views_get_current_view performance

text:
# Question
Title: views_get_current_view performance
Does this function `views_get_current_view` inside views header or footer (to count rows number for example) means running the same view twice?
Or is it somewhat simplified version of running full view? Thank you.

# Answer
> 1 votes
That function is just a wrapper for this function: https://api.drupal.org/api/views/views.module/function/views\_set\_current\_view/7.x-3.x which will just return a reference to a static code cache.

Conclusion: no view gets run, it's just grabbing a copy of what's already been created.

In general, views is very efficient in such cases.

But I'd tend to agree with @berramou that you might have a better way of accomplishing what you really, really want.

---
Tags: 7, views
---


# Question
Title: Fill the "Unpublish on" date field of the Scheduler module depending on list field
I have a content type, where I want to give the user only three possibilities to unpublish content: in 1, 3 or 6 months. For the selection of the three options I use a list field. How can I transfer the selected value to the unpublish field?

# Answer
> 0 votes
You'd do better to have a custom module that does a form alter on the unpublish date field itself - converting it from a date/text to a date/select.

---
Tags: 8, nodes
---


# Question
Title: Why would a view be displayed differently in different software?
Using Drupal 7 and the Views PDF module, I have created a PDF output that looks perfect when opened in a browser, but is inconsistent everywhere else: On Chrome, Firefox, and Edge it is displayed exactly as designed; on
Acrobat Reader, it shows only a table background color, the rest is blank, and there is no text; on iPad and Outlook, it displays a blank white screen.

What would cause the PDF to display perfectly in a browser and horribly in everything else?

# Answer
Ironically, the PDF document format was designed to display the same everywhere ... but that's an overly ambitious goal.

First note that "in the browser" isn't especially meaningful - different browsers, with different configurations, will use different engines to display the pdf.

Your different experiences are due to those different engine(s) in your browsers vs. the acrobat reader engine, which is perhaps also used for your ipad and outlook.

My best guess is that your browsers have access to some non-standard fonts that you're using in the output, but the other engines don't. Getting the views pdf to embed those fonts, or using standard fonts instead, will probably fix it.
> 1 votes

---
Tags: views
---


# Question
Title: After changing a webform multi-select field to single-select, submissions made pre-change show only the first selection
I've created a webform in Drupal 7 with a component drop-down list. I selected 'multiple' for multiple selections. Now, I need to unselect 'multiple' giving users just one choice of the drop-down list.

Now, when viewing the submission data, the past data w/ multiple choices only show the topmost choice. How can I have the past data show the multiple choices despite I'm allowing only one choice in the component?

# Answer
> 1 votes
You can keep the field set to single choice, and use `hook_webform_submission_render_alter()` to display the values as if it was still a multi-select field.

You can use the hook in a module or the `template.php` of a theme. If you are thinking about implementing it in a theme, keep in mind that the `Webform Results` view is displayed through the Administration theme. So, the hook must be implemented in the default administration theme for it to work in that view. By implementing it in a module, you shouldn't have to worry about which theme the submission results are being shown.

You will need the `nid` for the webform, and the `form Key` for the select field. The nid is in the url of the webform's edit page. The `form key` can be seen in the webform's `Form components`page.

The following code is implemented in the "my\_module" module, for a webform with a `nid` of "100", and a field with the `form key` "my\_select\_field".

```
/**
 * Implements hook_webform_submission_render_alter().
 */
function my_module_webform_submission_render_alter(&$renderable) {
  if ($renderable['#node']->nid == '100' && isset($renderable['my_select_field'])) {
    $renderable['my_select_field']['#multiple'] = 1;
  }
}

```

The `isset($renderable['my_select_field'])` in the if statement may seem redundant, but it's there to prevent an exception if someone changes the `form key` for the field.

# Answer
> 0 votes
You could instead create a new component for the single choice option, and disable the multi-option one.

---
Tags: 7, webforms
---


# Question
Title: How can I convert the code that used drupal_get_http_header() to check if a 403 or 404 error is returned?
I have a module that in `hook_preprocess()` checks with `drupal_get_http_header()` whether Drupal is returning a 403 or 404 error, but in Drupal 8 that function is deprecated, since header handling is being shifted to a Symfony response object.

The used code is similar to the following one.

```
$header = drupal_get_http_header('Status');

switch ($header) {
  case '403 Forbidden':
    // Add new headers.
    // …
    break;

  case '404 Not Found':
    // Add new headers.
    // …
    break;
}

```

What code should I use in Drupal 8? If that means to use a different hook, that is fine.

I would also be interested in the case I need to add HTML output to the page. I guess that in this case I should use `hook_page_alter()`, but I still don't know how to access the response object for the page being served.

# Answer
You can subscribe to the Symfony `KernelEvents::RESPONSE` event:

> The RESPONSE event occurs once a response was created for replying to a request
>
> This event allows you to modify or replace the response that will be replied. The event listener method receives a Symfony\Component\HttpKernel\Event\FilterResponseEvent instance.

To do so, create a new module ("response\_test" in this example), with the usual .info.yml and .module file.

Then register your event subscriber in the module's services file.

### response\_test.services.yml

```
services:
    response_test.response_subscriber:
      class: Drupal\response_test\ResponseSubscriber
      tags:
        - { name: event_subscriber }

```

Now all you need is the class to handle the event.

### lib/Drupal/response\_test/ResponseSubscriber.php (src/ResponseSubscriber.php in latest Drupal 8 versions)

```
namespace Drupal\response_test;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ResponseSubscriber implements EventSubscriberInterface {

  public function onRespond(FilterResponseEvent $event) {
    if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
      return;
    }

    $response = $event->getResponse();
    if ($response->getStatusCode() == 404) {
      // Prepare a new Symfony\Component\HttpFoundation\Response and use
      $event->setResponse($new_response);

      // or call one of the setter methods on $response, the changes will persist
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;
  }

}

```

I'm a little unsure about changing the HTML content in this context; you have access to `$response->getContent()` and `$response->setContent()` so you can manipulate the raw string directly, but as far as I can tell everything's already rendered at this point.
> 4 votes

# Answer
To check for error codes you can use the following snippet. It won't work for 200 status codes though. Since there's no exception.

```
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

$exception = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
if ($exception instanceof HttpExceptionInterface) {
  $status_code = $exception->getStatusCode();
  // ...
}

```

I'm unsure if it's safe to assume that the status code must be 200 if there's no exception in the first place. If yes you could use the following snippet to cover a 200er response.

```
if (!\Drupal::requestStack()->getCurrentRequest()->attributes->has('exception')) {
  $status_code = '200';
}

```
> 3 votes

---
Tags: hooks, 8
---


# Question
Title: Is there a way to partially rebuild the router or invalidate a route cache?
I'm using the Groups module (http://dgo.to/group) to set up groups on a SaaS project I'm working on. I've set up a domain field on the groups, allowing groups to have vanity domain. As such, groups can have custom front pages, which are shown at site route. The front page is set as a field on the Group entity. For example, group 1 may set their front page path as `/page/1` and group 2 may set it as `/page/2`.

To show this front page, I'm using inbound URL processing, showing the different paths on the different domains. To get the different paths to cache independently, I've overridden `Drupal\Core\Routing\RouteProviderRouteProvider::getRouteCollectionCacheId()`:

```
  /**
   * {@inheritdoc}
   */
  protected function getRouteCollectionCacheId(Request $request) {
    $cache_id = parent::getRouteCollectionCacheId($request);

    // Get the current domain.
    $domain = $this->currentPath->getRequestStack()->getCurrentRequest()->getHost();

    $cache_id .= ':' . $domain;

    return $cache_id;
  }

```

I've got this all working, however I ran into an issue in that when the path to the front page of a group is updated, the page content doesn't update until the router is rebuild.

I did find a solution, rebuilding the router in `hook_entity_update()` using `\Drupal::service('router.builder')->rebuild()`. This works, but it seems very heavy handed.

I tried finding a way to invalidate the cache tags for the route using the cache tags invalidator, but I could not figure out which cache tags to pass.

So my questions are:

1. Is there a way to partially rebuild the router, rather than rebuilding the whole thing? Or...
2. Is there a way to invalidate the cache for a route?

# Answer
Instead of `\Drupal::service('router.builder')->rebuild()` you can invalidate route matches:

```
Cache::invalidateTags(['route_match']);

```

You don't need to rebuild the router table, because the static routes don't change. What you need to clear are route matches, which are calculated on the processed path and then stored for the unprocessed path. And this is the relation which changes in your case.

The router builder invalidates the route matches because after a route rebuild there might be routes missing which are still in route match collections.

To be more selective you can add a second cache tag for the frontpage in `RouteProvider::getRouteCollectionForRequest` and then only invalidate this tag.

Of course you also need to invalidate entries of the front page stored in page caches, but the front page has probably already a specific cache tag you can target.
> 5 votes

---
Tags: 8, routes, caching
---