# Question
Title: Entity reference field hidden widget or edit disabled on custom form
I have a custom node creation form I am rendering within a views preprocess hook. In that form I have two entity reference fields. I am setting the \[#value\] and \[#default\_value\] of those reference fields programmatically.

On form submit the values I've set are created, but only if the fields are "editable" by the user. I want to make the fields "disabled" and/or "hidden" from the user. Not just hidden with CSS but with the entire autocomplete widget being made inaccessible. The field needs to be type "hidden".

**How can I make an autocomplete entity reference disabled and/or inaccessible to the user creating the content?**

Or another way of putting it, how can I add entity reference values programmatically on form submit without the user being able to interact with the fields?

Here are some things I've tried that do not work:

1. $form\['field\_entity\_reference'\]\['#access'\] = false; // Setting #access to false seems as though it should work because the form fields still exist when debugging $form, but it does not work as it prevents the value from being submitted.
2. Adding \['#attributes'\]\['readonly'\], changing \['#type'\] to hidden or another widget type, adding \['#attributed'\]\['disabled'\]. None work
3. Entity prepopulate \- This does not work for this particular situation as some values cannot be provided by tokens

**Code for reference**

```
function <theme>_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];

  if ($view->id() == '<view>') {
    $field = $variables['field'];

    switch($field->options['id']) {
      case '<view_field>':
        $node = \Drupal::entityTypeManager()
          ->getStorage('node')
          ->create(['type' => '<node_type>']);
        $form = \Drupal::service('entity.form_builder')->getForm($node, 'secondary');

        // Set default_value and value
        $form['field_entity_reference']['widget']['#default_value'] = (int)$cid; // Note this is using the "select list" widget for the entity reference field
        $form['field_entity_reference']['widget']['#value'] = (int)$cid; // Same as above

        // Stuff that doesn't work. Values do not submit unless field is editable by user, or the field is not hidden/disabled
        $form['field_entity_reference']['#access'] = false; // Value does not submit
        $form['field_entity_reference']['widget'][0]['#attributes']['readonly'] = 'readonly'; // Doesn't make field read only
        $form['field_entity_reference']['widget'][0]['value']['#type'] = 'hidden'; // Seems autocomplete widget and select widget do not have a "hidden" type
        $form['field_entity_reference']['widget'][0]['target_id']['#type'] = 'textfield'; // Seems one cannot change the type to textfield

        // Change view field output to the form
        $variables['output'] = $form;
      break;
    }
  }
}

```

# Answer
Kudos to @Patrick Kenny for setting me on a workable path with `hook_entity_presave()`. I'm posting this as an "answer" as it provided a means of accomplishing what I needed, but I still think the D8 entity reference field is missing a "hidden" widget type. Perhaps a port of entityreference\_hidden. If anybody knows how to accomplish that programmatically please share.

**Here’s how I accomplished what I needed.**

1. Create a redundant integer field on the content type to hold value which will be applied to the entity reference field once `hook_entity_presave()` runs.
2. Set the redundant integer field to be available on the form, change the field type to hidden. You can use the field\_hidden module for this.
3. Inside the theme `hook_preprocess_views_view_field()` hook set the value of the redundant field to the target node id (see code in original question to understand what I mean here). Note this is just for my example as I am adding the form to a views row specific field, but could be applied in other hooks.
4. In a custom module, inside `hook_entity_presave()` grab the redundant field value and apply it to the entity reference field before save (see code below)

```
function <module>_entity_presave($entity) {
  if ($entity->getEntityType()->id() == 'node') {
    if ($entity->bundle() == ‘<content_type>’) {
      // ----- Get entity id
      $eid = $entity->redundant_field_name->value;

      // ----- Set entity field target_value
      $entity->normal_entity_reference_field>target_id = $eid;
    }
  }
}

```

**A side note about hooks within the `<theme>.theme` file**

The `hook_form_alter()` hook when within the `<theme>.theme` file do not always apply in the way/order in which one might hope.

***For example*** applying `[#ajax]` to a form action does not make that form ajax capable unless the hook is within a module (theme file hooks will not work). It appears this is because the application of necessary form configuration happens before theme hooks are run.
> 0 votes

---
Tags: hooks, 9
---


# Question
Title: Custom Entity "changed" field is unknown
I'm having a problem I really don't know how to solve, and need your knowledge. I have a custom entity that someone created, and forgot to add the "changed" field. So the objective is to add this field, and updated all entities to set the "changed" field to be equal to the "created" field.

Somehow even if I've updated the entity inserting this changed field, the database shows it, and when dumping the entity this field exists, somehow when I try to set a value to it, it does show an error:

I'll show what I've done to insert this field.

**Inside the .module**

```
function module_update_9012()
{
  $changed = \Drupal\Core\Field\BaseFieldDefinition::create('changed')
  ->setLabel(t('Changed'))
  ->setDescription(t('The time that the entity was last edited.'));

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('changed', 'trialmachine_evaluation', 'trialmachine_evaluation', $changed);
}

```

**Inside the Evaluation entity**

```
use EntityChangedTrait;
public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
{
     $fields = parent::baseFieldDefinitions($entity_type);
     //There are other fields, but they are not needed for this example.
     $fields['changed'] = BaseFieldDefinition::create('changed')
        ->setLabel(t('Changed'))
        ->setDescription(t('The time that the entity was last edited.'));
     return $fields;
}

```

I've also extended the ContentEntityBase and implemented the EvaluationInterface. While in the EvaluationInterface I've extended the ContentEntityInterface and EntityChangedInterface.

I added the changed to entity\_keys on the annotations, and run drush cr to rebuild the cache, and everything.

Then, I'm trying to simply update the field programmatically using a route with a controller to test it. This is what I did:

```
$evaluations = \Drupal::entityTypeManager()->getStorage('trialmachine_evaluation')->loadMultiple();

if (!empty($evaluations)) {
   foreach ($evaluations as $item) {
      if (empty($item->changed->value)) {
         //$item->set('changed', $item->created->value);
         //$item->changed->value = $item->created->value;
         //$item->changed = $item->created->value;
         $item->setChangedTime($item->created->value);
         $item->save();
      }
   }
}

```

In this example there are commented lines to show what I've tried to do, but in any of these atempts the same error appeared.

**Dump of the entity object. The data are '---' for privacy reasons, there are right data types in there.**

```
object(Drupal\trialmachine_evaluation\Entity\Evaluation)[967]
  protected 'values' =>
    array (size=7)
      'id' =>
        array (size=1)
          'x-default' => string '---' (length=1)
      'user_id' =>
        array (size=1)
          'x-default' => string '---' (length=1)
      'campaign_id' =>
        array (size=1)
          'x-default' => string '---' (length=1)
      'order_id' =>
        array (size=1)
          'x-default' => string '---' (length=1)
      'answers' =>
        array (size=1)
          'x-default' => string '---' (length=66)
      'created_at' =>
        array (size=1)
          'x-default' => string '---' (length=19)
      'changed' =>
        array (size=1)
          'x-default' => null
  protected 'fields' =>
    array (size=0)
      empty
  protected 'fieldDefinitions' =>
    array (size=6)
      'id' =>
        object(Drupal\Core\Field\BaseFieldDefinition)[971]
          protected 'type' => string 'integer' (length=7)
          protected 'propertyDefinitions' => null
          protected 'schema' => null
          protected 'indexes' =>
            array (size=0)
              ...
          protected 'itemDefinition' =>
            object(Drupal\Core\Field\TypedData\FieldItemDataDefinition)[972]
              ...
          protected 'definition' =>
            array (size=7)
              ...
          protected 'typedDataManager' => null
      'user_id' =>
        object(Drupal\Core\Field\BaseFieldDefinition)[975]
          protected 'type' => string 'entity_reference' (length=16)
          protected 'propertyDefinitions' => null
          protected 'schema' => null
          protected 'indexes' =>
            array (size=0)
              ...
          protected 'itemDefinition' =>
            object(Drupal\Core\Field\TypedData\FieldItemDataDefinition)[976]
              ...
          protected 'definition' =>
            array (size=8)
              ...
          protected 'typedDataManager' => null
      'campaign_id' =>
        object(Drupal\Core\Field\BaseFieldDefinition)[979]
          protected 'type' => string 'entity_reference' (length=16)
          protected 'propertyDefinitions' => null
          protected 'schema' => null
          protected 'indexes' =>
            array (size=0)
              ...
          protected 'itemDefinition' =>
            object(Drupal\Core\Field\TypedData\FieldItemDataDefinition)[980]
              ...
          protected 'definition' =>
            array (size=7)
              ...
          protected 'typedDataManager' => null
      'order_id' =>
        object(Drupal\Core\Field\BaseFieldDefinition)[983]
          protected 'type' => string 'entity_reference' (length=16)
          protected 'propertyDefinitions' => null
          protected 'schema' => null
          protected 'indexes' =>
            array (size=0)
              ...
          protected 'itemDefinition' =>
            object(Drupal\Core\Field\TypedData\FieldItemDataDefinition)[984]
              ...
          protected 'definition' =>
            array (size=7)
              ...
          protected 'typedDataManager' => null
      'answers' =>
        object(Drupal\Core\Field\BaseFieldDefinition)[987]
          protected 'type' => string 'string' (length=6)
          protected 'propertyDefinitions' => null
          protected 'schema' => null
          protected 'indexes' =>
            array (size=0)
              ...
          protected 'itemDefinition' =>
            object(Drupal\Core\Field\TypedData\FieldItemDataDefinition)[988]
              ...
          protected 'definition' =>
            array (size=6)
              ...
          protected 'typedDataManager' => null
      'created_at' =>
        object(Drupal\Core\Field\BaseFieldDefinition)[990]
          protected 'type' => string 'datetime' (length=8)
          protected 'propertyDefinitions' => null
          protected 'schema' => null
          protected 'indexes' =>
            array (size=0)
              ...
          protected 'itemDefinition' =>
            object(Drupal\Core\Field\TypedData\FieldItemDataDefinition)[991]
              ...
          protected 'definition' =>
            array (size=7)
              ...
          protected 'typedDataManager' => null
  protected 'languages' => null
  protected 'langcodeKey' => string '' (length=0)
  protected 'defaultLangcodeKey' => string 'default_langcode' (length=16)
  protected 'activeLangcode' => string 'x-default' (length=9)
  protected 'defaultLangcode' => string 'und' (length=3)
  protected 'translations' =>
    array (size=1)
      'x-default' =>
        array (size=1)
          'status' => int 1
  protected 'translationInitialize' => boolean false
  protected 'newRevision' => boolean false
  protected 'isDefaultRevision' => boolean true
  protected 'entityKeys' =>
    array (size=7)
      'bundle' => string 'trialmachine_evaluation' (length=23)
      'id' => string '---' (length=1)
      'campaign_id' => string '---' (length=1)
      'answers' => string '---' (length=66)
      'user_id' => string '---' (length=1)
      'order_id' => string '---' (length=1)
      'created_at' => string '---' (length=19)
  protected 'translatableEntityKeys' =>
    array (size=0)
      empty
  protected 'validated' => boolean false
  protected 'validationRequired' => boolean false
  protected 'loadedRevisionId' => null
  protected 'revisionTranslationAffectedKey' => string 'revision_translation_affected' (length=29)
  protected 'enforceRevisionTranslationAffected' =>
    array (size=0)
      empty
  protected 'entityTypeId' => string 'trialmachine_evaluation' (length=23)
  protected 'enforceIsNew' => null
  protected 'typedData' => null
  protected 'cacheContexts' =>
    array (size=0)
      empty
  protected 'cacheTags' =>
    array (size=0)
      empty
  protected 'cacheMaxAge' => int -1
  protected '_serviceIds' =>
    array (size=0)
      empty
  protected '_entityStorages' =>
    array (size=0)
      empty
  protected 'isSyncing' => boolean false

```

**Thanks for reading.**

# Answer
When putting all the elements together, your code seems absolutely correct (I ran a few entity update tests and the update code doesn't need anything else).

Yet, when looking at the dump of your entity, I can see that there is no "fieldDefinitions" for the "changed" field. My best guess is that something went wrong when updating the entity schema.

Can you please elaborate on how you performed the update, please? When going to `/admin/reports/status`, do you see any Entity-related error?

Also, just to make sure:

* is your Entity id "trialmachine\_evaluation"? The namespace being Drupal\trialmachine\_evaluation\Entity\Evaluation, I just wonder if the entity id is different.
* you mentioned that the hook\_update\_N() is in .module file. I don't think it prevents the update script from running it, but it should be in a .install file.
> 1 votes

---
Tags: entities, 9
---


title: Day and month name translation

text:
# Question
Title: Day and month name translation
I am new to Drupal world and **creating a site in Urdu language in Drupal 8**. I have enabled its multilingual support and set default language to Urdu (in fact, this is the only language of the site).

I have created a content type and **enabled to show `Display author and date information`**. I have also added some contents for this content type. When I go to view some content, its **author and date information is displayed as below**.

`Submitted by mabilalmirza on Fri, 02/09/2018 - 23:33`

I know I can translate the string using translation interface but **I want the day name to be shown in Urdu**. I want to translate month names as well for long date format.

Can anyone guide me to accomplish this?

# Answer
> 1 votes
You can translate Interface strings through Configuration \> Regional and language \> **User interface translation** (`/admin/config/regional/translate`).

Enter "`Submitted by`" into the "String contains" search field. It's important to enter correct capitalization of letters or your string won't be found (don't enter "submitted by").

Your search will find this string to translate:

`Submitted by @author_name on @date`

As you can see you can translate part of the message that doesn't contain tokens for data (you need to copy `@author_name` and `@date` into your translation so the text makes sense, don't translate "author\_name" or "date", leave them in English as they are!).

Dates are special formats in Drupal, with special translation options.

You can translate Date formats by going to Configuration \> Regional and language \> Date and time formats (`/admin/config/regional/date-time`).

The one being used for "Submitted by" text is "Default medium date". Choose **Translate** in the drop-down next to Edit button.

Here you only configure how dates are usually structured in your language (maybe something like `D, d/m/Y - H:i` in your case for the Default medium format, to have the day before the month).

Month and Day name translations will probably already be available from Drupal Localization project, but if you see they aren't translated you can translate them yourself through the User interface translation page.

If you don't see some of the options mentioned here, make sure you have enabled all translation modules, including "Configuration translation".

# Answer
> 0 votes
To translate month labels (in Drupal 9 at least) search for the next string on `/admin/config/regional/translate` page:

`January: January February: February March: March April: April May: May June: June July: July August: August September: September October: October November: November December: December`

and translate it like `English_January_month_name: translated_month_name ...`

---
Tags: 8
---


# Question
Title: Get raw SQL query from Drupal::entityTypeManager
How can I fetch the raw sql version of the following statement?

```
             $t = \Drupal::entityTypeManager()
              ->getStorage('taxonomy_term')
              ->loadByProperties(['name' => $s, 'vid' => $v]);

```

Couldn't find anything suitable to try with EntityTypeManager. TIA.

# Answer
> 5 votes
Glad this question was re-opened, converting my comment to an answer:

If you write it as an entity query then you can cast it to a string, like this:

```
$t = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->getQuery()
  ->condition('vid', 'test')
  ->condition('name', 'test');
var_export((string) $t)

```

---
Tags: 8, database
---


# Question
Title: template_preprocess_HOOK: what do I put for HOOK?
My objective: get and change the breadcrumb within a custom module.

So it's possible that template\_preprocess\_HOOK is not even the best tool to be using for this, please mention that.

My question, though, is what HOOK to use? Should it be called template\_preprocess\_mymodule or template\_preprocess\_mytheme?

# Answer
> 4 votes
The HOOK corresponds to the theme function or template you are preprocessing.

If you wanted to alter `page.tpl.php`, you would use `function MYTHEME_preprocess_page(&$variables)`.

If you wanted to alter `theme_item_list()`, you would use `function MYTHEME_preprocess_item_list(&$variables)`.

A note, any dashes should be converted to underscores.

So `views-view.tpl.php` would be altered by `function MYTHEME_preprocess_views_view(&$variables)`.

# Answer
> 0 votes
Assuming your template file for breadcrumb menu is `my-breadcrumb.html.twig`. So you can override variables in this template by defining `template_preprocess_my_breadcrumb(&$variables)` in a module.

Or you can also use `MYTHEME_preprocess_my_breadcrumb(&$variables)` in your `YOUTHEME.theme`

---
Tags: theming
---


# Question
Title: How to delete a webform submission in a custom module?
I want to delete a webform submission from a custom module that I've written. I'm using `webform_submission_delete(123, 76)`. The error I receive is:

> Notice: Trying to get property of non-object in webform\_submission\_delete() (line 141 of /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc). Warning: Invalid argument supplied for foreach() in webform\_submission\_delete() (line 141 of /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc). Notice: Trying to get property of non-object in webform\_submission\_delete() (line 153 of /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc). Notice: Trying to get property of non-object in webform\_submission\_delete() (line 157 of /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc).

I'm a bit new to module development. Am I missing something?

# Answer
If you are calling this webform\_submission\_delete() function, then both the first and second parameters must be objects. At least the first parameter is a node object. Most likely you are calling this using:

```
$nid = 12345;
webform_submission_delete($nid, $sid);

```

instead of doing

```
$node = node_load(12345);
webform_submission_delete($node, $sid);

```

and as a result causing PHP to complain.

If you have doubts on how to implement webform\_submissions\_delete(), I suggest you take a look at the various functions that implement it for an example.
> 5 votes

# Answer
Or if you would like to just do it via an external module you could also use the Webform\_clear module
> 1 votes

# Answer
This is ancient now, but for future posterity:

As amateur barista suggests, you need to **pass the objects**, not just the ids. For BOTH node and submission.

```
webform_submission_delete($node, $submission)

```
> 1 votes

# Answer
in drupal9 webform provides an option to delete the submission after a certain days

/admin/structure/webform/manage/{my webform name}/settings/submissions
> 0 votes

---
Tags: 7, webforms
---


title: how to check messages exists

text:
# Question
Title: how to check messages exists
I want to check is there any messages in my template in drupal 7 there was a global variable in page template variables messages

now in drupal 8 I want to check is there any message but `messages` variable in `page--front.html.twig` is always empty, alternative way is check region highlightes( because status messages block is in highlighted region) **but below statement always return TRUE**,

```
    {% if page.highlighted %}
      {% block highlighted %}
        <div class="highlighted">{{ page.highlighted }}</div>
      {% endblock %}
    {% endif %}

```

is there any way to check that messages exists in page in drupal 8?

# Answer
While the `page.highlighted` variable contains the block data (`mytheme_messages`) for message display, the block rendering data doesn't contain the messages themselves, so there's no way to check for message existance there.

However, you can inject a custom variable based on the current message queue from `drupal_get_messages()`.

For example, in your **MYTHEME.theme**:

```
/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
function MYTHEME_preprocess_page(array &$variables) {
  // Inject a flag based on the current message queue.
  $variables['available_messages'] = !empty(drupal_get_messages(NULL, FALSE));
}

```

And within your **page.html.twig**:

```
{% if available_messages == true %}
   <!-- TODO: Add custom markup when there are messages -->
{% endif %}

```
> 6 votes

# Answer
In Drupal 9, use the Messenger service.

```
function MYTHEME_preprocess_page(array &$variables) {
  $variables['available_messages'] = !empty(\Drupal::messenger()->all());
}

```
> 1 votes

---
Tags: 8, theming, status-messages
---


# Question
Title: Replace E-Mails in Webform 8 when dumping to test stage
We sanititze our dumps from production to test so that no newsletter subscriptions, form submissions or ohter things get into the test environement and bad things happen :D

Is there a simple way to get the E-Mails configured in webforms automatically replaced too?
As the number of forms and drupal sites will grow (100+), its a bit hard to handle with drush or sql.

# Answer
This link covers `drush sql:sanitize`, including how to extend it with your own custom sanitizations: https://www.hashbangcode.com/article/drupal-9-sanitising-data-drush
> 2 votes

---
Tags: webforms, emails, staging
---


# Question
Title: Entity reference auto complete field is missing value on ajax callback
I have an entity reference field on my content type using the autocomplete widget.

I'm adding an ajax callback to that field using this in a form alter:

```
$form['field_er']['widget'][0]['target_id']['#ajax'] = [
  'callback' => '::ajaxCallback',
  'event' => 'autocompleteselect',
  'wrapper' => 'nm-resend-selector',
  'progress' => [
    'type' => 'throbber',
    'message' => t('Updating.'),
  ],
];

```

The ajax call triggers when I select an entity, but in my form alter when I use `$formState->getValue('field_er')` the target\_id is null, when it should be the id of the entity I selected.

How do I get at the selected entity?

Edit: I looked into FormState::input to see if I could get the value from there, but the value there is 'a' which is the text I entered to trigger the autocomplete.

# Answer
> 1 votes
Looks like I was just using the wrong event, switching the event to 'autocompleteclose' gets me the value I need.

---
Tags: entities, ajax, 9
---


# Question
Title: Webform block shows for anonymous user but not authenticated
I am using the webforms module (6.1.1) on a Drupal 8 site for a form that shows up in a block on my front page.

If I **am not** logged in (go Incognito or InPrivate mode) the form displays and works.

If I **am** logged in, the form *does not show*, but the \< div\> it is located in does.

It works in the admin pages as expected.

I have verified that the Webform's Access has Roles "Anonymous user", "Authenticated user" and "Administrator" checked.

I have verified the Block also has Roles "Anonymous user", "Authenticated user" and "Administrator" checked.

Looking in the browser's developer view at the space where the form should be, I get the following code instead. I don't know if it is relevant or not.

```
<span data-big-pipe-placeholder-id="callback=Drupal%5Cblock%5CBlockViewBuilder%3A%3AlazyBuilder&args%5B0%5D=webform&args%5B1%5D=full&args%5B2%5D&token=DAFi9sg2c3cBjy5LxuoGFFwM6MALQtu8KIca_a1b5E8"></span>

```

This is opposite than most web hits that talk about the form not showing up for anonymous users.

Thank you.

# Answer
> 1 votes
This is not a webform issue. The problem is that BigPipe is unable to lazily load the block. What happens if you disable this module?

If you want to debug the module, server-side it is delivering the content for placeholders delayed at the end of the page (scroll down in the HTML source). Client-side this is then processed in javascript. Check if javascript is running without errors.

You can also try to change the theme, that's the most likely cause for such errors by not rendering the HTML markup and the attached libraries correctly.

---
Tags: 8, blocks, webforms
---


# Question
Title: How to add page restrictions for blocks in drupal?
I'm using the drupal administrator menu for the settings there i have a page called /desert/234234 the block should appear only when the url is /desert/(desert\_id) how can i restrict that

# Answer
In Drupal 7 you can use PHP code in the block's "Visibility settings."

### Steps

* Go to admin/modules and enable the PHP filter module
* Go to admin/structure/block and click on "Configure"

+ Enter the following PHP code (including `<?php` and `?>`) in the *Page* settings.
> 3 votes

# Answer
on visibility settings, choose two mode of visibility, for example:

* type of content, choose one content type you want your block to show on
* on page visibility, you choose hide for listed page, the type /desert/\*/\*
> 1 votes

# Answer
Make a block appear only when URL is something: On the configuration page of the block go to Visibility settings -\> Pages -\> Show block on specific pages, and select "Only the listed pages." Wildcards may be used if needed; for example, desert/\* would match any path starting with desert/.
> 0 votes

# Answer
Drupal 7: 1. Go to: /admin/structure/block 2. Click configure 3. In Visibility settings set "Only the listed pages" and in textarea below insert " /desert/\* .

Also remember to activate block - put it in one of regions of the page.
> 0 votes

---
Tags: blocks
---


# Question
Title: How do I programmatically get the URL of an entity referenced media image field using on a custom_preprocess_html() hook on THEME.theme?
**Reason:** I need to create an Open graph meta tag og:image and pass the URL as content.

On THEME\_preprocess\_html(), I loaded the node using

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
      $nid = $node->id();
      if($node->hasField('field_image')){
        $image_id = $node->field_image->target_id;
        $image = \Drupal::entityTypeManager()->getStorage('file')->load($image_id);
      }
}

```

I have loaded the node and I was able to get the field\_image\_entity\_id as shown. I want to get the URL of the image field of entity referenced field.

The below code gives me NULL. How can I load the media entity and get this value?

```
$image = \Drupal::entityTypeManager()->getStorage('file')->load($entity_img_id);

```

# Answer
> 2 votes
ok, here is what worked for me. After digging through stack overflow, found that I was missing the ImageStyle and this resulted in not rendering the url.

I added

```
use Drupal\media\Entity\Media;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\MediaInterface;
use Drupal\node\Entity\Node;

```

and then on preprocess function, I loaded the media using the target\_id that I got form the $node-\>field\_image-\>target\_id;

Then, I loaded the ImageStyle using

```
$media = Media::load($image_id);
$media_url = ImageStyle::load('TYPE_OF_CROP')->buildUrl($media->image->entity->getFileUri());
$variables['media_url'] =  $media_url;

```

Hopefully this helps people.

# Answer
> 2 votes
`file_create_url` has been deprecated. Use `\Drupal::service('file_url_generator')` instead.

```
$image_uri = $node->field_my_media->entity->field_media_image->entity->getFileUri();

$image_url = \Drupal::service('file_url_generator')->generateAbsoluteString($image_uri);

```

# Answer
> 1 votes
Just tested the following code and was able to get the image URL from `field_image` of the current node.

```
function THEMENAME_preprocess_html(&$variables) {
  //get the current node
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if($node->hasField('field_image')){
      $image_url = file_create_url($node->field_image->entity->getFileUri());
    }
  }
}

