# Question
Title: How do I make a link to a flagging edit page?
I'm using Drupal 8 with Flag 4.0-beta1.

On my flag, I have several fields. I want users to be able to edit these fields after making the flag.

How can I make a link to edit the flagging?

I tried various things in Views (making a view of flaggings; making a view of nodes with flaggings as a relationship), but I can't find a way to get an edit link to the flagging (to edit the fields on the flag itself).

NOTE: This question is about flaggings (an instance of a flag). Here's the same question about flags.

# Answer
> 2 votes
Digging into the flag module a little, I can see this entry in `flag.routing.yml` that appears to be for your Flagging edit screen.

```
flag.field_entry.edit:
  path: '/flag/details/edit/{flag}/{entity_id}'
  defaults:
    _controller: '\Drupal\flag\Controller\FieldEntryFormController::edit'
    _title_callback: '\Drupal\flag\Controller\FieldEntryFormController::editTitle'
  requirements:
    _flag_access: 'entity:flag{flag}'

```

You can build out the link to the flagging manually, e.g.

```
<a href='/flag/details/edit/FLAG_ID/FLAGGING_ID'>Edit My Flagging</a>

```

Or if you're working with twig, e.g. rewriting a view's field, make sure you're also including the flag's id and flagging's id in the view then rewrite doing something like:

```
<a href='/flag/details/edit/{{ FLAG_ID }}/{{ FLAGGING_ID }}'>{{ "Edit Flagging"|t }}</a>

```

Or you can use PHP to build the url directly from the route. It's recommended to use one of the following methods if you're working in PHP.

To get just the url text or object in PHP, use Url::fromRoute():

```
use \Drupal\Core\Url;

$my_flagging_url_object = Url::fromRoute('flag.field_entry.edit', [
  'flag' => FLAG_ID,
  'entity_id' => FLAGGING_ID,
]);
// $my_flagging_url_string returns something like "/flag/details/edit/123/1234"
$my_flagging_url_string = $my_flagging_url_object->toString();

```

To build the whole link in PHP, use Link::createFromRoute():

```
use \Drupal\core\Link;

$my_flagging_edit_link = Link::createFromRoute('MY FLAGGING EDIT TEXT', 'flag.field_entry.edit', [
  'flag' => FLAG_ID,
  'entity_id' => FLAGGING_ID,
]);

```

# Answer
> 0 votes
It turns out that you can also use the "Unflag" link, and if the flag has fields, it will open an edit form... if you set the **Link type** to **Field Entry Form** on the flag admin page.

I didn't even think to try this because "unflag" and "edit" sound like completely different operations to me.

Thankfully, on the flag's edit page, you can change the text from "unflag" to "edit", which makes it much more clear.

Then you can add the "flag/unflag" link field in Views to give an easy way to get to the edit form.

---
Tags: 8, flags
---


# Question
Title: Replace the URLs entered in a textarea with "url_removed"
I am using Drupal 8.9.1 and Webform module 8.5.16. I looking for the best way to either replace all URLs that a user might enter in a text area with "url\_removed" or not allow the user to enter a functioning URL.

The goal is to prevent webform submission emails from having potentially malicious links within them the body of a comment.

# Answer
When adding your text area to the webform you can set form validation and use a regex that makes sure the text is free of urls. Something like:

/^(?!.*(http|www|ftp|file|data|irc)).*$/gmi

You definitely want to revise the actual regex as Im sure this one is not all inclusive. I'm far from a regex expert.
> 0 votes

---
Tags: webforms
---


title: Theme a contact form

text:
# Question
Title: Theme a contact form
I'd like to theme a contact form in Drupal 8. I'd like to put divs around form elements (using bootstrap).

I also want to put some classes on certain elements (submit button, the form itself).

# Answer
Open up your YOURTHEMENAME.theme file and add the following code:

```
function YOURTHEMENAME_form_contact_message_feedback_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Name
  $form['name']['#prefix'] = '<div class="row"><div class="col-md-6"><div class="form-group">';
  $form['name']['#suffix'] = '</div>';
  $form['name']['#attributes']['placeholder'][] = $form['name']['#title'].'*';
  $form['name']['#attributes']['class'][] = 'form-control';
  unset($form['name']['#title']);

  // Mail
  $form['mail']['#prefix'] = '<div class="form-group">';
  $form['mail']['#suffix'] = '</div>';
  $form['mail']['#attributes']['placeholder'][] = $form['mail']['#title'].'*';
  $form['mail']['#attributes']['class'][] = 'form-control';
  unset($form['mail']['#title']);

  // Subject
  $form['subject']['widget'][0]['value']['#attributes']['class'][] = 'form-control';
  $form['subject']['widget'][0]['value']['#attributes']['placeholder'][] = $form['subject']['widget'][0]['#title'].'*';
  $form['subject']['widget'][0]['#title'] = '';
  unset($form['subject']['widget'][0]['value']['#title']);
  $form['subject']['widget'][0]['#prefix'] = '<div class="form-group">';
  $form['subject']['widget'][0]['#suffix'] = '</div></div>';

  // Message
  $form['message']['widget'][0]['value']['#attributes']['class'][] = 'form-control';
  $form['message']['widget'][0]['value']['#attributes']['placeholder'][] = $form['message']['widget'][0]['#title'].'*';
  $form['message']['widget'][0]['#title'] = '';
  unset($form['message']['widget'][0]['value']['#title']);
  $form['message']['widget'][0]['#prefix'] = '<div class="col-md-6"><div class="form-group">';
  $form['message']['widget'][0]['#suffix'] = '</div></div></div>';

  // Submit
  $form['actions']['#prefix'] = '<div class="clearfix">';
  $form['actions']['#suffix'] = '</div>';
  $form['actions']['submit']['#attributes']['class'][] = 'btn';
  $form['actions']['submit']['#attributes']['class'][] = 'btn-success';
  $form['actions']['submit']['#attributes']['class'][] = 'pull-right';

}

```

And here is your result:

Don't forget to clear your caches ;)
> 16 votes

# Answer
You can simply theme every form how you want. I don't like the method by @rpayanm, cuz it hard to maintane and hard readable, with big forms this is not the case, just single wrapper and simple structure.

Every form trying to use theme equals their machine name. You can find this template name in `$form['#theme']` just by alter, it is always (or in most times) same as form id machine name. What you need to do is register template for it. You need to implement `hook_theme()`. You can write it in CUSTOMMODULE.module or in THEMENAME.theme. Theme key must be the same as in `$form['#theme']`, so its automatically use it, otherwise you need to add new one via form alter.

```
/**
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'FORM_ID_THEME' => [
      'template' => 'custom-form-template-name',
      'render element' => 'form',
    ]
  ];
}

```

Drupal pass $form variable with form.

Then you must create `custom-form-template-name.html.twig` (with your template name from hook\_theme()).

The minimal template is

```
{{ form }}

```

You also can print every field from form where you want

```
{{ form.field_name }}

```

Here you can do whatever you want with markup.

You also can pass additional data to template by implementing `template_preprocess_TEMPALTENAME`

```
function template_preprocess_FORM_ID_THEME(&$variables) {
  $variables['example'] = 'This is added via preprocess';
}

```

And then use in template

```
{{ example }}
<div class="first-field">
  {{ form.first_field }}
</div>

<div class="second-field">
  {{ form.second_field }}
</div>

<div class="buttons">
  {{ form.submit }}
  {{ form.preview }}
</div>
{#
Don't forget to add printing form special info at the end.
Without this data form will not working propertly.
#}
{{ form.form_build_id }}
{{ form.form_token }}
{{ form.form_id }}

```

I think this method is more fliexible, clean and powerful.

P.s. sorry for my english, hopes someone edit and fix my mistakes :)

Example of complex form using this method.
> 25 votes

# Answer
You have a similar approach here:

```
//file themename.theme
function themename_preprocess_node(&$variables) {
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->getType() == 'application') {
        $message = \Drupal::entityTypeManager()
            ->getStorage('contact_message')
            ->create(array(
            'contact_form' => 'webentwickler_job', //ID(Machine name) of form
        ));
        $form = \Drupal::service('entity.form_builder')->getForm($message);
        $variables['application_form'] = $form;
    }
  }
}

//file node--application.html.twig
{{ application_form }}

```
> 0 votes

---
Tags: theming, 8, emails
---


# Question
Title: Why do I get an error related to a controller when I created a custom module?
I created custom module following the *Creating a custom module on Drupal* tutorial.

The teacher of this tutorial demonstrated how you can create a custom module that displays on the page `Hello world`. But I have a slightly more difficult task. I need to create a custom module that will display the weather on the page, receiving data using API, like this.

**17.52
1016
London**

### What I did.

I created the weather.info.yml file.

```
name: Weather module
description: Weather module
core: 8.x
type: module
package: Weather

```

I created the weather.routing.yml file.

```
weather.weather_page:
  path: '/weather'
  defaults:
    _controller: '\Drupal\weather\Controller\WeatherPage::getWeather'
  requirements:
     _permission: 'access content'

```

In src/Controller, I created the WeatherPage.php file.

```
namespace Drupal\weather\Controller;

class WeatherPage
{
  public function getWeather($city)
  {
    $response = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q='.$city.',uk&appid=32ae008b1c7259324aa50450687fabf5&units=metric');
    $jsn = json_decode($response);

    echo $jsn->main->temp;
    echo '<br>';
    echo $jsn->main->pressure;
    echo '<br>';
    echo $city;

  }
}

$class = new WeatherPage();
$class->getWeather('London');

?>

```

I get an error related to the controller.

>

How do I fix this error?

P.S. One forum user writes that the problem may be due to:

* The controller must return the array
* No code should be behind the class

I'm a Drupal newbie.

# Answer
You need to add the parameter to the path. Change this:

```
path: '/weather'

```

To this:

```
path: '/weather/{city}'

```