```

# Answer
> 0 votes
In more recent version of Drupal 8, you can use:

```

$image_field = $node->get('field_image');
if ($image_field->isEmpty())
  return;
$media_entity = $image_field->referencedEntities()[0];
$uri = $media_entity->get('field_media_image')->entity->uri->value;
$variables['image_url'] = file_create_url($uri);

```

---
Tags: 8, media
---


# Question
Title: What is the twig template name for a node edit form?
In Drupal 8, what is the twig template name for a node edit form for a **custom content type** called for example "device".

* For a default node we use node-edit-form.html.twig
* So what is the edit template name for a custom content type ?

I would appreciate your help. Thank you !

# Answer
You could have a look at this comment. It suggests adding a theme suggestion like this:

> This feels hacky, but it's the best I can come up with. First add this code to your admin .theme file (likely a sub-theme of Seven):
>
> ```
> function NAMEOFTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
>    if ($hook == 'node_edit_form') {
>      if ($node = \Drupal::routeMatch()->getParameter('node')) {
>       $content_type = $node->bundle();
>      }
>      else {
>        $current_path = \Drupal::service('path.current')->getPath();
>        $path_args = explode('/', $current_path);
>        $content_type = $path_args[3];
>      }
>      $suggestions[] = 'node_edit_form__' . $content_type;
>    }
>  }
>
> ```
>
> Next, create twig templates in your theme's template directory in the form of **node-edit-form--NODE-TYPE-SEPARATED-WITH-DASHES.html.twig**.
> 6 votes

# Answer
Based on Neograph734's answer and Berdir his comment on it, the node type is indeed already available (no need get it out of the path). I would recommend to add the theme suggestion using:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for node_edit_form.
 */
function example_theme_suggestions_node_edit_form_alter(array &$suggestions, array $variables) {
  $route_match = \Drupal::routeMatch();

  if ($node = $route_match->getParameter('node')) {
    // When editing an existing node, add the node's bundle as the theme hook
    // suggestion.
    $suggestions[] = $variables['theme_hook_original'] . '__' . $node->bundle();
  } elseif ($node_type = $route_match->getParameter('node_type')) {
    // When a new node is created, the node type (object) is provided.
    $suggestions[] = $variables['theme_hook_original'] . '__' . $node_type->id();
  }

  return $suggestions;
}

```