Note that the parameter name `{city}` must be expressed as the parameter `$city` in your callback (which you've done). If you for exampled changed the function definition to `getWeather($c)`, you would get an error.

Also, you need to remove this code:

```
$class = new WeatherPage();
$class->getWeather('London');

?>

```

And finally, you'll need to return a render array. Change this:

```
echo $jsn->main->temp;

```

To this:

```
return [
  '#markup' => $jsn->main->temp,
];

```
> 3 votes

---
Tags: views, 8, routes, page-controller
---


# Question
Title: Hierarchy of content types with taxonomy as parent
What would be the best way to implement a hierarchical structure like this:

* (A) Taxonomy term from single vocabulary
    + (B) Some content type with parent of type A
        - (C) Some content type with parent of type B

There are reference fields from (B) to (A) and from (C) to (B) but not from (C) to (A).

Basically i need to implement something like this:

```
Topic (taxonomy term)
|___ Subtopic (custom content type)
         |___ Page (custom content type)
         |___ Page (custom content type)
         |___ + N
|___ Subtopic (custom content type)
         |___ Page (custom content type)
         |___ Page (custom content type)
         |___ + N

```

I tried using entity reference in all flavours but with not much success. I don't know how to:

* Implement path aliasing when i add content of type (C) so i have hostname/(A)/(B)/(C) so i don't have to enter the url manually (tried with url patterns but couldn't do it)
* Create a view that displays content belonging to (C) with `Context Filters` on `hostname/(A)/(B)/(C)` url

Any help is much appreciated!

# Answer
The most suitable structure in your case seems to be to create two-level Taxonomy for your `Topic` and `Subtopic`, and a Content Type with Taxonomy term Entity Reference Field.

If you want to limit which Taxonomy level appears when creating new nodes you can configure the Entity Reference field to use the Views Entity reference Display that filters and shows only the second level.

Use Pathauto module to set up automatic URL patterns based on the Taxonomy field and node title.

With Views you can create a Page with Contextual filters for the Taxonomy with Depth or Parent term, and the actual term the node is tagged with. These are two Contextual filters, each gives you one argument in the path.

With the first Contextual filter you filter out all the nodes that are tagged with the the child of the parent from the first URL argument. When you add the second Contextual you narrow it down to the particular Child term.

The third Contextual can be added for the node title, or node ID.

ER fields store entity IDs, not their names, so if you want the actual names in the path as arguments, and not the ID numbers, you'll have to add the Relationship for the ER field. This will open up more options in Views for the Vocabulary fields.

The solution I've described isn't trivial. If you're inexperienced in setting up Contextual filters try to practise first on simple examples. You can find many examples here with answers about Contextuals, Names, and Relationships.
> 1 votes

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


# Question
Title: Where to translate SHOW DETAILS from a display view?
I would like to find out where would I be able to translate the SHOW DETAILS/HIDE DETAILS menu options a DATATABLES FORMAT view. We are using Drupal 7, and I have tried to find it in the Configuration options, with no success. Would this need to be changed in the back end of Drupal?

# Answer
> 0 votes
This string seems to be a part of the interface, so you can translate it through `Configuration » Regional and language » Translate interface` (`/admin/config/regional/translate/translate`).

You have to enter the exact capitalisation into the search as is written in code (it's case sensitive), not necessarily what you see on the screen (CSS can affect what capitalisation is used in display).

The string won't appear on this list unless you have visited a page with that string in another language (other than English) so Drupal picks it up and makes it available for translation.

---
Tags: views
---


# Question
Title: Loop through multiple values from an array to create multiple arrays
I have $host\_entity which contains:

```
field_eventorganizer (Array, 1 element)
und (Array, 3 elements)
0 (Array, 1 element)
target_id (String, 2 characters ) 20
1 (Array, 1 element)
target_id (String, 4 characters ) 345
2 (Array, 1 element)
target_id (String, 2 characters ) 678

```

and the below code in which I need to create multiple arrays inside the `array('#markup'`.

```
$organisers=user_load($host_entity->field_eventorganizer['und'][0]['target_id']);
$organiser_email=$organisers->mail;
    $build['field_eventorganizer'] = array(
    '#theme' => 'registration_property_field',
    '#label' => 'Event Organiser(s)',
    '#items' => array(
        array('#markup' => l($username, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
        ),
        '#classes' => 'field field-label-inline clearfix',
    );

```

Do I need to create a foreach loop after `array('#markup' =>` ?

# Answer
> 0 votes
Try this to loop the `$build` variable :)

```
// define variables
$organisers[] = "";
$organiser_email = "";
$organiser_name = "";
$email_delimiter = "; ";

// recreate the array from your example
$organisers['und'][0]['target_id'] = 20;
$organisers['und'][1]['target_id'] = 345;
$organisers['und'][2]['target_id'] = 678;

// populate $build variable
$build['field_eventorganizer'] = array(
      '#theme' => 'registration_property_field',
      '#label' => 'Event Organiser(s)2',
      '#classes' => 'field field-label-inline clearfix',
    );

// because the numbers are nested in the array, I've chosen to use `for` instead of
// `foreach` to use $i as the iterator then rebuild what I'm looking for in the loop. I've
// used count($organisers['und']) because the next piece of the array is the number we are
// using to load user data.

for ($i = 0; $i < count($organisers['und']); $i++) {
    // load the user object based on $i
    $organisers = user_load($host_entity->field_eventorganizer['und'][$i]['target_id']);
    // fetch loaded users email
    $organiser_email = $organisers->mail;
    // fetch loaded users name
    $organiser_name = $organisers->name;
    // populate $build variable
    $build['field_eventorganizer'][] = array(
      '#items' => array(
        array('#markup' => l($organiser_name, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
      ),
    );
}

```

Side note: Not sure if it was intentional or not, but be careful of your plurals. You are using `$organisers` and `$organiser_email` which can sometimes be missed and cause a headache.

---
Tags: 7
---


# Question
Title: Import content using the "Default Content for D8" module
I am using Default Content for D8 to import content on my site.

After Profile installation completed, I enabled my custom default content module with contents sample json for node entity \[my\_module/content/\[entity\_type\]/anything.json\].

I get the following error:

> Symfony\Component\Serializer\Exception\UnexpectedValueException: Type /drupal-pro-8/rest/type/node/article does not correspond to an entity on this site. in Drupal\hal\Normalizer\ContentEntityNormalizer-\>getTypedDataIds() (line 239 of \drupal-pro-8\core\modules\hal\src\Normalizer\ContentEntityNormalizer.php).

And the node isn't imported...

What have I done to try to fix it:

. Ensure I have the article content type;

. Flushed all cache;

. Tested in different browsers;

. In the module page it says all tests were passed with the following conditions: PHP 5.5 & MySQL 5.5, D8.5 6. I started to use the same version of PHP, MySQL and D8.

After all this, the same problem keeps on appearing and I can't understand why this happens. May I missed something. Any help.

Thanks in advance.

# Answer
> 1 votes
This will be probably resolved by setting the \_links type href domain as `http://drupal.org` (the default links domain used by default\_content module) in yor .json files to import, instead of `drupal-pro-8` that was set form the site you exported?.

---
Tags: 8, nodes, installation-profiles
---


title: File size on View

text:
# Question
Title: File size on View
Is there a way to display the file's size next to it in a View? This is for a File field in Drupal 8.

I tried the advice (for D7) here, but I received this error.

> The handler for this item is broken or missing. The following details are available: Enabling the appropriate module may solve this issue. Otherwise, check to see if there is a module update available.

I am not sure which module it means. When I go to the modules list, the only thing with "file" in it is the actual File field module, which is installed. I ran `composer update` earlier today, and the status report shows that everything is current.

I also thought I might be able to do this by adding a field or doing a field re-write. So I looked under the list of available fields to add to the View and didn't see anything about file size there.

# Answer
> 1 votes
Various file properties are available directly in Views if you're Views type is `File`.

Since your Views type is probably `Content` you have to add the Relationship for the file field in your content that references the file(s).

The File field inside a Content Type only stores the reference to the file ID, nothing else.

When you add the Relationship for the File field from the `Content` Category, new fields will become available in Views. I twill be called something like **File (field\_file:target\_id)**. You can Require it if you only want to see results where that field isn't empty.

When you go to add a new field you will see **File size** available from the `File` Category.

# Answer
> 1 votes
You have different options:

* create a pseudo field which markup is showing file size
* preprocess the file field
* relationship on view for file field and then you are able to place filesize field or in overridden markup

If you go with custom you can use (load file entity) function https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/format\_size/8.2.x

---
Tags: 8, views, files
---


# Question
Title: Can't find migration when running drush migration:status
I'm trying a tutorial to migrate users data from a CSV file.
From here: https://u.group/thinking/drupal-8-csv-migration/

I've created a module as suggested. Here is the code:

**/config/install/migrate\_plus.migration.demo\_user\_migration.yml**

```
id: demo_user_migration
langcode: en
dependencies:
  enforced:
    module:
      - user_migrate
label: 'User migration from CSV'
source:
  plugin: csv
  track_changes: true
  path: /config/users.csv
  header_row_count: 1
  ids:
    - Uid
destination:
  plugin: entity:user
process:
  name: Name
  mail: E-mail
  field_last_name: First Name
  field_first_name: Last Name
  status: Active status
migration_dependencies:
  required: {  }
  optional: {  }

```

**user\_migrate.info.yml**

```
name: User Migrate
type: module
description: Custom Migrate of Users using a CSV file
core: 8.x
package: Migration
dependencies:
    - migrate_source_csv
    - migrate_plus
    - migrate_tools

```

**user\_migrate.module**

```
<?php

/**
 * @file
 * Contains teacher_migrate.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function user_migrate_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the custom_user_migrate module.
    case 'help.page.user_migrate':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('User Migrate') . '</p>';
      return $output;

  }
}

/**
 * Implements hook_migration_plugins_alter().
 */
function teacher_migrate_migration_plugins_alter(&$definitions) {
  $definitions['demo_user_migration']['source']['path'] =
    drupal_get_path('module', 'user_migrate') . $definitions['demo_user_migration']['source']['path'];
}

```

I've enabled the module from the *Extend* page.

However, when I run `drush migration:status` the migration I've created is not found. This confirmed by executing `drush migrate:import demo_user_migration`

Do you know where the problem can be?

# Answer
> 0 votes
Did you try clearing drush cache with **drush cr drush**?

Also, the correct notation for checking the status is **drush migrate-status demo\_user\_migration**

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


title: Permit only one role to download files

text:
# Question
Title: Permit only one role to download files
I'm trying to set up a new D8 site. It needs to include some "subscriber only" type functionality. There is one content type which is little more than a title, a file, and one extra field for sorting purposes. There is also a View to make this visible to the end user. What I'm trying to do is let the unauthenticated site visitors see the list, but not download anything while the authenticated users in a specific Role are allowed to download those files. The site's owner will be taking care of adding people to it manually. It isn't too frequent of an event, apparently.

I see how to make the View itself only available to people in that Role. I see how to make content as a whole unavailable to the unauthenticated (Anonymous Users) in /admin/people/permissions. Am I going to have to disable Anonymous Users' access to all content and then enable it one content type at a time? Or is there a better way to achieve the goal?

I'm open to scraping the approach I've taken (Content Type, File field, and a View) and doing something else entirely if it would be better.

Note: We're currently using private files as the default storage location.

# Answer
> 2 votes
It's good you're using Private file system. That is one level of control you need to prevent the files from being freely downloaded.

Other levels of control are the Page (Views list), Node, and File fields.

You could create two different Views, one without the file field, and one with it, and use Role permissions on those pages. In this case you'd have to make nodes not accessible to all, which isn't fortunate if you want to control other types differently. There are modules, though, that you can use to set up different node type permissions.

But in your case I think it makes the most sense to have different File permissions. This way you don't have to duplicate Views or control node access.

You can do this with the Field Permissions module.

All can see the nodes and Views pages, but only special Roles will see the File field that has those special permissions.

# Answer
> -1 votes
You can create a field formatter for a file field.

When you extend the FormatterBase class you can implement method inapplicable or just prevent rendering by adding return false in a view method.

So add a check if currently logged in use has a correct role - render the file field, else don't display it.

---
Tags: views, files
---


# Question
Title: Define fields created through the UI as non-revisionable on a revisionable entity
Let's say, I have a revisionable entity. Whether base fields should be revisionable or not can be set in the code. So far, so good.

But how about those fields that get added through the user interface? Is there a way to set all the fields as either revisionable or non-revisionable? Or is there a way to set this for each field individually in the UI?

# Answer
By default, all the entity fields created from the user interface are set as revisionable, and the user interface doesn't allow to set a field as not revisionable. That information is added from `field_entity_field_storage_info()`, which contains the following code.

```
$ids = \Drupal::entityQuery('field_storage_config')
  ->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
  ->execute();

// Fetch all fields and key them by field name.
$field_storages = FieldStorageConfig::loadMultiple($ids);
$result = [];
foreach ($field_storages as $field_storage) {
  $result[$field_storage->getName()] = $field_storage;
}
return $result;

```

`FieldStorageConfig::isRevisionable()` always returns `TRUE`.

```
public function isRevisionable() {
  // All configurable fields are revisionable.
  return TRUE;
}

```

To make a configurable field not revisionable, a module should implement `hook_entity_field_storage_info_alter()` and alter the `$field_storage` values returned from `field_entity_field_storage_info()`.

```
function mymodule_entity_field_storage_info_alter(&$fields, $entity_type) {
  $ids = \Drupal::entityQuery('field_storage_config')->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
    ->execute();

  // Fetch all fields and key them by field name.
  $field_storages = FieldStorageConfig::loadMultiple($ids);
  $result = [];
  foreach ($field_storages as $field_storage) {
    $result[$field_storage->getName()] = // Replace $field_storage with an object implementing FieldStorageDefinitionInterface and returning the value you want with isRevisionable().
  }
  return $result;
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Cannot update core with composer after switching to core-recommended
I tried to update core from 8.9.0 to 8.9.1 with `composer require drupal/core-recommended:8.9.1` but I get the following error:

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

Problem 1
- Can only install one of: drupal/core[8.9.1, 8.9.0].
- Can only install one of: drupal/core[8.9.1, 8.9.0].
- Can only install one of: drupal/core[8.9.1, 8.9.0].
- drupal/core-recommended 8.9.1 requires drupal/core 8.9.1 -> satisfiable by drupal/core[8.9.1].
- Installation request for drupal/core-recommended 8.9.1 -> satisfiable by drupal/core-recommended[8.9.1].
- Installation request for drupal/core (locked at 8.9.0) -> satisfiable by drupal/core[8.9.0].

```

This is pretty confusing, I thought drupal/core was replaced by drupal/recommended?

# Answer
I tried again with `composer require drupal/core-recommended:8.9.1 --update-with-dependencies` and it started to update core. Unfortunately drupal/core-composer-scaffold was not touched so I had to update it directly with an extra composer command.

Also I noticed that both of these were updated, I hope it is right:

```
- Updating drupal/core (8.9.0 => 8.9.1): Downloading (100%)
- Updating drupal/core-recommended (8.9.0 => 8.9.1)

```
> 0 votes

---
Tags: 8, composer
---


title: Feeds file path to content type

text:
# Question
Title: Feeds file path to content type
I’m using feed module to import csv file. and the content type includes file field. I added the external file path in the csv file (file column). but It's not working. Mapping includes:

```
Target:
Attachments: (field_file): File ID
Attachments: (field_file): Desciption

Feeds item: (feeds_item): item URL
Feeds item: (feeds_item): item GUID

Title(title)

csv:
ID
file
title

```

How I can deal with Attachments and Feeds item in source section. What I should put in the source section for Attachments and Feeds item.

Thanks in advance

# Answer
> 0 votes
Currently only files coming from a HTTP(s) source are supported in the D8 version of Feeds. So the sources for the files need to look like this:

Adding support for local file paths is planned: https://www.drupal.org/project/feeds/issues/2968671

See also other file target related issues: https://www.drupal.org/project/issues/search?issue\_tags=Feeds%20file%20target

---
Tags: 8, feeds
---


# Question
Title: Filter the list of entities referenced by "Entity reference revisions" field
I have a content type "Slider" which uses an Entity reference revisions field named "Slides" to save reference to various paragraphs that are then displayed on the frontend as a hero slider.

Everything works fine but now we have received a request of filtering out the slides by a show/hide boolean flag in the slide paragraph. Adding a boolean field to each such paragraph is straightforward but how do I filter those paragraphs based on it? I'm assuming a Drupal hook that allows a function to filter out the referenced entities by some arbitrary criterion but I've been unable to find it.

I understand that this question relates to a 3rd party module but it is quite possible that a core Drupal hook could be used in this context.

Any help will be greatly appreciated.

Thanks.

# Answer
> 1 votes
I'd recommend doing this by creating a new Field Formatter by extending the default EntityReferenceRevisionsEntityFormatter (or extending whichever formatter you're using to display the paragraphs). If you're not sure how to create a field formatter, review the Create a custom field formatter documentation on d.o.

Specifically, you'll need to override the `getEntitiesToView()` method, something like this:

```
protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
  $entities = parent::getEntitiesToView($items, $langcode);
  $allowed_entities = [];

  foreach($entities as $entity) {
    // Check if your show/hide checkbox is checked.
    // Note: I can't remember if this check is sufficient by itself.
    if (!$entity->my_show_hide_field->isEmpty()) {
      $allowed_entities[] = $entity;
    }
  }

  return $allowed_entities;
}

```

Lastly, you'll need to configure your entity reference revisions field to use this new formatter.

---
Tags: 8, entities, hooks
---


# Question
Title: Programmatically change placeholder text of form input
Inside a custom block plugin I'm creating, I programmatically load the user form and return it like so

```
public function build() {
    $fb       = \Drupal::formBuilder();
    $userform = $fb->getForm("Drupal\user\Form\UserLoginForm");

    $render = [
        '#type'       => 'container',
        '#attributes' => [
            'class'      => ['row', 'expanded'],
            'id'         => ['login-page-block']
        ],
        'userlogin' => [
            '#type'    => 'html_tag',
            '#tag'     => 'h3',
            '#value'   => 'Welcome Members!',
            'caption'  => [
                '#type'   => 'html_tag',
                '#tag'    => 'p',
                '#value'  => 'To access member-exclusive content on our website, you must login.',
            ],
            'form' => $userform,
        ],
    ];

    return $render;
}

```

It creates labels for the inputs for Username and Password, but I'd rather ditch the labels and put 'Username' and 'Password' as placeholders inside the input fields. However I'm not sure how I would go about doing that. I performed a die(print\_r($userform)); to get a list of fields in the array but I didn't see anything applying to the array.

Is there a way to place placeholder text inside the text input fields of a form that was programmatically retrieved and rendered?

UPDATE: I attempted changing the placeholder by writing

```
$userform['keys']['#attributes']['placeholder'] = t('Username');

```

But that didn't seem to do anything.

# Answer
I was able to add the placeholder text by entering

```
    $userform['name']['#attributes']['placeholder'] = t('Username');
    $userform['pass']['#attributes']['placeholder'] = t('Password');

```

After looking at the results of die(print\_r($userform)); more closely I saw that the username input was called 'name', and password was 'pass'
> 5 votes

# Answer
I've found this solution here that worked for me:

```
/**

 * Implements template_preprocess_input().

 */

function MYTHEME_preprocess_input(&$variables) {

  // Set a placeholder for all search form elements.

  if ($variables['attributes']['type'] == 'search') {

    $variables['attributes']['placeholder'] = $variables['element']['#title'];

  }

}

```
> 1 votes

---
Tags: forms, 8
---


# Question
Title: Twig template not rendering new field variable
I created a new field for a custom block type and have already exported necessary yml files and updated the yml for different view modes.

However, when I make a reference to the new field using the correct field\_machine\_name, it doesn't recognize it.

This new field is a checkbox, that when enabled, hides the h1 header of the page, but is still visible for screen readers.

sample code:

```
{% set hide_header_title = content.field_hide_header_title|render|striptags|trim %}

 {% if hide_header_title == 1 %}
    {% set hide_header_title = "show-for-sr" %}
  {% else %}
    {% set hide_header_title = "block" %}
  {% endif %}

```

With the code above, I'm only getting to the else statement.

# Answer
> 0 votes
> @4k4, thanks for sharing the link. I was able to retrieve the value this way: content.field\_hide\_header\_title\[0\]

`content.field_myfield[0]` still gets the rendered output, now of the first field item. It's not a good idea to use it for programming, because the output can be formatted in different ways and is translatable. You don't want to adjust the code anytime this is changing.

For programming if/else code better use the block content object.