This allows you to write targeted Twig templates and/or pre-process functions. When your node type's machine name is *device*, your Twig template should be named `node-edit-form--device.html.twig` and your pre-process function `example_preprocess_node_edit_form__device(&$variables)`, where example is the name of your theme (or module).
> 2 votes

# Answer
Here are the complete steps it took me to implement on D9.2.10

1. Create subtheme of admin theme seven
2. Install and enable new admin theme (note: enable through drop down)
3. create hook\_theme\_suggestions\_HOOK\_alter in new admin \*.theme

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for node_edit_form.
 */
function NAMEOFTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
   if ($hook == 'node_edit_form') {
     if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $content_type = $node->bundle();
     }
     else {
       $current_path = \Drupal::service('path.current')->getPath();
       $path_args = explode('/', $current_path);
       $content_type = $path_args[3];
     }
     $suggestions[] = 'node_edit_form__' . $content_type;
   }
 }

```
4. Copy seven's `node-edit-form.html.twig` to new subtheme's templates directory.
5. Create a node bundle specific override `node-edit-form--BUNDLE-NAME.html.twig`
6. Clear caches

Note: I did not need to override the theme for the form in a hook\_form\_alter for it to pick up node\_edit\_form.
> 0 votes

# Answer
If you want to theme a specific form, for example the edit form of a node type, then all you have to do is

```
/**
 * Implements hook_theme().
 */
function THEMENAME_theme($existing, $type, $theme, $path) {
  return [
    // form id (weather it's an edit node for or a new node form)
    'node_NODE_CONTENT_TYPE_edit_form' => [
      'render element' => 'form',
    ],
  ];
}