`content['#block_content'].field_myfield.value`

This is a similar question for a node field: Boolean field inside node twig renders ok but does not work in if statement

---
Tags: 8, theming
---


title: How to imitate EVA with TWIG?

text:
# Question
Title: How to imitate EVA with TWIG?
On my Drupal 8.9 (with Twig Tweak module) home page I integrated a block with the following code :

```
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}

```

This block displays the rendered entity (with display mode `tasks-frontpage`) of the stores of the current user.

I rewrote the display mode of the stores with by creating the following file :

```
commerce-store--professionnel--tasks-frontpage.html.twig

```

Here is the file code. All views included in this code have a context filter with the path of the current store :

```
Vous avez
{% set dangers = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1') is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1') is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1') is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1') is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1') is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{{ dangers }}
tâches importantes dans votre {{ store_entity.type.entity.label }} "{{ store_entity.name.value }}".
<a href="/store/{{ store_entity.id }}/tasks" data-drupal-link-system-path="/store/{{ store_entity.id }}/tasks">Voir la liste</a>

```

**MY PROBLEM :**

When the `{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}` block is rendered on my home page, the blocks in the `commerce-store--professionnel--tasks-frontpage.html.twig` templates do not work. This is normal because I think it searches for the store ID in the URL.

How do I fix this ? There is an EVA module, but is there another way to do this directly with TWIG ?

**THE OBJECTIVE :**

The goal is to create a list of tasks in stores and display it on the user's home page.

The blocks views in the `commerce-store--professionnel--tasks-frontpage.html.twig` template are used to control this :

* If the store has no product.
* If one of the products in the store has no variation.
* If the store has an order in progress.
* If the store does not have an associated delivery method.
* If the store does not have an associated payment gateway.

It may be possible to control this directly in a store template without using views ?

**SOLUTION :**

```
Vous avez
{% set dangers = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{{ dangers }}
tâches importantes à traiter dans votre {{ store_entity.type.entity.label }} "{{ store_entity.name.value }}".
<a href="/store/{{ store_entity.id }}/tasks" data-drupal-link-system-path="/store/{{ store_entity.id }}/tasks">Voir la liste</a>

```

# Answer
> 0 votes
> **MY PROBLEM :**
>
> When the `{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}` block is rendered on my home page, the blocks in the `commerce-store--professionnel--tasks-frontpage.html.twig` templates do not work. This is normal because I think it searches for the store ID in the URL.
>
> How do I fix this ? There is an EVA module, but is there another way to do this directly with TWIG ?

If you don't want context filters getting IDs from the current path or current user you have to pass arguments to the View:

```
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1', store_entity.id()) }}

```

The arguments can be an array or a scalar if it is only one argument.

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


# Question
Title: Local Dev <subtheme>.theme file not loading
I'm working on a local development environment (via Acquia Dev Desktop). Our theme is a subtheme of the Stack theme.

In this situation, I'm making changes to my .theme file, but they don't seem to be loading at all. If I make the same changes to the stack.theme, they load and work as expected.

I've ensured I'm using function `<subtheme>_theme_suggestions_page_alter` but still no luck. There is nothing in the error.log either.

# Answer
Got it fixed on my local environment by putting the base theme name in quotes and then clearing the cache.

Changed `base theme: classy` to `base theme: "classy"`.

Also, check for a single quote on your theme's description. If you find it, make sure you put the whole description in quotes.
> 5 votes

---
Tags: 8, theming
---


# Question
Title: How can I prevent one template from displaying cached values?
I have a site with Drupal 8.9 and Twig Tweak.

I created 7 view blocks to set up a task list in stores. I want to display a task counter for my current user on my home page.

The tasks checks :

* If the store has no product (danger).
* If a product has no product variation (danger).
* If an order does not have the processed status (danger).
* If the store does not have a delivery method (danger).
* If the store does not have a payment gateway (danger).
* If a product from the store is not published (warning).
* If the store owner does not have the "merchant" role (warning).

I created a display mode in the types of stores, which I rewrite (integrating the 7 task blocks) with the following code :

commerce-store--professionnel--tasks-frontpage.html.twig

```
{% set warnings = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_produit_non_publie', 'block_1') is not empty %}
  {% set warnings = warnings + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_role_marchand', 'block_1') is empty %}
  {% set warnings = warnings + 1 %}
{% endif %}
{% set dangers = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}

{% if dangers or warnings > 0 %}
  <div class="alert alert-light border overflow-hidden shadow rounded hover mt-5 mb-0" role="alert">
    <div>
      <i class="fas fa-tasks fa-2x mr-4 float-left"></i>
      <div class="alert-heading h5 mt-0 mb-2">Des tâches requièrent votre attention dans votre <span class="text-lowercase">{{ store_entity.type.entity.label }}</span> "{{ store_entity.name.value }}".</div>
      <small>Veuillez passer en revue <a href="/store/{{ store_entity.id }}/tasks" data-drupal-link-system-path="/store/{{ store_entity.id }}/tasks">cette liste</a>.</small>
    </div>
    <hr class="mt-3 mb-3 border">
    <div class="d-flex justify-content-around">
      {% if dangers > 0 %}
        <p class="text-center mb-0"><i class="fas fa-times-circle fa-2x text-danger"></i><br>{{ dangers }} importante{% if dangers > 1 %}s{% endif %}</p>
      {% endif %}
      {% if warnings > 0 %}
        <p class="text-center mb-0"><i class="fas fa-exclamation-circle fa-2x text-warning"></i><br>{{ warnings }} avertissement{% if warnings > 1 %}s{% endif %}</p>
      {% endif %}
    </div>
  </div>
{% endif %}

{# /** TEST */ #}
{{ drupal_view('boutique_page_liste_des_taches_role_marchand', 'block_1', store_entity.id()) }}

```

I created a view block to display the stores of the current user :

I integrated this block to my home page :

page--front.html.twig

```
<div class="main-timeline">
  {{ drupal_view('accueil_page_liste_des_taches_utilisateur', 'block_1') }}
  {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}
  {{ drupal_view('accueil_page_liste_des_taches_groupe', 'block_1') }}
  {{ drupal_view('message_activity_stream_timeline_private', 'block_1') }}
</div>

```

I have disabled the cache for all views :

Great, the counter works :

**My problem :**

The counter never changes, to update it I have to do a `drush cr`.

How to correct this problem ?

Maybe I should add something to my `.theme` file.

To deactivate the cache of this template.

Or update this code with JS.

I DON'T WANT TO DESECTIVATE THE COVER FOR THE WHOLE SITE, BUT ONLY ON THE COUNTER.

Just for information, here is what the list of stains in a store looks like :

**UPDATE :**

I added this code at the end of the `commerce-store--professionnel--tasks-frontpage.html.twig` template.

Only this block is updated without any problems. For the rest of the code, it is cache and there is no update without clearing the cache manually.

It seems that the code adds them to the code (the counting functionality) is problematic.

```
{# /** TEST */ #}
{{ drupal_view('boutique_page_liste_des_taches_role_marchand', 'block_1', store_entity.id()) }}

```

I did not clear the cache. The counter is not updated. The added block is updated.

# Answer
> 4 votes
You need to add the correct cache metadata to the template. Since you don't render anything, you are just counting view results, Drupal can't bubble up the caching information from the rendered output. It's hard to tell what is the right thing to do because you don't provide any details about the type of template.

For testing you could render a cache max-age in the template directly

```
{{ {'#cache': {'max-age': 0}} }}

```

and later build a proper render array with the correct cache metadata when preparing the variables for the template.

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


# Question
Title: Is it possible to extend an existing contributed module?
There's a new Drupal module that I'm interested in integrating in our websites, the Media Entity File Replace module. I've already installed it via composer and created an update hook to enable it across our different profiles, but the problem is exporting its yml configuration file. Step 3 of the module's Usage Instructions says you have to enable it in the Form Display settings of the media type you wish to use it on. In our case, we just want it on Documents media type.

I looked for the yml configuration under Entity Form Display and found that it updates this particular file: *core.entity\_form\_display.media.document.default.yml*

I run a search in my local Drupal branch and found that that file only exists in the Acquia Lightning Media contributed module (docroot/modules/contrib/lightning\_media/modules/lighnting\_media\_document/config/install/)

How would I safely utilize the Media Entity File Replace Module without breaking a contributed module?

# Answer
**If you're using core's configuration sync to manage your site's config**, you should be able to update this through the UI, then export your site's configuration to the sync directory, e.g. `drush cex sync`. This will create a new file in the config sync directory for the updated config which can be safely committed along with your other changes. While deploying, you'll need to import the synced configuration, e.g. `drush cim sync` to import the UI change on your second environment.

Configuration files in a module's `config/install` directory are only read from that location when the module is installed. That configuration file shouldn't change at all here and there's no reason for it to.
> 0 votes

---
Tags: 8
---


title: How can I change the date format?

text:
# Question
Title: How can I change the date format?
I'd like to change the Date format of recent log messages (/admin/reports/dblog) in Drupal 8.9.1 from short date to something with the time. In Drupal 7 using watchdog I just edited the view and it was done. Since moving logging into core, I can't figure out where to edit the view. There is no view listed for Recent Log Messages or dblog and I can't find any other way to edit the date format. It's not an option in /admin/config/development/logging.

I know I can change Short Date globally to include time but I'm hesitant to change it everywhere just for an admin page. It seems like my only option is to create a new view with what I want and then replace the Recent page altogether.

Any help would be greatly appreciated.

# Answer
> 4 votes
This is still a view. The "Watchdog" view. Go to /admin/structure/views/view/watchdog and edit the date format. That's all.

# Answer
> 3 votes
Ok, using @leymannx's shock that I could access views and yet the watchdog view wasn't there, I did a grep of watchdog and found the following entry in /core/modules/dblog/dblog.post\_update.php:

```
/** Replace 'Recent log messages' with a view.*/
function dblog_post_update_convert_recent_messages_to_view() {
  // Only create if the views module is enabled and the watchdog view doesn't
  // exist.

```

This lead me to assume that when the module was enabled/added, my views module WASN'T enabled and so no view created for watchdog. I uninstalled dblog, checked again that Views was enabled, and re-enabled dblog. The watchdog view was created!

Thanks.