```

Then create a twig file node-NODE-CONTENT-TYPE-edit-form.html.twig

and theme it like so:

```
{{ form.field_MACHINE_NAME_OF_FIELD }}
{{ form.field_MACHINE_NAME_OF_FIELD2 }}
...
{# this prints out the submit button #}
{{ form.actions }}
{# you need to have this for the form to work properly #}
{{ form|without('name', 'field_MACHINE_NAME_OF_FIELD2', 'field_MACHINE_NAME_OF_FIELD3') }}

```
> -1 votes

---
Tags: theming, 8, forms
---


# Question
Title: Create address element for webform to output country code
I'd like to create a field using `webform` that accepts a country but outputs the country code.

I'm guessing one path forward is to find the handler used by contrib and extend it? Or is that functionality already in the plugin and hiding in plain sight?

# Answer
> 1 votes
Pretty simple - for Basic address, click edit, then uncheck everything but "country" and select `Country codes`

---
Tags: 8, webforms
---


title: How to remove a spurious entity update?

text:
# Question
Title: How to remove a spurious entity update?
Something (I'm not sure what) has introduced what appears to be a spurious entity update into my Drupal 9 site. I'd like to delete the update so that I'm no longer prompted to apply it.

```
> drush dentup
user entity type :
The User ID field needs to be updated.

 Do you wish to run all pending updates? (yes/no) [yes]:
 > yes

In SqlContentEntityStorageSchema.php line 1842:

  The SQL storage cannot change the schema for an existing field (uid in user
   entity) with data.

```

When I remove all user data and reattempt the update:

```
> drush dentup
user entity type :
The User ID field needs to be updated.

 Do you wish to run all pending updates? (yes/no) [yes]:
 > yes

In ExceptionHandler.php line 50:

  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY':
  ALTER TABLE "users" ADD `uid` INT unsigned NOT NULL, ADD PRIMARY KEY (`uid`); Array()

In StatementWrapper.php line 116:

  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'

```

The `users` table already has a `uid` column which is its primary key and this entity update will always fail.

Where are entity updates stored? Is there a way to safely remove this update from its storage location?

# Answer
> 4 votes
This seems very odd, how did the entity schema for the uid field get changed?

So you are saying the user database tables are the same as in any other Drupal install?

What is then with the installed storage schemas, for the tables

```
\Drupal::keyValue('entity.storage_schema.sql')->get('user.entity_schema_data')

```

and the field?

```
\Drupal::keyValue('entity.storage_schema.sql')->get('user.field_schema_data.uid')

```

If this is the only thing wrong you could set the correct data:

```
\Drupal::keyValue('entity.storage_schema.sql')->set('user.entity_schema_data', $data)

```

Drupal keeps track of installed versus in code defined entity definitions. So whatever the unknown code has done, there could be more damage.

---
Tags: entities
---


# Question
Title: Custom form adding a commerce price field
I am creating a custom form using the form api. I'd like to reuse the price field used by commerce, but I don't know how to include their form type in my own form.

# Answer
> 1 votes
this works for me

```
$form['price'] = array(
  '#type' => 'commerce_price',
  '#title' => $this->t('Price'),
);

```

---
Tags: 7, forms, commerce
---


# Question
Title: How to setup access dependency on a block content created programatically
In Drupal 8, I am creating block instances (BlockContent) for node layouts programatically and setting them all as non-reusable. That causes a following access error: "Non-reusable blocks must set an access dependency".

How do I set access dependency on an existing block instance (or during it's creation)? Was never in a position to have to manipulate access from such angle and I can't find a good example for this.

# Answer
> 0 votes
The BlockContent class uses the RefinableDependentAccessTrait which has 2 methods that can be used to add/set access dependencies:

---
Tags: 8, blocks, layout-builder
---


# Question
Title: How can I display the current Search API filters to the user?
Using Search API and Facets on Drupal 9. If a user selects some filters (facets, text), how can we display the current search criteria to the user?

For example, similar to a breadcrumb list shows all of the current filters.

I seem to remember seeing this option before but cannot seem to find it now.

# Answer
The experimental sub-module for the Facets module call "Facets Summary" provides this functionality.
> 0 votes

---
Tags: search
---


# Question
Title: Only show the cart block if it contains items
How can I set a Drupal Commerce shopping cart block to only display if it contains items? I'd like to hide the cart block when the cart is empty.

# Answer
Here is the solution. Add these lines in template.php file of a theme you\`re using. Change THEMENAME on the name of your theme.

```
function THEMENAME_commerce_cart_empty_block() {
  return '';
}

```
> 5 votes

# Answer
For drupal8+ and commerce 2 the answer is

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'commerce_cart') {
    if ($variables['content']['#count'] == 0) {
      $variables['attributes']['class'][] = 'visually-hidden';
    }
  }
}

```
> 2 votes

# Answer
The solution that worked for me is not just hiding this "your shopping cart is empty" but also hiding all possible long list of items. And you can accomplish this using views:

* create two fields of text links, one for view cart and another for checkout.
* Add another field to display the total amount. Look for "add commerce order: order total" I got this idea from this
* Filter criteria: commerce order to \>=1. This will make block disappear when the order is greater than 1.
* Apply some css.
> 1 votes

---
Tags: commerce
---


# Question
Title: How do I display nodes in a map block and in the page content, with shared filters?
I am using the Olivero theme on my Drupal 9 site and building a map with the Geolocation module.

I want to create a Views to display these two displays of the same nodes :

* one display which is a map (displayed in the "hero" region)
* another display (e.g. a list of teasers) which is displayed in the "content" region.

I want them both displayed on the same page and have them share the same filters. If I filter the map, it must filter the nodes.

If I create a Views page with an "Attachment", the map is attached before or after the content. I want to display the map in one region and the content in another region.

How do I display the map in a block and the nodes in a page, with shared filters?

**EDIT :**

I tested with a page and a block in the same Views. But that doesn't work, it only filters the page, not the map :

Here is the configuration of the Views page :

The block is identical, I simply customized the "Format" and the "Pagination" :

I don't know how I can filter the page and the block at the same time. How clarified in my question, the block must be in the "Hero" region of the "Olivero" theme.

I know it's possible to do this with an "Attached File", but I want the map to be in a specific region of the theme.

I found the module below, but it no longer exists :

https://www.drupal.org/project/views\_attachment\_block

# Answer
OK, according to your edits, here is a working solution :

* Under the page display of your Views, edit the exposed filter and copy its id (Filter identifier field). You can set it to a different value if you wish too (e.g. "my\_filter\_id").
* Now, edit your block display. Remove the "Content Type" filter criterion and add a "Content: Content type" Contextual filter instead.
* Choose "Provide default value" option and "Query parameter" type. Fill the "Query parameter" textfield with the id of your filter ("my\_filter\_id").
* Under the "When the filter value is available or a default is provided" section, click on "Specify validation criteria", validator "Content type", action to take if filter value does not validate "Display all results for the specified field"
* Make sure that none of your display uses the "Use AJAX" option and save the Views.

Now, when the page reloads to filter the page display, the query parameter is going to be used by the block display to filter its results as well.

Biggest fallback is that this solution does not work with AJAX, though. :-(
> 0 votes

---
Tags: views, nodes, 9
---


# Question
Title: what json structure does simple oauth expect?
Drupal 8. I'm new with simple Oauth. I had manage to do this:

But I want to do it with the Raw format, cuz my frontend is in Angular, so I will send a Json to Drupal.

This is my first try:

```
{
    "grant_type":"password",
    "client_id":"f011cc58-40ce-43a9-8f71-842494e3a997",
    "client_secret":"abc123",
    "username":"test",
    "password":"test"
}

```

And this is the response:

> { "error": "invalid\_grant", "message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.", "hint": "Check the configuration to see if the grant is enabled." }

I have set up the Content-type: Application/json but I got the same result.

Any idea??

# Answer
It will depend if the backend can receive a JSON format.

In my case, I am working with the Drupal 8 Module simple Oauth. and the The format for OAuth 2.0 Bearer tokens is actually described in a separate spec, RFC 6750.

More concrete here

> The entity-body follows the encoding requirements of the "application/x-www-form-urlencoded" content-type as defined by HTML 4.01 \[W3C.REC-html401-19991224\].

So, In my particular case, I will try to send a form-data from angular.
> 0 votes

# Answer
You need to stringify your data. To do this install npm package qs, then create object

```
const data = {
    "grant_type":"password",
    "client_id":"f011cc58-40ce-43a9-8f71-842494e3a997",
    "client_secret":"abc123",
    "username":"test",
    "password":"test"
}

```

And use in request

```
axios.post('oauth/token', qs.stringify(data))

```
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Run an update hook after specific configuration has been imported?
I am introducing new configuration to an entity in Drupal that adds a few new boolean fields. The problem is, even though I set the default value as TRUE in the UI, this is only for new entities. Existing entities will have no value, or false, when evaluated in code.

I would like to script a change in that will default all existing entities to TRUE when the configuration is introduced for backwards compatibility, and only run it that one time.

Typical deployment scripts advise running updb first before cim with Drush. This creates a conflict when trying to attempt this.

Pantheon deployment script example:

```
if (isset($_ENV['PANTHEON_ENVIRONMENT'])) {
  $status = 0;
  $config_directory = dirname(__FILE__) . '/config/default';

  passthru("drush updb --yes", $status);
  passthru("drush cim --yes", $status);
  passthru("drush cim --yes", $status);
  passthru("drush cim --yes", $status);
  passthru("drush updb --yes", $status);
  passthru("drush cr", $status);

  if ($status == 0) {
    echo('Configuration imported and database updated.' . "\n");
  } else {
    echo('Configuration not imported / database not updated. Drush command returned an error.' . "\n");
  }
}

```

Is there a better way to do changes like this that only run once without causing script like the one above to fail?

# Answer
> 3 votes
You can use drush deploy, which performs updates in this order:

1. Update hooks from module.install
2. cim
3. cr
4. Deploy hooks from module.deploy.php

So converting your update hook to a deploy hook means it will run after the config import.

---
Tags: 9
---


# Question
Title: How to solve this error "Class \Drupal\simple_sitemap\Controller\SimpleSitemapController does not exist"
I got this error which is kind of surprising to me since I don't have it on my local environment. What I did is that I compressed the project directory and uploaded it to my cpanel file manager and then extract it. I then imported the sql file to phpmyadmin and made the credential match the ones on my production server.

When I open my site, it was working on the front page and other pages created with the Content type Basic pages. However, when I navigate to /user/login, this error appears. It also appeared on webform pages.

> The website encountered an unexpected error. Please try again later. Error: Class 'Drupal\simple\_sitemap\Queue\SimpleSitemapQueue' not found in Drupal\Component\DependencyInjection\Container-\>createService() (line 262 of core/lib/Drupal/Component/DependencyInjection/Container.php). Drupal\Component\DependencyInjection\Container-\>createService(Array, 'simple\_sitemap.queue') (Line: 176) Drupal\Component\DependencyInjection\Container-\>get('simple\_sitemap.queue', 1) (Line: 437) Drupal\Component\DependencyInjection\Container-\>resolveServicesAndParameters(Array) (Line: 240) Drupal\Component\DependencyInjection\Container-\>createService(Array, 'simple\_sitemap.queue\_worker') (Line: 176) Drupal\Component\DependencyInjection\Container-\>get('simple\_sitemap.queue\_worker', 1) (Line: 437) Drupal\Component\DependencyInjection\Container-\>resolveServicesAndParameters(Array) (Line: 240) Drupal\Component\DependencyInjection\Container-\>createService(Array, 'simple\_sitemap.generator') (Line: 176) Drupal\Component\DependencyInjection\Container-\>get('simple\_sitemap.generator', 1) (Line: 437) Drupal\Component\DependencyInjection\Container-\>resolveServicesAndParameters(Array) (Line: 240) Drupal\Component\DependencyInjection\Container-\>createService(Array, 'simple\_sitemap.form\_helper') (Line: 176) Drupal\Component\DependencyInjection\Container-\>get('simple\_sitemap.form\_helper') (Line: 198) Drupal::service('simple\_sitemap.form\_helper') (Line: 43) simple\_sitemap\_form\_alter(Array, Object, 'webform\_submission\_contact\_node\_25\_add\_form') (Line: 539) Drupal\Core\Extension\ModuleHandler-\>alter('form', Array, Object, 'webform\_submission\_contact\_node\_25\_add\_form') (Line: 836) Drupal\Core\Form\FormBuilder-\>prepareForm('webform\_submission\_contact\_node\_25\_add\_form', Array, Object) (Line: 279) Drupal\Core\Form\FormBuilder-\>buildForm(Object, Object) (Line: 48) Drupal\Core\Entity\EntityFormBuilder-\>getForm(Object, 'add') (Line: 1230) Drupal\webform\Entity\Webform-\>getSubmissionForm() (Line: 18) Drupal\webform\WebformEntityViewBuilder-\>view(Object, 'default') (Line: 165) Drupal\entity\_block\Plugin\Block\EntityBlock-\>build() (Line: 105) Drupal\layout\_builder\EventSubscriber\BlockComponentRenderArray-\>onBuildRender(Object, 'section\_component.build.render\_array', Object) call\_user\_func(Array, Object, 'section\_component.build.render\_array', Object) (Line: 142) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch(Object, 'section\_component.build.render\_array') (Line: 90) Drupal\layout\_builder\SectionComponent-\>toRenderArray(Array, ) (Line: 86) Drupal\layout\_builder\Section-\>toRenderArray(Array) (Line: 317) Drupal\layout\_builder\Entity\LayoutBuilderEntityViewDisplay-\>buildSections(Object) (Line: 276) Drupal\layout\_builder\Entity\LayoutBuilderEntityViewDisplay-\>buildMultiple(Array) (Line: 340) Drupal\Core\Entity\EntityViewBuilder-\>buildComponents(Array, Array, Array, 'full') (Line: 24) Drupal\node\NodeViewBuilder-\>buildComponents(Array, Array, Array, 'full') (Line: 282) Drupal\Core\Entity\EntityViewBuilder-\>buildMultiple(Array) (Line: 239) Drupal\Core\Entity\EntityViewBuilder-\>build(Array) call\_user\_func\_array(Array, Array) (Line: 101) Drupal\Core\Render\Renderer-\>doTrustedCallback(Array, Array, 'Render #pre\_render callbacks must be methods of a class that implements \Drupal\Core\Security\TrustedCallbackInterface or be an anonymous function. The callback was %s. See https://www.drupal.org/node/2966725', 'exception', 'Drupal\Core\Render\Element\RenderCallbackInterface') (Line: 786) Drupal\Core\Render\Renderer-\>doCallback('#pre\_render', Array, Array) (Line: 377) Drupal\Core\Render\Renderer-\>doRender(Array, ) (Line: 201) Drupal\Core\Render\Renderer-\>render(Array, ) (Line: 241) Drupal\Core\Render\MainContent\HtmlRenderer-\>Drupal\Core\Render\MainContent{closure}() (Line: 578) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 242) Drupal\Core\Render\MainContent\HtmlRenderer-\>prepare(Array, Object, Object) (Line: 132) Drupal\Core\Render\MainContent\HtmlRenderer-\>renderResponse(Array, Object, Object) (Line: 90) Drupal\Core\EventSubscriber\MainContentViewSubscriber-\>onViewRenderArray(Object, 'kernel.view', Object) call\_user\_func(Array, Object, 'kernel.view', Object) (Line: 142) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch(Object, 'kernel.view') (Line: 163) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 80) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 191) Drupal\page\_cache\StackMiddleware\PageCache-\>fetch(Object, 1, 1) (Line: 128) Drupal\page\_cache\StackMiddleware\PageCache-\>lookup(Object, 1, 1) (Line: 82) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 52) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 717) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

I searched and found some articles which says that clearing cache will solve the issue. I cannot login to the interface so I ran /core/rebuild.php but it doesn't solve it.

When I ran `drush cr` on the command line, I got this error.

> In EntityResolverManager.php line 128:
> Class \Drupal\simple\_sitemap\Controller\SimpleSitemapController does not exist

On my local environment I used Lando with Varbase, which is based on Drupal 9.

# Answer
Cpanel makes this tough. But it is definitely possible to ask your hosting provider for Secure SHell (SSH) access to the Cpanel server. Once you have that, you can download Drush -- I don't expect you'll have Composer on Cpanel, so skip a step and download the Drush PHAR appropriate to your Drupal version (probably the latest Drush 10 unless you are still on Drupal 7 or lower). Once you have Drush, you'll have many options (to rebuild caches, apply database schema updates, and repair various things) which are not available via the web browser.

Since the error is related to the Simple Sitemap module, you can try:

```
$ drush pm-uninstall simple_sitemap

```

That should get your site to load again. Then export the database from your production site and import it in your local environment to see if you can duplicate the bug.

Often, problems like this are caused by applying database schema updates in your local environment and forgetting to do it again in production. It could also be caused by a code update, even to custom code if it home into this module, but the most likely explanation is that you just need to run `drush updb` on the server.

Also, this sort of error usually means that you are not deploying configuration when you deploy code.

Good luck!
> 0 votes

# Answer
What happened was, we (maintainers of the module) renamed a few class names from *Simplesitemap* to *SimpleSitemap* (CamelCase). Apparently certain case insensitive environments like Windows and in some cases OSX disregard letter case changes.

If you are transferring files through FTP, the solution is to make sure the files arrive with the correct case, by e.g. deleting the old files instead of overwriting them.

If you use git to push changes and you have this problem, ensure your host computer has git's *ignorecase* set to *false*: `git config core.ignorecase false`

There is a support ticket you can read through with a couple of solutions.
> 3 votes

---
Tags: 9, dependency-injection
---


# Question
Title: Simple sitemap news are always in pending state?
To site that is using Simple XML sitemap I installed Simple XML News Sitemap module. Basically I cloned all the setting form existing sitemaps. Also configured article content type to use new site map variant. Problem is that Status page (/admin/config/search/simplesitemap) those new variant for news sitemap type are always in "pending" state. I do have articles with this sitemap variant set, I was rebuilding sitemaps many times, and all other are re-generated well, but new one for news is always in pending state?

What can be the reason for that? Using Simple xml news sitemap 8.x-1.0 and Simple xml sitemap 8.x-3.10

# Answer
> 1 votes
'Pending' in this context means either no items have been queued (yet), or, all items from the queue have been skipped during generation. The latter happens if e.g. anonymous users lack permission to see those items (in your case: article nodes).

So please double-check that there are in fact URLs that are set to be indexed for that variant and that anonymous users can view those URLs.

If that's the case, I suggest opening up a support request in the module's issue queue.

---
Tags: xml-sitemap
---


# Question
Title: "This entity (node: id) cannot be referenced" error
I use Drupal 8 and I have a content type which has a field that references another content type as a entity reference field. I use a rest endpoint to create the node and the referenced node which works fine.

I also have the workbench module installed so I can change the moderation state of the nodes.

The problem is that when I change the moderation state from draft to review I get the error *This entity (node: {ID}) cannot be referenced.*

Why am I getting this?

# Answer
The issue was that the field was used to reference unpublished nodes and kept throwing the error. I updated the field to allow unpublished nodes too. It worked.
> 1 votes

# Answer
The view\_unpublished "module allows you to grant access for **specific** user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard."

```
composer require drupal/view_unpublished
drush en -y view_unpublished

```

At /admin/people/permissions set permissions as required:

Finally, at /en/admin/reports/status/rebuild rebuild the permissions, which may take some time:
> 3 votes

# Answer
We can use this module entity\_reference\_unpublished. Or add "bypass node access" permission.

> !!! This is very powerful permission that you may not want to give to your editors.
> 1 votes

# Answer
Check that the view does not have a filter for 'Content: Published (=Yes)'.

The validator uses an *entity\_reference* view to get a list of valid entity ids. If the entity selected (e.g. from *entity\_browser* view) is not in the list of valid ids, then this error will be displayed.

Ensure that both views have the same criteria.

If you are working in workflow, the default 'Published' may not be the filter criteria that you want.
> 1 votes

# Answer
The views\_unpublished module (from this answer) has an ominous bug for multilingual sites and translations with different published status.

An alternative is to use a patch from 'Move permission "view any unpublished content" from content moderation to core: this is something which is currently targeting Drupal Core 8.5. At the time of writing, I've used this patch in Drupal 8.3.7.
> 0 votes

# Answer
I was getting this when the Manage fields \> Reference Type wasn't set. There are 2 kinds of reference: Reference method and Content type and it is possible to not select anything here - selecting the correct content type solved the issue for me.
> 0 votes

# Answer
I had received the same error during form submission of a content type.

I was using an entity reference field with Ajax that is set to display values of two other taxonomy reference fields in the same content type. The field could only show terms selected in the other two fields.

On form submission I was getting this error. I found that the root cause of the problem was that the ajax field was not set to reference one of the vocabulary in the other field.

I proceeded to edit the field settings and enable the vocabulary in the checkboxes. The error was resolved after that.
> 0 votes

# Answer
Many of the other answers here require installing new modules and making configuration changes. If you're comfortable with adding patches to your site, see the patches at the bottom of this issue: https://www.drupal.org/project/drupal/issues/2845144

In theory this is ready to be committed to Drupal Core as of May 2020. However, my guess is that there will be debates about whether this breaks backwards compatibility, and ultimately won't be committed until Drupal 10.
> 0 votes

---
Tags: entities, workbench
---


# Question
Title: Should I remove "Commerce Base" from site before an upgrade?
The "Upgrade Status" module reports that "**Commerce Base**" exists in site file structure, but is not installed and suggests removing it. I expect that the Commerce project references those files to work, but I don't know.

**Should this project in my composer/json 'requires' list be removed using Composer?** "drupalcommerce/commerce\_base": "dev-8.x-1.x",