# Answer
> 1 votes
Short answer is change the date format in the view:

1. Change the date format used in the view at /admin/structure/views/view/watchdog

or

2. Edit the date format itself, that the view is using (which you don't want to do), so create a new one, at /admin/config/regional/date-time/formats/add and select that one in the view.

The default view that Watchdog reports uses on my D8 installation is the "Short Date Format", which out of the box includes the date and time in the php format `m/d/Y - H:i` e.g 06/22/2020 - 15:47

---
Tags: 8, log-messages
---


title: Views sum row for Degree

text:
# Question
Title: Views sum row for Degree
I am trying to get the SUM of a group of fields in a view. We hold events and I wanted to create a view that showed How many degree types by total. See below image for quick idea.

So, If there are 20 MD's, I want one row that shows MD's with a total of 20 - versus 20 rows of MD's.

I have look at views aggregation but since it isn't a number I can not see it working. I have also looked at view calc but that just shows a total at the bottom.

I am looking to figure out the best way to handle this. If I have to custom code any help pointing me in the right direction would be greatly appreciated!

# Answer
> 1 votes
You want to try using the Views Aggregator Plus community module.

The example from the Project page (very similar to your own):

> Say the original View based on raw database results looks like below.

```
Industry    Company Name    Turnover
IT          AquiB           $25,000,000
Clothing    Cenneton        $99,000,000
Food        Heiny           $66,000,000
IT          PreviousBest    $5,000,000
Food        McRonalds       $500,000,000

```

> Then with the grouping taking place on, say Industry, and aggregation functions TALLY, ENUMERATE and SUM applied on Industry, Company Name and Turnover respectively, the final result with a descending sort on the last column will display like below. Note that the module identified three groups. It also added a totals row, Views Calc style.

```
Industry        Companies            Turnover
Food (2)        Heiny, McRonalds     $566,000,000
Clothing (1)    Cenneton             $99,000,000
IT (2)          AcquiB, PreviousBest $30,000,000
Totals              5                $695,000,000

```

At that point I think you just need to play with output settings of that module ...

# Answer
> 0 votes
You can use the Views Calc module.

> This module adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

Then all you need to do is to set up aggregation properly. You should do a COUNT aggregate on a field that all of your degrees have in common, for instance content type.

# Answer
> 0 votes
In Drupal 8 (at the time of this writing), there is no Views Summarize, no Views Calc, and Views Aggregator Plus didn't work for me.

So I created another view with aggregation, and included it in the footer with *Global: View area*. It won't actually be a row in the table, but if you want it to look like it is, you could fix that with some theming.

---
Tags: views, entities
---


# Question
Title: How to disable/hide submit button in webform based on a computed_twig element's value
\[sorry for the length of this message, I tried to provide a concise decription of my problem in order to make it easier for people to understand and help\]

Hello all,

I have a webform comprised of 3 pages (two pages of input and a custom preview page).

I explain the whole webform in order to make my question more concise:

My first page has 4 inputs, all required (1 text field, 3 select fields). This works fine.

My second page is a little bit more complicated.

It has three 'triples', each triple consisting of: **one checkbox, one select, one number**.

None of these is required. The logic is that **when one checkbox is checked** (default value is unchecked), **the subsequent select and number will be enabled**, otherwise they are disabled (default).

You can find the code for one of these triples in the end of my post - the other two triples are similar.

This works ok, but my problem is this:

**A valid submission should only happen when: a. at least one checkbox is checked AND b. the total sum of all number fields is in the range 3-30.**

**Note: I can't simply force each number field to accept values in the range: 1-10, because user should be able to give up to 30 in one field and 0 on the other two.**

I have used a computed\_twig element and appropriate templates, and I have managed to put all my logic there and I show an appropriate message to the user. **This works ok**, so I have managed to print a green message when values are ok, and appropriate messages in red when values are invalid (if total sum is less than 3, or greater than 30 etc etc). I have covered all cases having enabled "Automatically update the computed value using Ajax" for the computed field, **it updates on-the-fly and user has correct information on whether data is OK or NOT**.

Now the problem and my question is:

**I have been trying to hide the submit button, by selecting appropriate logic in the 'conditions' tab of the submit button. For example, something easy like "hide" or "disable" submit button, when pressure\_total\_thickness (computed twig value which holds the sum of individual number fields - same computed field which I successfully use for my messages) is greater than 30 ..**

Problem is whatever I do there, the submit button is always present ...

***In a few words, what I want to do is validate data as much as I can in the front-end so that I don't allow invalid submissions. I can do checks in the back-end (because data will subsequently be fed into another software) but it would be nice to do as much validation as possible in the front end and not allow submissions when data is invalid. Hence, use my computed\_twig value which holds the sum of three number fields, and only show submit button when that value is between 3 - 30.***

For example, here is the page with all three 'triples' - user has checked 2nd and 3rd checkboxes and supplied 15 and 30 values respectively. Total is 45, which is invalid and appropriate red message is written:

however, when user goes forward and reaches submit phase, the submit bitton is present although I use following condition to 'hide' it (have tried 'disable' in cindition, but same result - submit button was shown).

Here is the simple such condition for the submit button, trying to 'hide' it:

I tried to find documentation and/or previous questions/answers, but could not find anything relevant..

I must be doing something wrong, but I can't find any way out of this ! ..

Webform is an amazing module, I am sure there is an easy way to achieve what I want. Any help would be appreciated!

Code for one of the three 'triples':

```
enable_insole:
    '#type': checkbox
    '#title': 'Enable Insole'
    '#description': 'Please enable insole if you want to enter custom values below for material and layer thickness.'
  select_insole_material:
    '#type': select
    '#title': 'Select Insole Material'
    '#options':
      1: Leather
      2: 'Composite leather & elastomer'
      3: EVA
      4: Polyisoprene
      5: 'Natural Rubber'
      6: Polychloroprene
      7: PTFE
      8: PU-Foam
    '#states':
      disabled:
        ':input[name="enable_insole"]':
          unchecked: true
    '#default_value': '0'
  insole_layer_thickness:
    '#type': number
    '#title': 'Insole Layer Thickness'
    '#help': 'See general help on choosing appropriate values for layers. Individual thickness for insole/midsole/outsole can have a range of 1-30 (mm), but total thickness of all layers  combined cannot exceed 30 (mm).'
    '#states':
      disabled:
        ':input[name="enable_insole"]':
          unchecked: true
    '#default_value': '0'
    '#min': 0
    '#max': 30
    '#step': 1

```

# Answer
> 0 votes
Well, I found a solution and I post it here for future reference..

I found this thread which was very helpful.

Now, looking at that post, I noticed the `'#value'` key in the form's code. So I ended up having another computed twig element in my form to incorporate the logic mentioned in my original post. The code for that element is:

```
the_sum:
    '#type': computed_twig
    '#title': 'the sum'
    '#value': |
      {% spaceless %}
      {% if data.enable_insole == 1 and data.enable_midsole == 1 and data.enable_outsole == 1 %}
         {% set total_thickness = data.insole_layer_thickness + data.midnsole_layer_thickness + data.outsole_layer_thickness %}
      {% elseif data.enable_insole == 1 and data.enable_midsole == 1 %}
         {% set total_thickness = data.insole_layer_thickness + data.midnsole_layer_thickness  %}
      {% elseif data.enable_insole == 1 and data.enable_outsole == 1 %}
         {% set total_thickness = data.insole_layer_thickness +  data.outsole_layer_thickness %}
      {% elseif data.enable_midsole == 1 and data.enable_outsole == 1 %}
         {% set total_thickness = data.midnsole_layer_thickness + data.outsole_layer_thickness %}
      {% elseif data.enable_insole == 1 %}
         {% set total_thickness = data.insole_layer_thickness %}
      {% elseif data.enable_midsole == 1 %}
         {% set total_thickness = data.midnsole_layer_thickness %}
      {% elseif data.enable_outsole == 1 %}
         {% set total_thickness = data.outsole_layer_thickness %}
      {% else %}
         {% set total_thickness = 0 %}
      {% endif %}

      {% if data.enable_insole == 0 and data.enable_midsole == 0 and data.enable_outsole == 0 %}
      {{ 0 }}

      {% elseif total_thickness < 0 %}
      {{ 0 }}

      {% elseif total_thickness < 5 %}
      {{ 0 }}

      {% elseif total_thickness > 30 %}
      {{ 0 }}

      {% else %}
         {{ 1 }}
      {% endif %}
      {% endspaceless %}

    '#ajax': true

```

Now, I find it a bit non-intuitive that I have to open the 'source' tab and hard-code the 'value' key (I found no other way to set it from UI - whatever I was writing was entered in the code with the 'template' key).

Anyway, so after this, I have the following condition in the submit button:

```
actions:
  '#type': webform_actions
  '#title': 'Submit button(s)'
  '#states':
    visible:
      ':input[name="the_sum"]':
        value: '1'

```

The funny thing is that if I choose the opposite logic, i.e. hide when value is 0, it doesn't work !!! (it always shows the submit button) ... I really don't know why .. But having the condition as visible only when value is 1 works correctly (shows it when sum is 1, hides it when sum is 0) ...

I 'm sure there must be a better way of doing this, but at least it now works .. I leave this open because (I hope) somebody might come up with a better solution ...

thanks.

---
Tags: webforms
---


# Question
Title: Display only taxonomy parents from an entity reference field
Is there a taxonomy entity reference field formatter to display only taxonomy parents from hierarcherical taxonomy elements ? Else what could be the way to display, from an entity reference field, only the taxonomy terms parents?

# Answer
> 1 votes
Create a custom view mode for taxonomy terms and display the taxonomy term as "rendered entity", using your customized view mode.

Then create a Twig template for that special view mode: Assuming your newly created view mode is `onlyparents`, create a template `taxonomy-term--onlyparents.html.twig`

There is no field like "parents", so there also is no pre-built field formatter for this. To get the parents, you will need to do some manual preprocessing like

```
function mymodule_preprocess_taxonomy_term(&$variables) {
  $term = $variables['elements'];
  $parents = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadAllParents($term->id());
  $variables['parents'] = $parents;
}

```

In Twig you can do something like

```
{% for parent in parents %}
  {{ parent.label }}
{% endfor %}

```

# Answer
> 0 votes
Inspired from Hudri answer, i have :

* created a taxonomy display mode taxo\_parent\_only
* use that display mode for my node entity referenced field display
* Add a suggestion and preprocess to my .theme
* Add a specific template

```
 function my_theme_theme_suggestions_taxonomy_term_alter(&$suggestions,
 $vars, $hook) {
    $term = $vars['elements']['#taxonomy_term'];
    $sanitized_view_mode = strtr($vars['elements']['#view_mode'], '.',
  '_');
   $suggestions[] = 'taxonomy_term__' . $term->bundle() . '__' .
   $sanitized_view_mode;   $suggestions[] = 'taxonomy_term__' .
    $term->id() . '__' . $sanitized_view_mode;   $suggestions[] =
    'taxonomy_term__' . $sanitized_view_mode;

    return $suggestions; }

 function my_theme_doc_preprocess_taxonomy_term(&$variables) {
     /* test if term is rank 1 of tree */
   $term = $variables['elements']['#taxonomy_term'];
   $storage = \Drupal::service('entity_type.manager')
  ->getStorage('taxonomy_term');
$parents = $storage->loadParents($term->id());
if(count($parents)===0){
     $variables['is_taxo_parent']= TRUE;   }
 }

```

taxonomy-term--myvocab--taxo-parent-only.html.twig

```
{% if is_taxo_parent is defined %}
    <div{{ attributes }}>
      {{ title_prefix }}
      {% if name and not page %}
        <a href="{{ url }}">{{ name }}</a>
      {% endif %}
      {{ title_suffix }}
      {{ content }}
    </div>
{% endif %}

```

---
Tags: taxonomy-terms
---


# Question
Title: Pull content from production to staging server
I have a setup that consists of a Drupal 8 instance on my `localhost`, a staging instance on a `develop` server and a productive version on a `production` server. Initially, I was co-designing the theme, the configuration and so on on my machine. But now, the site is live.

For configuration changes, I can update my local instance and export the configuration. Pushing this to my `develop` branch in my git repository automatically triggers a deployment on the `develop` server. Creating a new release triggers a deployment on the `production` server.

Now this situation: Content editors create new nodes on the instance on the `production` server. On some piece of the new content, they discover an issue and want a fix for that and maybe even want to review this fix on the `develop` instance.

I already have such a neat deployment for the configuration, so I really want to avoid copying databases around. For images, there's a module, that can replace local static files with links to the productive version. What would be the equivalent solution for the content in the database?

What might be a useful flow for the case that there's no better automation:

* I do a composer update on my local machine
* The content from develop gets pulled to my local instance
* I commit my changes and pull them to the `develop` instance
* The `develop` instance pulls content from the `productive` instance
* The `develop` instance reads my new configuration

It would be even better if there would be some API magic that enables my instances on `localhost` and `develop` to read the content directly (and cache it).

So, is there some API magic around? Or do I have to write scripts and everything to pull databases from server to server?

Additional requirement: I did most of the work so far and have all the administrative rights, but in the future, this should work for additional developers who should not need to login onto a server.

# Answer
Content is particularly difficult to Migrate. It's not as clean as Configuration. Generally, what you are talking about is not done - as Kevin points out, content is created on prod, and databases are pulled from prod to any other environment that needs that content. That said you could set up a Migration strategy with the Migrate API that could be used to migrate content around between environments. You're mostly on your own with this though - I haven't seen any tutorials for your specific issue.
> 1 votes

---
Tags: 8, workflows, staging
---


# Question
Title: View to display all child taxonomy terms
I have a content type called "Unit Staff" with a term reference field called "Department". I also have a vocabulary called "Person" which is using a paragraph field consisting of a date field and the same "Department" vocabulary as a term reference. Every department has several child terms. I want to create "Unit Staff" pages where I only select the unit name and a block will display all persons using the taxonomy term.

I have already all page views for every department but if something needs to be changed, I have to go through +30 pages and update them manually. I hope this way to be able to use one view for 30 units/departments.

In other words, I need a view for child taxonomy terms whose parent term is defined in a node taxonomy reference field.

Any help is appreciated.

# Answer
You actually want to list sibling entities, with another level of complication in between: the paragraph reference.

Both Unit staff and Person reference Department taxonomy, only the Person does it through a paragraph.

Had there been no paragraf and the reference was direct you could simply follow the sibling taxonomy tutorials to get what you want.

Here's an example:
Building views relationship with location

and one with additional complexity:
Views Contextual Filter by taxonomy in field collection

In your case the chained Relationships will be:

Unit staff to Department term reference \> Reverse Relationship from Department to Paragraph \> Reverse Relationship from Paragraph to Person.

Then you add the Person (Term Name) to your Fields, it will use the last Relationship.

This gives you a list of Unit staff nodes, each with related Persons.

If you want to show a block of Persons on Unit staff pages add the Contextual ID filter for the ID, Default value ID from URL (the most common case). Place the block on Unit staff pages, adjust the contextual options, and the block will show Persons related to the Department of that Unit staff.
> 2 votes

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


title: How do I add a site to a multi-site

text:
# Question
Title: How do I add a site to a multi-site
I am trying to convert my installation to a Drupal multi-site.

I have the original site (www.original.com) with a settings.php file under the sites/default folder. I want to add a new site by adding the following files.

* sites/original2.com/sites.php
* sites/original2.com/settings.php

I can access both URLs, but they use the default.settings.php file.

I have not changed anything in NginX as both URLs are resolved from Drupal on my docker instances.

# Answer
You have the *sites.php* file in the wrong spot, it should be at *sites/sites.php*, it should **not** be inside any of the site directories, such as *sites/original2.com/sites.php*.
> 3 votes

---
Tags: 8, multi-sites
---


# Question
Title: Site crashes after running 'composer install' to update modules
My website is running Drupal 8.8.x When upgrading to Drupal 8.9.x and then running 'composer install' on production everything seems to install as expected but the site then goes offline with a 500 error and running any Drush command outputs the below text. I suspect it may be an issue with something in my composer.json file but I have no idea what it could be. I have dozens of other similar Drupal sites and none have this issue.

I've spent a couple of days trying to figure out the cause or a fix without look. Any suggestions?

```
PHP Warning:  require(/home/WEBSITE/public_html/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /home/WEBSITE/public_html/vendor/composer/autoload_real.php on line 73

PHP Warning:  require(/home/WEBSITE/public_html/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /home/WEBSITE/public_html/vendor/composer/autoload_real.php on line 73

 PHP Fatal error:  require(): Failed opening required '/home/WEBSITE/public_html/vendor/composer/../../load.environment.php' (include_path='/home/WEBSITE/public_html/vendor/pear/pear_exception:/home/WEBSITE/public_html/vendor/pear/console_getopt:/home/WEBSITE/public_html/vendor/pear/pear-core-minimal/src:/home/ntgitc                                om/public_html/vendor/pear/archive_tar:.:/opt/alt/php73/usr/share/pear') in /home/WEBSITE/public_html/vendor/composer/autoload_real.php on line 73

```

# Answer
> 1 votes
Your composer.json probably has this in it (many do):

```
"autoload": {
  "files": [
    "load.environment.php"
  ]
}

```

But you don't have load.environment.php present in the file system.

Either remove the line from composer.json if you don't need to use dotenv, or add the file which typically contains something like this:

```
<?php
/**
 * This file is included very early. See autoload.files in composer.json and
 * https://getcomposer.org/doc/04-schema.md#files
 */
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
/**
 * Load any .env file. See /.env.example.
 */
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();

```

---
Tags: composer
---


# Question
Title: Do we have an option to change/override the drupalsettings variable which is defined by some other module through our custom module?
What is the best approach to change/override the `drupalsettings` variable which is defined by some other module (basically core) through our custom module ? If I follow the same hooks then how to call it at very last in **Drupal 8**?

Here: by `drupalsettings`, I am asking about the Drupal behaviors variable.

The question is updated as suggested by @leymannx.

# Answer
You can alter the drupalSettings with the hook "hook\_js\_settings\_alter":

```
function hook_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {

  // Add settings.
  $settings['user']['uid'] = \Drupal::currentUser();

  // Manipulate settings.
  if (isset($settings['dialog'])) {
    $settings['dialog']['autoResize'] = FALSE;
  }
}

```

For more information see: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook\_js\_settings\_alter/8.9.x

I checked the code and the theme hook is run after the module hook. So if you really want to be last. Add the hook to your theme.

web/core/lib/Drupal/Core/Asset/AssetResolver.php:

```
$this->moduleHandler->alter('js_settings', $settings, $assets);
$this->themeManager->alter('js_settings', $settings, $assets);

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Problem with drush and site alias (Drupal 8.8.6 / Drush 10.3.1)
I've installed two drupal sites on a share hosting (OVH), in two folders :

* dev.www
* www

I've installed drush 10.3.1 and create two alias, but when I try use alias (drush @dev status), I have the follow error :

```
[warning] Drush command terminated abnormally.

```

I don't know if my drush configuration or aliases are good or bad. Here is my configuration in .drush/sites/the-choices.site.yml:

```
'@the-choice.dev':
  remote-host: ...
  user: ...
  root: /home/thechoc/dev.www
  uri: 'http://dev.the-choice.org'
  ssh:
    options: '-o PasswordAuthentication=no -i /home/thechoc/dev.www/insecure_private_key'
'@the-choice.prod':
  host: ...
  user: ...
  root: /home/thechoc/www
  uri: 'https://the-choice.org'
  ssh:
    options: '-o PasswordAuthentication=no -i /home/thechoc/www/insecure_private_key'

```

If someone can help me. Thank in advance.

# Answer
There is no need for the leading `@name` and try adding the full path to drush for all remote environments:

```
dev:
  ...
  paths:
    drush-script: /example/path/www/vendor/drush/drush/drush
prod:
  ...
  paths:
    drush-script: /foo/bar/www/vendor/drush/drush/drush

```
> 1 votes

# Answer
I see two issues with what you're doing here.

1. As Hudri mentioned, you don't want the site name piece of the alias inside your aliases file. That part of the drush alias is determined by the alias file name.
2. When you use your alias, you should use use it like `drush @sitename.env status`, using the full alias name.

In your case, remove the `@the-choice` piece from your environment keys in your *.drush/sites/the-choices.site.yml* alias file, e.g.

```
'dev':
  remote-host: ...
  user: ...
  root: /home/thechoc/dev.www
  uri: 'http://dev.the-choice.org'
  ssh:
    options: '-o PasswordAuthentication=no -i /home/thechoc/dev.www/insecure_private_key'
'prod':
  host: ...
  user: ...
  root: /home/thechoc/www
  uri: 'https://the-choice.org'
  ssh:
    options: '-o PasswordAuthentication=no -i /home/thechoc/www/insecure_private_key'

```

With the above configuration and your alias file named *the-choices.site.yml*, you'll interact with the two sites like: `drush @the-choices.dev status` or `drush @the-choices.prod status`.
> 1 votes

---
Tags: 8, drush
---


# Question
Title: Hide Webform Message "You are viewing this form as..."
How can I hide the message at the top of a webform which says

***You are viewing this form as \[user name\]. Please click here if that's not you.***

# Answer
Doh! I didn't realise this was a configuration option in another module - Webform CiviCRM.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Can't update to 8.9.1 after migrating from webflo/drupal-core-strict to drupal/core-recommended
I successfully updated my drupal 8.7.8 site to 8.9.0 following the instructions on 'Migrate composer project for Drupal earlier than 8.8.0' Drupal documentation page, section 'Migrating from webflo/drupal-core-strict to drupal/core-recommended'.

```
    composer update # To update any dependencies as a separate step.
    git add composer.lock; git commit # Save the updates as a separate commit.
    composer remove webflo/drupal-core-strict --no-update
    composer remove drupal/core --no-update
    composer require 'composer/installers:^1.7' --no-update
    rm composer.lock
    rm -rf vendor # Also helps avoid conflicts.
    composer require drupal/core-recommended:^8.8 --update-with-dependencies
    git add composer.json composer.lock; git commit -m "Update Drupal to 8.8.0 and use drupal/core-recommended instead of webflo/drupal-core-strict"

```

Now I can't update drupal to 8.9.1.

I execute the command

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

> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.
Package webflo/drupal-core-require-dev is abandoned, you should avoid using it. Use drupal/core-dev instead.
Generating autoload files
38 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> DrupalProject\composer\ScriptHandler::createRequiredFiles

```

To check if the my project now uses drupal/core-recommended I executed

```
composer show drupal/core-recommended

name     : drupal/core-recommended
descrip. : Locked core dependencies; require this project INSTEAD OF drupal/core.
keywords :
versions : * 8.9.0
type     : metapackage
license  : GNU General Public License v2.0 or later (GPL-2.0-or-later) (OSI approved) https://spdx.org/licenses/GPL-2.0-or-later.html#licenseText
homepage :
source   : [git] https://github.com/drupal/core-recommended.git 1b87cf5dea633a66a1c4f22d635bc92c127071d9
dist     : [zip] https://api.github.com/repos/drupal/core-recommended/zipball/1b87cf5dea633a66a1c4f22d635bc92c127071d9 1b87cf5dea633a66a1c4f22d635bc92c127071d9
path     : /Applications/MAMP/htdocs/d8composer
names    : drupal/core-recommended

requires
asm89/stack-cors 1.3.0
composer/semver 1.5.1
doctrine/annotations v1.4.0
doctrine/cache v1.6.2
doctrine/collections v1.4.0
doctrine/common v2.7.3
doctrine/inflector v1.2.0
doctrine/lexer 1.0.2
drupal/core 8.9.0
easyrdf/easyrdf 0.9.1
egulias/email-validator 2.1.17
guzzlehttp/guzzle 6.5.4
guzzlehttp/promises v1.3.1
guzzlehttp/psr7 1.6.1
laminas/laminas-diactoros 1.8.7p2
laminas/laminas-escaper 2.6.1
laminas/laminas-feed 2.12.2
laminas/laminas-stdlib 3.2.1
laminas/laminas-zendframework-bridge 1.0.4
masterminds/html5 2.3.0
paragonie/random_compat v9.99.99
pear/archive_tar 1.4.9
pear/console_getopt v1.4.3
pear/pear-core-minimal v1.10.10
pear/pear_exception v1.0.1
psr/container 1.0.0
psr/http-message 1.0.1
psr/log 1.1.3
ralouphie/getallheaders 3.0.3
stack/builder v1.0.5
symfony-cmf/routing 1.4.1
symfony/class-loader v3.4.41
symfony/console v3.4.41
symfony/debug v3.4.41
symfony/dependency-injection v3.4.41
symfony/event-dispatcher v3.4.41
symfony/http-foundation v3.4.41
symfony/http-kernel v3.4.41
symfony/polyfill-ctype v1.17.0
symfony/polyfill-iconv v1.17.0
symfony/polyfill-intl-idn v1.17.0
symfony/polyfill-mbstring v1.17.0
symfony/polyfill-php56 v1.17.0
symfony/polyfill-php70 v1.17.0
symfony/polyfill-php72 v1.17.0
symfony/polyfill-util v1.17.0
symfony/process v3.4.41
symfony/psr-http-message-bridge v1.1.2
symfony/routing v3.4.41
symfony/serializer v3.4.41
symfony/translation v3.4.41
symfony/validator v3.4.41
symfony/yaml v3.4.41
twig/twig v1.42.5
typo3/phar-stream-wrapper v3.1.4

conflicts
webflo/drupal-core-strict *

```

I executed the command

```
composer prohibits drupal/core:8.9.1

drupal/core-recommended         8.9.0  requires  drupal/core (8.9.0)
webflo/drupal-core-require-dev  8.9.0  requires  drupal/core (8.9.0)

```

my composer.json file is

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.7",
        "cweagans/composer-patches": "^1.6",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/admin_toolbar": "^2.2",
        "drupal/backup_migrate": "^4.0",
        "drupal/console": "^1.0.2",
        "drupal/core-recommended": "^8.9",
        "drupal/ctools": "^3.2",
        "drupal/module_filter": "^3.1",
        "drupal/pathauto": "^1.5",
        "drupal/token": "^1.5",
        "drush/drush": "^9.0.0",
        "vlucas/phpdotenv": "^2.4",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3",
        "zaporylie/composer-drupal-optimizations": "^1.0"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "^8.7.0"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold",
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"]
        }
    }
}

```

I don't know how solve this issue. Thanks in advance for your help.

# Answer
I'm pretty new with Composer, so take this advice with some skepticism.

I think the problem is you deleted drupal/core:

composer remove drupal/core

I looked in my composer.lock, and found drupal/core-recommended requires drupal/core. (I think maybe drupal/core-recommended is a metapackage that encompasses drupal/core.)

Look at the results of the "prohibits" command. "core-recommended" requires "core".

Hope that helps, Bill
> -1 votes

---
Tags: composer
---


# Question
Title: What are the effects of the "access commerce administration pages" permission
The SA-CONTRIB-2020-020 security patch was titled "Further restrict anonymous user access to anonymous orders."

Unfortunately it seems to have broken some sites I work on. We are now seeing access denied errors on admin/commerce/orders/xxx for "semi-trusted" users who have permission "Default: Update orders". For these sites the security patch was a non-back-compatible change and I have raised an issue for that.

The solution that worked for me is to grant the semi-trusted users the "access commerce administration pages" permission.

However I am nervous because this permission doesn't seem to have clear documentation. I don't wish for these "semi-trusted" users to suddenly gain extra access that they should not have such as to edit products.

Please can anyone confirm the effects of this permission? Does it do nothing alone and only work if other permissions are added?

# Answer
> 0 votes
> Does it do nothing alone and only work if other permissions are added?

Currently, yes (although that could theoretically change in the future).

The permission is added to all HTML admin routes for the order entity type (add/edit/etc), and for admin overview pages, which essentially list sub-pages that the user has access to.

If the user doesn't have access to those sub-pages, all provided by separate permissions, they won't see the links, and won't be able to visit them. Similarly, if they don't have the correct entity access permission, they won't be able to perform the respective operation on the entity.

---
Tags: commerce
---


# Question
Title: How to redirect the user to the home page?
When users access the site, they are redirected to their user account page. I want to redirect them to the front page. If I leave the *Default front page* setting empty, users are redirect to their account page, while the description for the setting says they would be redirected to the front page.

>

In this field, you must put */node* to display the front page.

I know there are modules to do this, but I would like to avoid installing additional modules. Is there a configuration to achieve what I want, in Drupal 8.9.3?

# Answer
> 2 votes
What Drupal considers the default front page is not /node, but /user/login, which redirects logged-in users to their account page. `SiteInformationForm::validateForm()` contains the following code.

```
  // Check for empty front page path.
  if ($form_state->isValueEmpty('site_frontpage')) {

    // Set to default "user/login".
    $form_state->setValueForElement($form['front_page']['site_frontpage'], '/user/login');
  }