My original Drupal 8 install was with Composer using: `composer create-project drupalcommerce/project-base XXXXXX --stability dev`

I presently have Commerce 8.x-2.26 installed.

I'd like to upgrade to from Drupal 8.9.x to 9.2.x.

Thank you for any advice!

# Answer
> 1 votes
There was a bug in upgrade\_status that didn't treat profiles (like drupalcommerce/project-base ) as they should be. But instead treated it like a misbehaving module.

This is fixed in this issue: https://www.drupal.org/project/upgrade\_status/issues/3230266

So you can try the patch from that issue, or wait for a new release which includes the patch.

---
Tags: commerce, composer, 9, distributions, upgrading
---


# Question
Title: Get client credentials from Simple Oauth module
I am creating user authentification with Drupal 9 + NuxtJS. Using Simple Oauth module and create post requests to

```
oauth/token

```

with data

```
const data = {
  grant_type: 'password',
  client_id: '',
  client_secret: '!',
  username: username,
  password: password,
}

```

So, how can I get this client\_id, client\_secret to past it in JS file ?

# Answer
> 0 votes
Maybe these following modules will help you, I was once stuck with the same issue for the authentication. My Drupal application was decoupled (Frontend - Vue and Backend - Drupal 9)

I installed the following contributed modules: JWT, and Get JWT on Login.