```

*site\_frontpage* is the form element for the front page, which in `SiteInformationForm::buildForm()` is set as follows.

```
  $front_page = $site_config->get('page.front') != '/user/login' ? $this->aliasManager->getAliasByPath($site_config->get('page.front')) : '';
  $form['front_page']['site_frontpage'] = [
    '#type' => 'textfield',
    '#title' => t('Default front page'),
    '#default_value' => $front_page,
    '#size' => 40,
    '#description' => t('Optionally, specify a relative URL to display as the front page. Leave blank to display the default front page.'),
    '#field_prefix' => $this->requestContext->getCompleteBaseUrl(),
  ];

```

Note that the Standard installation profile set the default front page to /node, in its system.site.yml file. Don't take that as the default front page. It's the default value assigned from that installation profile to the *Default front page* setting.

```
uuid: ''
name: ''
mail: ''
slogan: ''
page:
  403: ''
  404: ''
  front: /node
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en

```

---
Tags: 8, redirection
---


title: Install and use Azure SDK

text:
# Question
Title: Install and use Azure SDK
Is it possible to install Azure SDK via Composer within a Drupal site and use it in custom modules?

```
{
  "require": {
    "microsoft/windowsazure": "*"
  }
}

```

Also according to Microsoft docs, below code should be used in order to use Azure API. Not sure where though.

```
require_once 'vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;

```

# Answer
You don't need to autoload it in Drupal.

what you need is in the root of the Drupal run :

```
composer require microsoft/windowsazure

```

then in your custom module use it with

`use WindowsAzure\Common\ServicesBuilder;`
> 0 votes

---
Tags: composer
---


# Question
Title: Acquia Dev Desktop and Drush broken with syntax is incorrect
I did a clean install of Acquia Dev Desktop (Build Nov 13th, 2017) under Windows 10. I can clone my site (Drupal 8) and then click to open my local Drush console. It opens a DOS prompt into the docroot directory. When I execute any drush commands I get "The filename, directory name, or volume label syntax is incorrect."

Here is a sample:

> C:\DevDesktop\website-dev\docroot\>drush -d -d version
>
> Loading drushrc "C:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\drushrc.php" into "drush" scope. \[bootstrap\]
>
> \[0.78 sec, 2.48 MB\] Cache HIT cid: 8.1.15-commandfiles-0-61c5476a3a04a40d4bdadfd521f0641f \[0.84 sec, 2.52 MB\] \[debug\]
>
> Begin redispatch via drush\_invoke\_process(). \[1.16 sec, 6.43 MB\] \[notice\]
>
> Backend invoke: "C:\DevDesktop\website-dev\docroot\vendor\bin\drush.launcher" \[command\] --root="C:\DevDesktop\website-dev\docroot" --debug --verbose version 2\>&1 \[1.21 sec, 6.45 MB\]
>
> Calling proc\_open("C:\DevDesktop\website-dev\docroot\vendor\bin\drush.launcher" --root="C:\DevDesktop\website-dev\docroot" --debug --verbose version 2\>&1);
>
> The filename, directory name, or volume label syntax is incorrect. End redispatch via drush\_invoke\_process(). \[1.24 sec, 6.44 MB\] \[notice\]

# Answer
> 2 votes
Acquia Dev Desktop (ADD) comes with Drush 8 included. When you call `drush` the version coming with ADD is started (as you can see from the "Loading drushrc" debug). That version of Drush is then detecting your site local version of Drush - the one located in the vendor directory of your Drupal installation. (Just look at the path from the "Backend invoke" debug.)

The problem is that `drush.launcher` doesn't work on Windows.

There are two options that probably solves the problem:

1. Update your site local Drush to Drush 9 with Composer. This my recommended solution. (Drush 9 doesn't have `drush.launcher`)
2. If you don't want to use Drush 9, just delete the site local Drush with Composer.

PS! This problem is not related to the known Windows issue with ADD.

# Answer
> 3 votes
I was also facing the same issue on windows 10 with Acquia Dev Desktop and configured existing Drupal 8 project from a client.

Following three things what I did worked for me.

I simply:

1. Removed directory **vendor/drush**
2. Removed directory **vendor/bin**
3. Removed line `"drush/drush": "^8.1"` from **composer.json** which is located on docroot directory.

Now, default drush is working for me as you can see the default drush version at `C:\Program Files (x86)\DevDesktop\tools\composer.json`.

Hopefully, this will help someone else.

# Answer
> 1 votes
In my case installing drush through composer is what caused the error for me. I also had issues removing it with composer, so in order to get it working I manually removed the following:

```
/vendor/drush/
/vendor/bin/drush

```

After that it worked fine for me.

---
Tags: drush, acquia-dev-desktop
---


# Question
Title: How to order search results based on author field content
I am using Drupal 8 search views, I would like to order the search result so that the content that's author has field "X" filled out should be ordered first and all other content where the author has field "X" empty shows up after. How can I achieve this with views

I made a relationship between the content and the author. I can access field "x" in the fields part of views, but it does not show up in the "filter" or "order by" parts.

# Answer
> 1 votes
You are almost have done it.

> I made a relationship between the content and the author. I can access field "x" in the fields part of views, but it does not show up in the "filter" or "order by" parts.

add that fix "X" in sort section and sort it as **Descending**. when you make it descending contents with null values appear after those that have value.

# Answer
> 0 votes
The field needs to be added to the search index here:

```
/admin/config/search/search-api/index/YOUR_SEARCH_INDEX_NAME/fields

```

Then the field shows up in the sort and filter sections in views.

---
Tags: 8, views, users, search
---


# Question
Title: Permission to submit webform only for the author of the node
I'm using webform 8.x for a personal project and I'd like to know if it possible to enable only the author of the node to submit the form.

In my project each node is an aquarium, and I am using webform to collect the all the daily data for that specific node ( aquarium ), like temperature, pH, KH ecc. I was able to create a view related to the node (aquarium) where you can see the data submitted daily for that specific aquarium, but the problem is that everyone can submit the form, while I need only the author of the node to be able to submit the webform.

Can you please give me some ideas? I'm stuck..

# Answer
> 0 votes
After consulting Allow comments only for the author of the node and This book I think I can try to answer this question myself:

I made a custom module and I used hook\_form\_alter:

here is the function:

```
function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
if($form['#webform_id'] == "YOUR-WEBFORM-ID"){
    $node = \Drupal::request()->attributes->get('node');
 if(!is_null($node) && $node->getOwnerId() != \Drupal::currentUser()->id()) {
     $form['#access'] = false;
 }
}

```

}

# Answer
> 0 votes
You haven't said if this is Drupal 7 or Drupal 8 but this should work for D8

It sounds like each author already has a user account on your website, so you can go to "Settings" on your webform and then click the "Access" tab (.e.g /admin/structure/webform/manage/FORM\_MACHINE\_NAME/access)

And in there you can restrict the ability to create submissions to a specific user(s) only

---
Tags: nodes, webforms
---


# Question
Title: how to apply 'noindex' to all nodes and leave Alias indexable to prevent perceived duplicates for SEO
We're working with an SEO specialist who is finding that our underlying /node/### page URLs are competing with our aliases and bringing our page ranking, etcetera down - because they're perceived as duplicate content. (Drupal 8)

I'm looking at anything that is out there, but not sure if any of these cover what I need. Is there a simple way to set all urls containing `/node/*` to noindex, nofollow? Maybe a way in `robots.txt`?

Would simply adding this to robots.txt work?

```
Disallow: /node/*

```

As a side question, what are the ramifications of making such a change? Any issues I need to be aware of, protect against?

Or maybe there's another way people have solved this problem?

# Answer
For Drupal8 and 9 what you need is simply this module: https://www.drupal.org/project/redirect. It will redirect all /node/\* to its alias. For Drupal7: https://www.drupal.org/project/globalredirect
> 2 votes

---
Tags: 8
---


# Question
Title: How to get user all order_items from different orders by entityQuery
I want to know if the user has purchased the specified product. I know the SQL. But I am learning to use entityQuery.

Example: user\_id = 1, product\_variant\_id = 5

```
SELECT *
FROM commerce_order
    INNER JOIN commerce_order_item ON commerce_order.order_id = commerce_order_item.order_id
WHERE (commerce_order.state = 'completed')
    AND (commerce_order.uid = 1)
    AND (commerce_order_item.purchased_entity = 5)
ORDER BY commerce_order.completed DESC

```

Could anyone help me tansfer to entityQuery?

# Answer
> 0 votes
Unfortunately, what you want to do isn't possible with an entity query, because that API does not support the appropriate joins. While you can simulate a join between a base entity and field value tables with field conditions, you cannot query against field values of referenced entities. If all you needed were order items referencing the order ID and specific purchasable entity ID, you'd be fine to write a single entity query against the order item table, but once you need to filter by order status (or support multiple purchasable entity types), you need to use \Drupal::database()-\>select().

To build a select query for this, I'd use the following:

```
$uid = 1;
$entity_id = 1;
$state = 'completed';

$query = \Drupal::database()->select('commerce_order', 'co');
$query->leftjoin('commerce_order_item', 'coi', 'co.order_id = coi.order_id');
$query->fields('co', ['order_id']);
$query->condition('co.state', $state);
$query->condition('co.uid', $uid);
$query->condition('coi.purchased_entity', $entity_id);
$result = $query->distinct()->countQuery()->execute()->fetchField();

```

The main change between your query and this code is that I'm fetching a count of the distinct number of orders. If you're trying to get the order IDs, remove the `countQuery()` and replace the `fetchField()` call with `fetchAllKeyed(0, 0)`. If you really just want to search for a non zero count, you can remove the `distinct()` for faster query performance.

---
Tags: commerce
---


# Question
Title: Why is this if statement not working in twig?
It's a bidirectional D9 site where I removed **dir=rtl** from my theme's **html.html.twig** with an if statement and it's working fine. I did that to avoid an MS browsers bug ignoring **position: sticky** in css if there was any dir="rtl" in either html or body tags. I did so in **html.html.twig** with this code:

```
{% if html_attributes['dir'] == 'rtl' %}
  <html{{ html_attributes|without('dir') }}>
{% elseif html_attributes['dir'] == 'ltr' %}
  <html{{ html_attributes }}>
{% endif %}

```

So now, when the site is in English (or any LTR lang) the html tag has a dir="ltr" attribute in it but none if the dir is rtl. That's working well.

I added the **dir** attribute to **page.html.twig** #page-warpper like this:

```
{% apply spaceless %}
{% if html_attributes['dir'] == 'ltr' %}
  <div id="page-wrapper" dir="ltr">
{% else %}
  <div id="page-wrapper" dir="rtl">
{% endif %}
{% endapply %}
  <div id="page"> ......

```

This isn't working. Only the rtl direction is applied to the #page-wrapper regardless of the site's direction/ language. I added the spaceless filter later as I thought it might be an indentation issue but no change still.

I also tried this but not working either:

```
{% if html_attributes['dir'] %}
  <div id="page-wrapper" dir="ltr">
{% else %}
  <div id="page-wrapper" dir="rtl">
{% endif %}

```

Thank you for any views. And sure, I did **drush cr** after each twig edit.

# Answer
> 5 votes
The variable `html_attributes` is not available in a page template. To make it available copy this code from template\_preprocess\_html() to your page preprocess hook:

```
use Drupal\Core\Template\Attribute;

/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {

  $variables['html_attributes'] = new Attribute();
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();
  $variables['html_attributes']['lang'] = $language_interface->getId();
  $variables['html_attributes']['dir'] = $language_interface->getDirection();

}

```

---
Tags: theming, 9
---