And just call the login (https://your-drupal-site/**user/login?\_format=json**) endpoint with provided credentials, it will send you back the user's details:

```
{
    "current_user": {
        "uid": "1",
        "name": "admin"
    },
    "csrf_token": "UlGb7fak5ZS-r1BRistBh4IWLm_Z7F1xMpY3KYTGqcU",
    "logout_token": "7AvbnHgr9iDxIDVertHTI3PMX2-Shd6sjuN8hNHrHv8F",
    "access_token": "eyJ0eXAiOiJKV1QiLDJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1NDg2NzA3NDUsImV4cCI6MTU0ODY3NDM0NSwiZHJ1cGAsIjp7InVpZCI6IjYifX0.cnG6atSLYrRh6D05LZg9RwrJJdYoJfTBXTUZboPhJH3lYf640FmQTkJwwy9E8kg7ot59qyb5qtgIewM3R1KCDw"
}

```

---
Tags: javascript, authentication-authorization, http-request
---


# Question
Title: Derive all image styles when user uploading
I have several image styles defined but only thumbnail and medium styles(images) can be derived from the original image.

I know those two styles are set in the "manage field" of image and my usage is not going to switch thumbnail nor medium to other styles. My use-case is to generate all styles when/after users upload.

Please help, Thanks!

# Answer
> 3 votes
I believe that the Image Style Warmer module is what you want.

> The Image Style Warmer module provides options to create image styles during upload or via queue worker. So configured image derivates already exists when they are requested.
>
> * Pre-generate configured image styles on image upload or crop change.
> * Pre-generate configured image styles via queue worker.

---
Tags: nodes, media, hooks
---


# Question
Title: Loading individual css files for custom modules
I have a custom module that creates three pages. Each page has a controller, twig file, and css file. What I'd like to do is only load the css files when they are needed. I created a libraries.yml file like this:

```
mymodule:
  version: 1.x
  css:
    theme:
      css/page1.css: {}
      css/page2.css: {}
      css/page3.css: {}

```

This loads the three css files whenever I display any of the three files. What I'd like to do is somehow load page1.css only when page1 is requested. Is there a way to subdivide the libraries.yml file into sections that each specified one css file, then load it into the template with an `attach_library()` call or preprocessing??

Or do I need to create a separate module for each page? The reason I put the three pages in one module is they are a section of the site that share other assets.

# Answer
You can create multiple library entries in \*.libraries.yml.

```
page.1:
  css:
    theme:
      css/page1.css: {}

page.2:
  css:
    theme:
      css/page2.css: {}

page.3:
  css:
    theme:
      css/page3.css: {}

```

Then you can attach the relevant library to the node it should be attached to using `my_module.page.3` (for page three). You would do attach it to the render array being returned from your controller on the given page as follows:

```
class ExampleController extends ControllerBase {
  function firstPageCallback() {
    // Build your $page array (not shown).
    // Then attach:
    $page['#attached']['libraries'][] = 'my_module.page.1';
  }
}

```
> 7 votes

---
Tags: theming
---


# Question
Title: How to hide a custom user field in user profile?
In Drupal 7, what is the best way to prevent any non-administrative user from changing a custom user profile field?

Use case: I've created a user field called "Customer ID" that I do not want the user (any of my actual customers) to change. The field exists for my own reference and for programmatic usage in other modules. I don't mind the user seeing Customer ID, but they should not be able to edit it.

Should I override the page template for the user profile page? If so, how is the template changed to make a field read-only or invisible?

Thank you very much for your help!

Chris

# Answer
I think Field Permissions is what you are looking for. Here is a quote about it (from the module's project page):

> ... allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> **Features**:
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
> * Field permissions overview
> 17 votes

# Answer
To hide the field from the user profile form you can set the `#access` property of a field to FALSE using `hook_form_FORMID_alter`.

The following snippet hides the field `field_organisation` from the user profile form for non-admins:

```
function YOURCUSTOMMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $current_user = user_uid_optional_load();
  if($current_user->uid != 1) {
    $form['field_organisation']['#access'] = FALSE;
  }
}

```

See also this similar question on drupalanswers

You can also hide the field from the user profile page (not the form) using template\_preprocess\_user\_profile

The following snippet hides the field `field_organisation` from the user page for non-admins:

```
function YOURCUSTOMMODULE_preprocess_user_profile(&$vars) {
  $current_user = user_uid_optional_load();
  if($current_user->uid != 1) {
    unset($vars['user_profile']['field_organisation']);
  }
}

```
> 7 votes

# Answer
Seems to be there is a module called http://drupal.org/project/user\_readonly "The module allows an administrator to prevent modification of user account/profile fields. The administrator can select which fields will be disallowed, or which fields will be allowed."
> 1 votes

# Answer
hook\_form\_alter will work for Drupal 8/9 as well, we can hide other custom fields in User profile using **#access** attribute of form elements:

```
use Drupal\Core\Form\FormStateInterface;

hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
{
    // Disable form fields based on User Roles
    if ($form_id == 'user_form') {
      $roles = \Drupal::currentUser()->getRoles();
      if (!in_array('administrator', $roles)){
        // Do something if user has no role administrator;
        $form['account']['roles']['#access'] = FALSE;
        $form['field_organizations_reference']['#access'] = FALSE;
      }
      if (in_array('administrator', $roles)){
         // Do something if user has role administrator;
         $form['account']['roles']['#access'] = TRUE;
         $form['field_organizations_reference']['#access'] = TRUE;
      }
      // Do other stuff for your other roles
    }
}

```
> 0 votes

---
Tags: 7, users, entities
---


# Question
Title: Copied Drupal 8 to Live server now can't log in
I built a simple Drupal 8 website on my DEV box and moved it to the LIVE server.

1. Copied the files on the DEV server into a tarball
2. Moved these file to the LIVE server (using scp).
3. Uncompressed web files into it's destination directory (/var/www/html/newsite)
4. Created the database, user and set permissions to match that on the DEV server
5. Backed up the MySQL Server database into a .sql file with mysqldump
6. Imported from the .sql file into the database of the same name
7. Made sure the APACHE settings pointed to the site's directory

When I navigate to the front page, it comes up.

* Images and page content displays
* Webform works and emails the account it is set for

BUT cannot navigate to any other page!

* /user = Page not found
* /\[anything\] = Page not found
* /?q=user = goes to the (front) page and the URL remains with the
* /?=\[anything\] = shows the front page with the URL remaining

Meaning I cannot log in or run (database) updates!

I've tried

* deleting the Sessions table in the database
* verify mod\_rewrite is enabled in httpd (CentOS)
* verified the apache (httpd) config files match

Any help or ideas appreciated.

I don't think wiping out the website, install a Drupal site and then copy the files/database over the new one would fix anything.

# Answer
Clive, you are correct.

Looking in the `/etc/httpd/conf/httpd.conf` (Apache configuration file on RedHat based distributions such as CentOS) I added the directory and include the `AllowOverride All`.

Once I refreshed it works! Thank you!
> 1 votes

---
Tags: 8
---


title: Add Composer to an existing site

text:
# Question
Title: Add Composer to an existing site
I built a Drupal 8.9 site with Composer on a DEV server and copied the files (& db) over to the LIVE server.

The LIVE server did not have Composer installed previously so I installed it, locally.

The new website has its `composer.json` file from when I created the site and added modules.

I tried `composer update` to verify that composer will work when the time comes.

It fails and I don't know if I need to rip out the website and re-create it again (then copy select files back over).

---

When I run it I get the following output:

```
Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages.

Problem 1

    - Conclusion: don't install drupal/core-recommended 8.9.x-dev (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.8.7 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.8.8 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.8.9 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.8.10 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.8.11 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.8.12 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.0 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.1 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.2 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.3 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.4 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.5 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.6 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.7 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.8 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.9 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.10 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.11 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.12 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.13 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.14 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.15 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.16 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.17 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.18 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.19 (conflict analysis result)
    - Conclusion: don't install drupal/core-recommended 8.9.20 (conflict analysis result)
    - drupal/core-recommended[8.8.0-beta1, ..., 8.9.0-rc1] require composer/installers v1.7.0 -> satisfiable by -> composer/installers[v1.7.0].
    - composer/installers v1.7.0 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.1.0] but it does not match the constraint.
    - symfony/polyfill-mbstring 1.23.x-dev is an alias of symfony/polyfill-mbstring dev-main and thus requires it to be installed too.
    - easyrdf/easyrdf 0.9.1 requires ext-mbstring * -> satisfiable by symfony/polyfill-mbstring[dev-main, 1.23.x-dev (alias of dev-main)].
    - You can only install one version of a package, so only one of these can be installed: symfony/polyfill-mbstring[dev-main, v1.0.0, ..., v1.23.1].
    - drupal/core-recommended 8.8.x-dev requires easyrdf/easyrdf 0.9.1 -> satisfiable by easyrdf/easyrdf[0.9.1].
    - drupal/core-recommended 8.8.x-dev requires symfony/polyfill-mbstring v1.12.0 -> satisfiable by symfony/polyfill-mbstring[v1.12.0].
    - Root composer.json requires drupal/core-recommended ^8.8 -> satisfiable by drupal/core-recommended[8.8.0-beta1, ..., 8.9.x-dev].

To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php.ini
    - /etc/php.ini
    - /etc/php.d/20-bz2.ini
    - /etc/php.d/20-calendar.ini
    - /etc/php.d/20-ctype.ini
    - /etc/php.d/20-curl.ini
    - /etc/php.d/20-dom.ini
    - /etc/php.d/20-exif.ini
    - /etc/php.d/20-fileinfo.ini
    - /etc/php.d/20-ftp.ini
    - /etc/php.d/20-gd.ini
    - /etc/php.d/20-gettext.ini
    - /etc/php.d/20-iconv.ini
    - /etc/php.d/20-json.ini
    - /etc/php.d/20-mysqlnd.ini
    - /etc/php.d/20-pdo.ini
    - /etc/php.d/20-phar.ini
    - /etc/php.d/20-simplexml.ini
    - /etc/php.d/20-sockets.ini
    - /etc/php.d/20-sqlite3.ini
    - /etc/php.d/20-tokenizer.ini
    - /etc/php.d/20-xml.ini
    - /etc/php.d/20-xmlwriter.ini
    - /etc/php.d/20-xsl.ini
    - /etc/php.d/30-mcrypt.ini
    - /etc/php.d/30-mysqli.ini
    - /etc/php.d/30-pdo_mysql.ini
    - /etc/php.d/30-pdo_sqlite.ini
    - /etc/php.d/30-wddx.ini
    - /etc/php.d/30-xmlreader.ini
    - /etc/php.d/40-zip.ini

You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

```

---

Running `php --ini` comes up with a matching list

---

Contents of my `composer.json` file:

```
$ clear && cat composer.json
{
  "name": "drupal/recommended-project",
  "description": "Project template for Drupal 8 projects with a relocated document root",
  "type": "project",
  "license": "GPL-2.0-or-later",
  "homepage": "https://www.drupal.org/project/drupal",
  "support": {
  "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
  "chat": "https://www.drupal.org/node/314178"
},
"repositories": [
  {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
],
"require": {
  "composer/installers": "^1.2",
  "drupal/block_class": "^1.3",
  "drupal/bootstrap": "^3.23",
  "drupal/captcha": "^1.2",
  "drupal/core-composer-scaffold": "^8.8",
  "drupal/core-project-message": "^8.8",
  "drupal/core-recommended": "^8.8",
  "drupal/mask": "^2.0@alpha",
  "drupal/recaptcha": "^3.0",
  "drupal/webform": "^6.1"
},
"conflict": {
  "drupal/drupal": "*"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
  "sort-packages": true
},
"extra": {
  "drupal-scaffold": {
    "locations": {
      "web-root": "web/"
    }
  },
  "installer-paths": {
    "web/core": [
      "type:drupal-core"
    ],
    "web/libraries/{$name}": [
      "type:drupal-library"
    ],
    "web/modules/contrib/{$name}": [
      "type:drupal-module"
    ],
    "web/profiles/contrib/{$name}": [
      "type:drupal-profile"
    ],
    "web/themes/contrib/{$name}": [
      "type:drupal-theme"
    ],
    "drush/Commands/contrib/{$name}": [
      "type:drupal-drush"
    ],
    "web/modules/custom/{$name}": [
      "type:drupal-custom-module"
    ],
    "web/themes/custom/{$name}": [
      "type:drupal-custom-theme"
    ]
  },
  "drupal-core-project-message": {
    "include-keys": [
      "homepage",
      "support"
    ],
    "post-create-project-cmd-message": [
      "<bg=blue;fg=white>                                                         </>",
      "<bg=blue;fg=white>  Congratulations, you’ve installed the Drupal codebase  </>",
      "<bg=blue;fg=white>  from the drupal/recommended-project template!          </>",
      "<bg=blue;fg=white>                                                         </>",
      "",
      "<bg=yellow;fg=black>Next steps</>:",
      "  * Install the site: https://www.drupal.org/docs/8/install",
      "  * Read the user guide: https://www.drupal.org/docs/user_guide/en/index.html",
      "  * Get support: https://www.drupal.org/support",
      "  * Get involved with the Drupal community:",
      "      https://www.drupal.org/getting-involved",
      "  * Remove the plugin that prints this message:",
      "      composer remove drupal/core-project-message"
    ]
  }
}

```

# Answer
> I tried composer update to verify that composer will work when the time comes.

To verify if it will work when the time comes, you would want to run `composer install`. This will attempt to install the set of dependencies according to what is listed in the `composer.lock` file. Running `composer update` attempts to update all your modules to the newest versions. Running this on your production server without having run it locally would result in your production server having a different untested set of module versions than your local system. You would never want to run `composer update` on a production server, only ever `composer install`. You can read more about it here (shameless self plug): https://www.morpht.com/blog/drupal-and-composer-part-1-understanding-composer#synchronizing-project-versions

As to your issue with the update, I believe it lies here:

```
composer/installers v1.7.0 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.1.0] but it does not match the constraint.

```

Your `composer.json` is trying to install `composer/installers`, which specifies a version beginning with 1.0, but Composer has only found 2.0. I think that this is a Composer version 1 vs. a Composer version 2 issue. If I recall correctly, when you have upgraded Composer to version 2, it cannot find `composer/installers` version 1.

You can try running `composer self-update --1` to downgrade to Composer version 1 (note that you can switch back to v2 with `composer self-update --2`). If you find that `composer update` works using Composer version 1, then you'll need to resolve your conflict before upgrading to Composer 2. That's a different topic though.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: Is it possible to render a View based on the Content language?
Drupal supports the concept of Interface Language and Content Language. I (and every client I have ever asked) seem to have a different opinion of what is "content" and what is "interface" than Drupal does (in most cases). I consider Interface as the items an administrator or editor would use to do their job (admin menu, edit tab, help details on forms, etc) and Content is what non-admins (often this is Anon but not always) would see.

A view that I create to present "content" on the site, I naturally think of as content - but Drupal has an inconsistent and often incorrect idea of what this is.

To start with, I have the site set up so that Interface language is defined by the User's preferred language (as a site admin/editor would set) and Content language is defined by the URL langcode prefix.

An example test view looks like this in FR (url is /fr/test) - Interface language is set to EN:

This is clearly incorrect as can be seen with the proper display when I set the Interface language to FR:

Views has numerous options to set how "content" render language is determined. For my example above it is set to render based on the page's "content language" (and therefore the url). This works for most field data (title, taxonomy terms, translated text fields); but sadly does not work for Datetime fields - they seem to be hard coded to incorrectly translate using Interface. But you can also see the config portions of the view (view title, field labels, etc) are also translated as Interface.

**Is there any way to tell a view to translate using the content language?**

I have used the following code:

```
  $languageManager = \Drupal::languageManager();
  $langcode = $languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
  $language = $languageManager->getLanguage($langcode);
  $languageManager->setConfigOverrideLanguage($language);

```

within a block preprocess function to allow some of the block pieces which are incorrectly using Interface language to translate with the content language. Is there some similar way to override the interface language that a view uses for translation? I am hoping it is something like the code above but that I am simply not inserting in the right place (I have unsuccessfully tried hooks for pre-build, pre-render, query\_alter).

If this is possible to do, I would love to write up a contrib module to use the existing ui in a View to set the render language and have it render everything rather than just certain fields.

# Answer
Ughh.. apparently my question had the answer all along. When I add the code snippet:

```
  $languageManager = \Drupal::languageManager();
  $langcode = $languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
  $language = $languageManager->getLanguage($langcode);
  $languageManager->setConfigOverrideLanguage($language);

```

to a \_views\_pre\_render hook it does what I want and uses the config override language to override the language used for the configurable parts of the view (title, column headings and more). The only thing it doesn't handle is the dates - as these are just done wrong in the Datetime module. Not sure why I didn't see this working when I tried it earlier.

And I can override the DateFormatter core service to use the Content language instead of the default (which is interface) and this fixes dates everywhere on the site. This should likely be submitted as a patch to core as I am sure this is a bug - why would dates be considered interface differently than all other content?
> 0 votes

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


# Question
Title: How to use hook_node_insert to automatically flag nodes of a specific content type
All nodes of one content type in my project need to get automatically flagged (by the Flags module) when created. I'm aware that there is probably a way to accomplish this using Rules module, but I'm attempting to build my first-ever custom module to do it, because a) I don't think I'm going to need Rules for anything else in this project and b) want to get my feet wet on making custom modules. (I've got a basic 'hello world' module working.)

A support request in the Flag module seems to provide a simple way to automatically flag nodes, but it looks to me like it would do this to nodes of all content types. https://www.drupal.org/project/flag/issues/3030288

For convenience here's the code there, for a flag called bookmark...

```
function your_module_node_insert(Drupal\Core\Entity\EntityInterface $entity){
 $flag = \Drupal::entityTypeManager()->getStorage('flag')->load('bookmark');
 \Drupal::service('flag')->flag($flag, $entity);
}

```

The api page for this hook doesn't seem to tell me what I need to know. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_ENTITY\_TYPE\_insert/9.0.x)

Questions: Is this even the right hook for this need? If so, how might I restrict it to a specific content type?

# Answer
This is working for me...

'rf\_tweaks' is the module machine name, 'research\_note' is the node content type, and 'research\_item' is the name of the flag.

```
use Drupal\node\Entity\Node;

function rf_tweaks_node_insert(Node $node) {
  if ($node->bundle() == 'research_note'){
 $flag = \Drupal::entityTypeManager()->getStorage('flag')->load('research_item');
 \Drupal::service('flag')->flag($flag, $node);
}
}

```

For the benefit of other first time module builders, this is in the rf\_tweaks.module file and the file begins with the `<?php` required in those.
> 0 votes

---
Tags: hooks, flags
---


# Question
Title: How do I programmatically set a flag's custom entity reference field when programmatically setting the flag?
Some background: I'm new to Drupal 8/9 module building. I need a particular content type's nodes to be automatically flagged. I have this working using the code below. However, the flag involved also has a custom field I need to set.

* It's an entity reference field (to another node)
* I want to set the flag's custom entity reference field to be the same value as an entity reference field on the flagged node.

(This may seem like a strange thing to do. There may be a better way to accomplish the UX goals. I still want to know how to do it.)

'rf\_tweaks' is the module machine name, 'research\_note' is the node content type, and 'research\_item' is the name of the flag.

```
use Drupal\node\Entity\Node;

function rf_tweaks_node_insert(Node $node) {
  if ($node->bundle() == 'research_note'){
 $flag = \Drupal::entityTypeManager()->getStorage('flag')->load('research_item');
 \Drupal::service('flag')->flag($flag, $node);
}
}

```

There's some great info at the flag api page, but the methods are different enough that it's not clear to me how to adapt them to this situation.

# Answer
> 1 votes
The method in your last line of code returns the "flagging" entity, which represents the entity/flag relationship. That's the thing you need to set the field on. e.g.

```
$flag = \Drupal::entityTypeManager()->getStorage('flag')->load('research_item');
$flagging = \Drupal::service('flag')->flag($flag, $node);

$flagging->field_foo->target_id = $node->field_bar->target_id;
$flagging->save();

```

That does involve the flagging entity being saved twice, so if performance ever becomes an issue you might need to create a `Flagging` entity manually and save it to avoid the double-hit.

---
Tags: hooks, flags
---


title: Webform email duplicates uploaded file

text:
# Question
Title: Webform email duplicates uploaded file
I'm using Drupal 9 and only have site admin level access and no developer support. I've also only been working with Drupal for a few months. So total newbie here; I apologize in advance.

I've created a webform which should allow external (non-registered) users to upload a file. The file should, upon submit, be emailed to a specific email address within the company. The problem that I'm running into is when the webform is emailed, the file that's uploaded is duplicated within the email. The file field is set to only allow one file per submission and the submissions stored in Drupal only show one file. The file is only duplicated in the email.

Has anyone come across this before? I've spent the last few days scouring the interwebs and haven't seen this before. I've tried adjusting the email/handler settings that I think might apply: selecting/deselecting exclude file elements with attachments, selecting/deselecting include files as attachments. I've set the email message to default, but I did look at it. Sadly with my limited skills, nothing seemed to jump out that might help. I tried excluding the field value, which just left off the attachment entirely.

I even created a new form with just a file upload field and it still duplicates. The form is 99% there - this is the last thing to work out so any help is greatly appreciated.

Thanks!

# Answer
If you have the SMTP module installed, it looks like you might be running into a known issue.

@see https://www.drupal.org/project/smtp/issues/2995290
> 0 votes

---
Tags: webforms
---


title: GraphQL query to validate User Login

text:
# Question
Title: GraphQL query to validate User Login
I'm working on the Drupal decoupled project, where the client is VueJs and the backend is Drupal 9. I'm using Drupal's contrib module GraphQL 8.x-3.1 for the interaction between client and server. I'm new to GraphQL.

I created a GraphQL query to validate the user during login. Below is the query,

```
query{
  userQuery(filter: {
    conjunction: AND,
    groups: [{conditions: [
      {operator: EQUAL, field: "name", value: "editor.user"},
      {operator: EQUAL, field: "status", value: "1"},
    ]}]}) {
    count
    entities {
        ... on User {
        uid
        name
        pass {
          value
          existing
          preHashed
        }
        mail
      }
    }
  }
}

```

The query is displaying the **pass** field as **null**.

```
{
  "data": {
    "userQuery": {
      "count": 1,
      "entities": [
        {
          "uid": 15,
          "name": "editor.user",
          "pass": null,
          "mail": "editor.user@test.com"
        }
      ]
    }
  }
}

```

Am I doing any mistake to query?

Also, is it the right way to validate the user?

Appreciate your suggestion.

# Answer
Drupal saves hashed password in database and it is a one way encryption, which means you can not get original password from it, during authentication process drupal encode the input password by user and checks if the encoded pass equals the one in the database and when met this condition, in a monolithic project (not decoupled) it creates a cookie with information about the user and sends it back to the browser which will be stored and used for future uses.

But when developing a decoupled approach like using GraphQL or JsonAPI or Rest API you cant always use cookie cause the front end application might not support it (like an android mobile app or ...) so in this case it is better to use Tokens for authentication , there are some modules which one of the most popular is Simple OAuth (OAuth2) & OpenID Connect (STABLE AND WIDLY USED)

after setting this module up (installing using composer ,creating private and public key and introducing consumers) you can simply get a token by making a Post request to:

```
{SiteName}/oauth/token

```

and in the body which should be of type `multipart/form-data` (application/json is not supported) you can have:

```
grant_type = password
client_id = CONSUMER ID YOU CAN BUILD THROGH UI
client_secret = CONSUMER PASSWORD (IF YOU HAVE SET)
username = USERNAME
password = PASSWORD
scope = ROLES YOU WANT USER HAVE WHICH IS NOT DEFIEND IN CONSUMER (WILL NOT AFFECT IF USER DOES NOT HAVE THAT ROLE, SO NO SECURITY CONCERNS)

```

and that's it, you will get an access and refresh token on response. which then can be used in future requests calling GraphQL or any other REST services.

One important notice about this module is about the usage of Scope, and that is when introducing a client you can assign one or more scopes to that client and when a user logins through that client will have all the roles assign to that client
> 2 votes

---
Tags: 9
---


# Question
Title: How do I use the markdown module to print the module README.md file?
I've created a README.md file in the custom module and would like to provide this as the help page in formatted HTML.

Raw text is being printed out, how do I get the HTML?

The module is drupal/markdown 3.0.0-rc1.

```
function cbi_bond_id_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
   case 'help.page.cbi_bond_id':
      $text = file_get_contents(dirname(__FILE__) . "/README.md");
      if (!\Drupal::moduleHandler()->moduleExists('markdown')) {
        return '<pre>' . $text . '</pre>';
      }
      else {
        // Use the Markdown filter to render the README.
        $filter_manager = \Drupal::service('plugin.manager.filter');
        $settings = \Drupal::configFactory()
          ->get('markdown.settings')
          ->getRawData();
        $config = ['settings' => $settings];
        $filter = $filter_manager->createInstance('markdown', $config);
        $filterResult =  $filter->process($text, 'en');
        $text = $filterResult->getProcessedText();
          return '<div>' . $text->getHtml() . '</div>';
        }
    }
    return NULL;
}

```

# Answer
I just tinkered a bit with your code and I believe that your parser settings are modifying your output. I was able to read in a markdown file and output it correctly, formatted as HTML, using the `\Drupal\markdown\PluginManager\ParserManager` service and setting the render strategy to `none`.

```
$text = file_get_contents(dirname(__FILE__) . "/README.md");
if (!\Drupal::moduleHandler()->moduleExists('markdown')) {
  return '<pre>' . $text . '</pre>';
}
else {
  /** @var \Drupal\markdown\PluginManager\ParserManagerInterface $parser_manager */
  $parser_manager = \Drupal::service('plugin.manager.markdown.parser');
  $parser = $parser_manager->getDefaultParser([
    'render_strategy' => ['type' => 'none'],
  ]);
  return $parser->parse($text);
}

```
> 5 votes

---
Tags: input-formats
---


# Question
Title: Change system file temporary maximum age
The default setting given to delete temp files is after 6 hours minimum. I have users upload files and I want that if it has temp status, delete it after 15 secs. Tweaking the file module code is risky, if I get the exact location to change 6 hours to 15 sec that will do the job.

# Answer
The value returned from `\Drupal::config('system.file')->get('temporary_maximum_age')` is the value that decides when temporary files are deleted. Using the following code, for example, you can change that value to 15 seconds.

```
\Drupal::config('system.file')->set('temporary_maximum_age', '15');

```

If you want to change the form as well, which is recommended, use `hook_form_FORM_ID_alter()` to adjust the system file settings shown in the *system\_file\_system\_settings* form.

The code currently used for that setting is the following one.

```
$intervals = [0, 21600, 43200, 86400, 604800, 2419200, 7776000];
$period = array_combine($intervals, array_map([$this->dateFormatter, 'formatInterval'], $intervals));
$period[0] = $this->t('Never');
$form['temporary_maximum_age'] = [
  '#type' => 'select',
  '#title' => $this->t('Delete temporary files after'),
  '#default_value' => $config->get('temporary_maximum_age'),
  '#options' => $period,
  '#description' => $this->t('Temporary files are not referenced, but are in the file system and therefore may show up in administrative lists. <strong>Warning:</strong> If enabled, temporary files will be permanently deleted and may not be recoverable.'),
];

```

You can alter the form and adjust it to what you need.

Keep in mind that files are effectively deleted after 15 seconds if cron tasks run at least every 15 seconds.
> 1 votes

# Answer
Add to local.settings.php

```
$config['system.file']['temporary_maximum_age'] = 15;

```

Note that the temporary files are deleted on cron , which is settable to 1h minimum through the back office or less using server cron job `https://www.drupal.org/docs/7/setting-up-cron/configuring-cron-jobs-using-the-cron-command`
> 0 votes

---
Tags: 8, files, cron
---


# Question
Title: TypeError: Argument 1 passed to EntityOperations::getEntityTranslation() must implement interface EntityInterface, null given
When I go to `admin/content` I'm getting the following error, whereas at the same time `node/{node_id}` is accessible just fine.

> The website encountered an unexpected error. Please try again later. Recoverable fatal error: Argument 1 passed to Drupal\views\Plugin\views\field\EntityOperations::getEntityTranslation() must implement interface Drupal\Core\Entity\EntityInterface, null given, called in /var/www-drupal/core/modules/views/src/Plugin/views/field/EntityOperations.php on line 116 and defined in Drupal\views\Plugin\views\field\EntityOperations-\>getEntityTranslation() (line 74 of core/modules/views/src/Entity/Render/EntityTranslationRenderTrait.php).

Can someone give me an insight what this error means and how I to solve it?

# Answer
I understand that this is an old question / thread, but just want to post something that worked for me for future reference. Your mileage may vary.

* Take a backup of the 'node\_field\_data' table.
* Search and delete 'orphaned' rows on node\_field\_data by comparing against the nids on the 'node' table.
> 5 votes

# Answer
I had this error when I had wanted to go to 'Custom block library'. After debugging I discovered some inaccuracies in DB. In my case there were some extra rows in 'block\_content\_field\_data' table. Those informations you can take from *ResultRow $values* (parameter of render() in EntityOperations.php).

I deleted the rows with id from *ResultRow $values* and it worked.

Remember of taking backup of you DB.
> 0 votes

---
Tags: views, 8
---