title: Error about non-existing configuration

text:
# Question
Title: Error about non-existing configuration
After trying to import configuration with `drush cim` it returns an error saying

> The import failed due to the following reasons:
> Configuration core.entity\_view\_display.contact\_message.kontaktujte\_nas.default depends on the field.
> field.contact\_message.kontaktujte\_nas.layout\_builder\__layout configuration that will not exist after import.

What am I doing wrong?

# Answer
`core.entity_view_display.contact_message.kontaktujte_nas.default` \- this means you have an entity bundle `kontaktujte_nas` of entity type `contact_message`, which has Layout Builder enabled on the `default` display and have enabled the per-entity layout option.

When you enable the per-entity layout option, Layout Builder adds a *hidden* `layout_builder__layout` field on that bundle. That field stores the layout configuration for a single entity of that bundle and uses that instead of the layout defined on the type. In your case, that's the `field.contact_message.kontaktujte_nas.layout_builder__layout` field configuration - you need this file present config during import.

Depending on when you started using Layout Builder, there might be one more configuration file you need in there, a `field.storage.contact_message.layout_builder__layout` \- which defines the DB schema of the layout field (field configs come in pairs, the instance (`field.field.*`) and the schema config (`field.storage.*`). The layout field may not have the former because it's not a visible field, but will certainly have the latter.).
> 1 votes

# Answer
> What am I doing wrong?

You or the person that created the config export most likely missed to update and/or commit one of those two config files.

To check if this is the case, go to live site and run `drush cex` you shouldn't see anything to update. (If there is, just cancel out as your config should be pushed via Git, assuming you're using a Git workflow). This would mean you will have to pull latest code & DB from live to your local and then do a "config sync" (`drush cex`) and push to live.
> 0 votes

---
Tags: configuration
---


# Question
Title: Print the query which is built using db_select()
I want to print the query which is built using db\_select() in a programmatical way. Is there any API function provided by Drupal Abstraction Layer?
It is similar to query output in Views, but I want to print it from my custom module for debugging purpose.

# Answer
`SelectQuery` implements `SelectQuery::__toString()`, which is called in the contexts where a string is required.

Consider the following code.

```
global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

print $query;

```

Its output is the following one.

```
SELECT block.*
FROM
{block} block
WHERE  (theme = :db_condition_placeholder_0) AND (status = :db_condition_placeholder_1)

```

To get the array of arguments used for the query, you can call `SelectQuery::arguments()`.

The following code prints the query and its arguments using the functions made available from the Devel module.

```
global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

dpm((string) $query);
dpm($query->arguments());

```

The Devel module is not necessary, though, and you could `drupal_set_message()` to show the output. For example, you could use the following function to get a string with the placeholders replaced by their actual values.

```
function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }

    $string = strtr($string, $arguments);
  }

  return $string;
}

```

The previous example code I shown would become the following one.

```
global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

drupal_set_message(format_string('Query: %query', array('%query' => _get_query_string($query))));

function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }

    $string = strtr($string, $arguments);
  }

  return $string;
}

```

Notice that `SelectQuery::arguments()` returns the array of query arguments only when it is called after `SelectQuery::__toString()`, `SelectQuery::compile()`, or `SelectQuery::execute()`; otherwise, `SelectQuery::arguments()` returns `NULL`.

You could use a function similar to the following one to get the string query, with the placeholders replaced with the arguments.
> 71 votes

# Answer
You can use dpq() to display the query, and dpr() to display the result.

```
  $query = db_select('users','u');
  $query->fields('u');
  $query->condition('u.uid', 1042);
  $result = $query->execute()->fetchAll();

  dpq($query); // Display the query.
  dpr($result); // Display the query result.

```
> 47 votes

# Answer
Another option is:

```
global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

print strtr((string) $query, $query->arguments());

```
> 23 votes

# Answer
The above answers are good when you have Devel installed and configured.

Best way to print the query without Devel is as below.

```
$query = db_select('block')
->condition('theme', $theme_key)
->condition('status', 1)
->fields('block');
//One way
echo $query->__toString();
// Second way
echo (string)$query;

```

We can use one of the above ways to print the query.
> 9 votes

# Answer
I have a good solution that you can copy/paste your query string directly in "SQL" section in Phpmyadmin and debug your query ( I often use this method when I struggle with query)

```
$querystring=$query->__toString();
$querystring=str_replace("{",'',$querystring);
$querystring=str_replace("}",'',$querystring);
foreach($query->getArguments() as $key=> $item){

    if(!$item) {
        $item = 'NULL';
    }
    $querystring=str_replace($key.')',$item.')',$querystring);
}
dpm($querystring);

```

I hope this be usful for other guys.
> 4 votes

# Answer
Drupal 8 Version:

```
$query = \Drupal::entityQuery('node')
    ->addTag('debug')
    ->execute();

```
> 1 votes

# Answer
We can print SQL String without Devel by **print\_r($query-\>\__toString);**

```
  $query = db_select('node', 'n');
  $query
      ->fields('n', array('nid', 'title'))
      ->condition('n.type', 'article', '=');
  $result = $query->execute();

  print_r($query->__toString());

```
> 0 votes

---
Tags: 7, database
---


title: Feeds: Hook after Import done

text:
# Question
Title: Feeds: Hook after Import done
I am wondering how to implement a Hook after the import of one of my importers is finished. The last imported node and the name of the importer itself would be the parameters that i need to have at this time.

Background/Usecase:

The site I'm working on is built to control IT-projects. After the user imports the bill-positions (each one a row in a CSV file =\> node in Drupal), which happens monthly, the site has to check if all bill-positions for a customer have been invoiced.

This is only one example, there are many other examinations that need to be done after an import is done.

I read the Feeds API & documentation, but I didn't find anything useful.

P.S. I'm pretty new to open source and Drupal itself; so please correct me if I am missing any guideline.

# Answer
> 1 votes
I have never used this, but you can try `hook_feeds_after_import`. You will likely need to `kpr` the `$source` parameter to the hook.

You may also be able to something with Rules. Feeds events don't appear in Rules (unless there is a module I don't know about), but you may be able to trigger on the node save and update events filtered to the content type(s) that you are importing to.

# Answer
> 0 votes
If you're looking at this post and wondering why your hook is not working is because in the D8 version of Feeds, all hooks are gone and most of them are converted to events.

The equivalent for this hook is the event `\Drupal\feeds\Event\FeedsEvents::IMPORT_FINISHED`. In the event callback you’ll get an object of type `\Drupal\feeds\Event\ImportFinishedEvent`.

To listen to this event:

1. Define your event subscriber in your module’s mymodule.services.yml file:

```
    services:
      mymodule.feeds_subscriber:
        class: Drupal\mymodule\EventSubscriber\FeedsSubscriber
        tags:
          - { name: event_subscriber }

```
2. Create your event subscriber class in `mymodule/src/EventSubscriber/FeedsSubscriber.php` and subscribe to `\Drupal\feeds\Event\FeedsEvents::IMPORT_FINISHED`:

```
    <?php

    namespace Drupal\mymodule\EventSubscriber;

    use Drupal\feeds\Event\FeedsEvents;
    use Drupal\feeds\Event\ImportFinishedEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;

    /**
     * (describe what your event listener does here)
     */
    class FeedsSubscriber implements EventSubscriberInterface {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = [];
        $events[FeedsEvents::IMPORT_FINISHED][] = 'afterImport';
        return $events;
      }

      /**
       * Called when an import has finished.
       *
       * @param \Drupal\feeds\Event\ImportFinishedEvent $event
       *   The import finished event.
       */
      public function afterImport(ImportFinishedEvent $event) {
        // (your code here...)
      }

    }

```

Got this answer from this post on drupal.org.

---
Tags: hooks, feeds, importing-exporting, nodes
---


# Question
Title: How to move "description" below the "label" for a field in a form?
Can I user **form\_alter** to move move "description" below the "label" for a field in a form?

Let´s say I want to move the "description" of the "body" field for the basic page content type.

# Answer
> 6 votes
Have a look at Label help module. It just creates a second help field that will appear directly below the form element's label.

It is a simple way to turn around the problem.

Or try something like

```
jQuery(document).ready(function ($) {

  // move the help text from below the input field to directly below the field label

  $('.form-item .description').each(function () {  // description is the help text
    var desc = $(this);
    var label = desc.siblings('label:first');
     if (label.length) {
       desc.insertAfter(label);
     }
  })
  // the help text is tangled up in the text format stuff on a filtered text field
  $('.text-format-wrapper .description').each(function () {
    var desc = $(this);
    var label = desc.siblings('.form-item').find('label:first');
     if (label.length) {
        desc.insertAfter(label);
     }
  })
});
```

(thanks to El bandito !)

# Answer
> 4 votes
## Drupal 7

The module Form element layout solves this both at API level and through the Field settings UI.

As a developer you would use the FAPI attribute `#description_display` and set it `before` if you want it between the `#title` and `#children`, i.e. after the label and before the input element(s):

```
$form['example'] = array(
  '#type' => 'textfield',
  '#title' => t("Example input"),
  '#description' => t("Example description of what this element does."),
  '#description_display' => 'before',
);

```

And as a site builder you would just configure your field settings and toggle the description position.

Note: This module will use replacement themes for various parts of Drupal that renders `#title` and `#description`, so if your theme already has overridden some of these, they won't "take" anymore and you will have to override the themes provided by Form element layout instead.

## Drupal 8

At API level this is already possible using the same FAPI attribute as above, `#description_display`. In addition to the values `before` and `after` it also supports `invisible`, just like `#title_display`.

Field UI wise, we're still waiting for issue #2318757.

# Answer
> 2 votes
You can't move it, but you can always work around things in Drupal.

A hook\_form\_alter() or better hook\_form\_FORM\_ID\_alter() (for a specific form) would be needed to solve your problem.

Inside the form alter, you can use the following code to place the description in different positions. The example is just for the body field, but you can apply the same logic to other fields as well.

```
// Get the language of the field
$lang = $form['body']['#language'];
// Check if a description exists
if (!empty($form['body'][$lang][0]['#description'])) {
  $body_field = &$form['body'][$lang][0];

  // Create new description markup and delete the default description
  $description = '<div class="custom-description">'. $body_field['#description'] .'</div>';
  $body_field['#description'] = '';

  // Place description before the field (between label and field)
  $body_field['#field_prefix'] = empty($body_field['#field_prefix'])
                                 ? $description
                                 : $description . $body_field['#field_prefix'];
}

```

And of course, you'll need to add the proper CSS for the new description markup.

# Answer
> 1 votes
Welcome to the debate. it has been going on for some time.

Check out this discussion for D8: Make position of #description configurable and this: Form Field Description should be between Label and Field. This will give you a perspective on the 5 years I have been watching this. The former has patches to address this, but that means hacking core, unless you wish to create a contributed module. There also seem to be options for moving the description using template.php.

I will leave it to you to join these discussions, and make a decision.

# Answer
> 1 votes
This can be done with hook\_form\_alter() and #field\_prefix. For example, we can take the *description* of the *body* field for the *basic page* content type, and move it directly below the *label*:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, &$form_id) {
  if ($form_id == 'page_node_form') {
    // Move the body's description below the label.
    $language = $form['body']['#language'];
    $form['body'][$language][0]['#field_prefix'] = $form['body'][$language][0]['#description'];
    $form['body'][$language][0]['#description'] = '';
  }
}

```

# Answer
> 0 votes
Here's a generic way using jQuery

```
'.form-group p.help-block'

```

is the child element is the text you want to move.

```
'.form-group label'

```

is the parent element - this where you want to put the text.

This will move each child element within it's own parent element.

Works for any elements you want to move.

```
$('.form-group p.help-block').each(function() {
    $(this).insertAfter($(this).parent().find('.form-group label'));

```

# Answer
> 0 votes
This isn't a very Drupally solution, but it was an easy front-end fix. Styles were designed to work with the Olivero 9.5.2 theme. It uses jQuery to move the elements around in the DOM after the page has been loaded (for text fields and fieldgroups so far)

This moves the descriptions up under the labels:

```
$=jQuery; // lazy hack to keep from typing 'jQuery' repeatedly

// Move the field descriptions just below the label
$(".form-item .form-item__description").each(function(){
  $(this).insertAfter($(this).closest('.form-item').find(".form-item__label:first"));
});

// Move fieldset descriptions to the top of the fieldset contents
$('.fieldset').each(function(){
   $(this).find('.fieldset__description').prependTo($(this).find('.fieldset__wrapper'));
});

```

Style to taste. I moved the help text and field labels together to flow better with this CSS: /\* Fieldgroup label \*/ .fieldset\__description { background-color: #ddd; }

```
/* Fieldgroup Help Text */
.fieldset__description {
    /* margin-top: 0.5625rem; */
    margin-bottom: 0.5625rem;
    font-size: 0.8125rem;
    /* line-height: 1.125rem; */
    padding: 0.1rem 1.25rem;
    margin: -1.1rem -1.1rem auto -1.1rem;
    border-radius: 0 0 0.5rem 0.5rem;
}

/* Form Field Labels */
.form-item__label {
    background-color: #5d7585;
    color: #fff;
    padding: 0 10px;
}

/* Form Field Help Text */
.form-item__description {
    max-width: none;
    background-color: #eee;
    padding: 0.5rem;
    border-radius: 0 0 1rem 1rem;
    margin-top: -0.55rem;
}

```

This ends up giving a display like this:

---
Tags: entities
---


# Question
Title: How to configure shipping rates based on product attributes
I am implementing Drupal Commerce 2

My use case

Product such as an album release is offered as a product in different format such as LP, 7inch, CD. Each format has a different shipping cost. In other words, different attribute has different costs of shipping.

Music Album xxx

* attribute LP - costs $17 to ship
* attribute 7 inch costs $5 to ship
* attribute CD costs $3 to ship

How do we do this with Drupal commerce shipping?

I tried to setup with "product category" taxonomy; however, it's only applicable on the product level, not to the product attribute.

# Answer
> 1 votes
I had to do a similar thing and ran into the same issue. I was selling prints of various sizes.

Each print was a product. Each size of the print was a variation inside of that product. Depending on the print size, I wanted to apply a certain amount for shipping.

Ultimately, you'll need to add a custom shipping condition.

**What I did**

On the Variation Type, I added a List (Text) field called `field_package_size`. Here, I put my shipping sizes (small, medium, large).

Then, I created a shipping method. But as you see, there's no condition to get the info from the variation. Just "product category" which only taps into taxonomy terms at the Product level.

**Create the Shipping Condition**

The Commerce docs have a good outline of making a condition: https://docs.drupalcommerce.org/commerce2/developer-guide/core/conditions#conditioninterface-and-conditionbase

I create a custom module that handles my conditions. All the module has besides the base `custom_module.info.yml` file is one file.

```
custom_module/src/Plugin/Commerce/Condition/PackageSizeInOrder.php

```

Here's the entire file:

```
<?php

namespace Drupal\plateau_astro_commerce\Plugin\Commerce\Condition;

use Drupal\commerce\Plugin\Commerce\Condition\ConditionBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides the SKU prefix in order condition.
 *
 * @CommerceCondition(
 *   id = "package_size_in_order",
 *   label = @Translation("Package Size"),
 *   display_label= @Translation("Package Size"),
 *   category = @Translation("Products", context = "Commerce"),
 *   entity_type = "commerce_order",
 * )
 */
class PackageSizeInOrder extends ConditionBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'package_size' => '',
      'exclude' => FALSE,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['package_size'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Shipping format'),
      '#description' => $this->t('Enter some shipping format to use as a condition for this offer. Separate with comma'),
      '#default_value' => $this->configuration['package_size'],
      '#required' => TRUE,
    ];
    $form['exclude'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Exclusive condition'),
      '#description' => $this->t('Check this box if the condition should be exclusive. IE the condition will pass if the order contains none of the package sizes listed.'),
      '#default_value' => $this->configuration['exclude'],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    $values = $form_state->getValue($form['#parents']);
    $this->configuration['package_size'] = $values['package_size'];
    $this->configuration['exclude'] = $values['exclude'];
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate(EntityInterface $entity) {
    $exclude = (bool) $this->configuration['exclude'];
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $entity;

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $purchased_entity */
    $items = $order->getItems();

    $formats = preg_split('/\r\n|\r|\n/', $this->configuration['package_size']);

    foreach ($items as $item) {
      if (!$purchased_entity = $item->getPurchasedEntity()) {
        continue;
      }
      if (!$purchased_entity || $purchased_entity->getEntityTypeId() !== 'commerce_product_variation') {
        continue;
      }
      if (!method_exists($purchased_entity, 'getSku')) {
        // Not sure what to do then.
        continue;
      }

      $size = $purchased_entity->get('field_package_size')->getString();

      foreach ($formats as $format) {
        if (empty($format)) {
          continue;
        }
        $config = explode(',', (string) $format);
        foreach ($config as $config_format) {
          $config_format = trim($config_format);
          if (empty($config_format)) {
            continue;
          }
          if (strpos($size, $config_format) === 0) {
            return !$exclude;
          }
        }
      }
    }
    return $exclude;
  }

}

```

I'll go through each of the functions.

**`defaultConfiguration()`**

Sets the defaults when loading the condition form.

**`buildConfigurationForm()`**

Builds the form. For me, all I really needed was a simple field that I could type the name of the value small, medium, or large.

Initially, I had a taxonomy term on my product variation. Ideally this field would be a dropdown of those terms, but loading in taxonomy terms was beyond my skill (it can be done! I just didn't know how to do it).

This is why I instead used a text field on my Product Variation.

**`submitConfigurationForm()`**

Submits the form.

**`evaluate()`**

This checks to see the value on `field_package_size`. If you follow my setup, you shouldn't need to adjust anything here except what the name of your field is on your Product Variation.

**Create Shipping Method for Each Shipping Cost**

After you create the file above, clear the cache, a new shipping condition should appear.

Then, you create a Shipping Method for each one you have. For mine, I have Small, Medium, and Large.

On each method, I add this custom condition, then fill in the value from `field_package_size`. Example below for my Small shipping method.

**Combine products into one shipment**

For my scenario, if somebody bought a product with a variation tagged with 'Small' and 'Medium', then I'd put both products into the same package/shipment with the 'Medium' price.

You will have to do some condition logic in the Shipping Method. I'll put screenshots of my Small, Medium, and Large shipping conditions in case you run into this snag:

Small

Medium

Large

# Answer
> 0 votes
mmmm if you need it bad you will need to make your own custom price resolver what i did was put a price field on the attribute itself then did ...

```
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
if ($entity->get('type')->getValue()[0]['target_id'] == 'something') {
    $base = (float) $entity->price->number;
    $code = $entity->price->currency_code;

    $wrap = $entity->attribute_attrib_name->referencedEntities()[0];
    $wrap_pice = (float) $wrap->field_price->getValue()[0]['number'];
    $new_price = $base + $wrap_pice;
    return new Price($new_price, $code);
}

```

see https://docs.drupalcommerce.org/commerce2/developer-guide/pricing/price-resolvers for more info

---
Tags: commerce
---


title: AJAX on Form Details

text:
# Question
Title: AJAX on Form Details
I have a lot of API calls in a form, so in order to not call everything on load, I only want to load it when the user opens the details element.

But I am having trouble adding #ajax to the element. I can see a spinner and that it calls buildForm(), but it is not triggering the callback method. When I wrap the ajax part inside e.g. an checkbox, it works. Thus, I come to the conclusion that it is something with the details element.

How can I create an ajax callback, when the user opens the details element?

Non-working example with ajax on details:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  [...]
  return [
    '#type' => 'details',
    '#title' => $title,
    '#open' => FALSE,
    '#ajax' => [
      'callback' => [$this, 'openAccordion'],
      'event' => 'click',
    ],
  ];
}

public function openAccordion(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  return $response;
}

```

Working example where ajax is on a button (just an example):

```
return [
  '#type' => 'details',
  '#title' => $title,
  '#open' => FALSE,
  'widget' => [
    '#type' => 'button',
    '#value' => 'Load',
    '#ajax' => [
      'callback' => [$this, 'openAccordion'],
      'event' => 'click',
    ],
  ],
];

```

# Answer
> 2 votes
I am suspecting you cannot attach #ajax to non-input elements. As the display element does not take an input, it likely doesn't trigger #ajax. You can do the following as a fix.

1. Create a library:

```
details_element_ajax:
  css:
    theme:
      css/details_element_ajax.css
  js:
    js/details_element_ajax.js
dependencies:
  - core/once
  - core/jquery

```
2. Add a details element, and a submit button that triggers the ajax, and attach the library

```
$form['details'] = [
  '#open' => FALSE,
  '#markup' => '',
  '#attached' => ['library' => 'examplemodule/details_element_ajax',
];

$form['hidden_submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('load_details),
  '#ajax' => [
    'callback' => [$this, 'openAccordion'],
    'event' => 'click',
  ],
];

```
3. Hide the submit button in the CSS file:

```
#edit_hidden_submit {
  display:none;
}

```
4. In the JS file, when the details element is opened, click the hidden submit button to trigger the ajax:

```
Drupal.behaviors.displayElementAjax = {
  attach: function(context) {
    const elements = $(context).find('#details_element_ajax').once('myfeature');
    elements.each(function () {
      $(this).click(function() {
        $("#edit_hidden_submit').click();
      });
    });
  }
};

```

---
Tags: forms, 9
---


# Question
Title: how to validate file size in drupal file upload
in here file validate extensions are working,but the file size validate is not working,i just need file size only, resolution doesn't matter,i want to restrict max file size to 1MB

```
 $form['photo']['file'] = array(
'#title' => t('Photo (Max size 2 MB)'),
'#type' => 'managed_file',
'#description' => t('xvxcds'),
'#default_value' => variable_get('photo', ''),
'#upload_location' => 'public://photo_images/',
 '#upload_validators' => array(
'file_validate_size' => array(1024*1280*800),
'file_validate_extensions' => array('gif jpg jpeg'),
// Pass the maximum file size in bytes
), );

```

# Answer
> 9 votes
You're currently setting the limit to 1024\*1280\*800 bytes, which is the equivalent of about 1Gb.

Remember, 1kb = 1024b, 1mb = 1024kb, so for a 1mb limit:

```
'file_validate_size' => array(1024 * 1024),

```

# Answer
> 0 votes
You can use managed\_file: Like this ....

> ```
>       $form['files'] = array(
>         '#type' => "managed_file",
>         '#title' => 'CV',
>         '#required' => 'required',
>         '#upload_location' => 'public://job',
>         '#upload_validators' => [
>           'file_validate_extensions' => ['pdf doc txt'],
>           'file_validate_size' => [1024 * 1024], // stores files into Byte
>         ],
>       );*
>
> ```

---
Tags: forms
---


# Question
Title: How show field labels in the node display even if it's empty
While showing a node, only the filled fields are rendered. I wanted to be able to show the empty field labels, and I was looking for something like the ability to uncheck an option such as 'Hide if empty' or check a 'Display even if empty.'. Unfortunately, there are no such options. In order to display them, I used a hook\_preprocess\_node:

```
/**
 * Implements hook_preprocess_node().
 */
function MYMODULE_preprocess_node(&$variables) {
    $node = $variables['node'];
    $all_fields = $node->getFieldDefinitions();
    $node_fields = $node->getFields();
    foreach ($node_fields as $field_name => $field) {
        $value = $field->getString();
        if (str_contains($field_name, 'field_') && !$value) {
            $variables['content']['_field_layout']['content'][$field_name] =
            [
                '#theme' => 'field',
                '#title' => $label = $all_fields[$field_name]->getLabel(),
                '#field_type' => $all_fields[$field_name]->getType(),
                '#label_display' => "inline",
            ];
        }
    }
}

```

This made all the hidden fields display, but are not honouring the order set on the node display. Is there a way to get and pass a #weight?

# Answer
> 2 votes
I found a contrib module that allows showing hidden fields: https://www.drupal.org/project/empty\_fields

Thank you for people chipping in that made me dig deeper ( I still can't believe how I missed it before moving to the preprocess )

# Answer
> 0 votes
As far as understand, most (if not all) twig files check:

```
if the field is empty
    don’t show both label or content
else
    show everything

```

I’ve came across the kind of situation you describe. My solution was to change (appropriately) the twig files so that the label is outside the if statement.

---
Tags: nodes
---


# Question
Title: How to get one time login for all the users?
I want to send one time login for all the users, So I am using drush uli and getting link like:

> `http://html/user/reset/1/1509979615/VBPx_FMfKeJUEt1moVcsSQGUMX_tFUSYEdEfRlmq7eA`

So if the user 5 wants to use one time login, this will be used for only the user 1, right? Basically I want to set one time login for all the users.

How do I pass this URL in Drupal 8?

I just wanna know that how could use this in forgot password mail.

# Answer
### `drush`

To get one-time login for the specific user, use this syntax:

```
drush uli <user>

```

Where `<user>` is either uid (e.g. `5`), user name, or email address for the user.

To get one-time login URL for multiple users or all, you need to run `drush` in the loop, e.g.

```
for uid in $(drush sqlq "SELECT uid FROM users"); do drush uli $uid; done

```

Run `drush help uli` for help with syntax.

To correct your `http://html` part, add `-l http://example.com` parameter, or set your `$base_url` in your settings file.

### Custom code

If you're interested in sending one-time login via e-mail using Drupal, you can use `user_pass_reset_url()` function in your custom code.

> Generates a unique URL for a user to login and reset their password.

### Contrib module

Or use Login one time module (for D8, check this issue).

> *Login one time* provides the ability to email one-time login links to users.
> 9 votes

# Answer
If you'd like to force all of your users to log in via one-time login links all the time, you could use the passwordless module.

If you set the $base\_url in your settings.php file, then the Drush user-login command will generate the correct URL in the output. You could then write a simple script to email every user with their own unique login link.

There is no Drush command to email a password-reset link to a user, but there of course Drupal does this on the request password page. You could use the user module as a guide, and write a simple module or Drush command to mass-reset all users.
> 4 votes

# Answer
**In Drush version \> 9 it should be**

```
drush uli --name=USERNAME

```

**notice** take a look at a digit after `reset/{UID}/` is should be the id of user you've tried to reset

in you case `user/reset/1/` it obviously reset the password for used one.

So if you want to do it for all user run the following command in your terminal :

```
for name in $(drush sqlq "SELECT name FROM users"); do drush uli --name=$name; done

```
> 4 votes

# Answer
```
drush uli --uid=1

```

This command would be logged in as an admin because when you set up your site for the first time, the user will be created as an admin role by UID=1.

After that, you will get one-time login URL in your terminal such as

```
http://default/user/reset/1/1674467207/PBQm_aOMgSH8Jnpko8sw0jDPrLZPT6_s1GTKv5k_Hb4/login

```

You can paste the URL from /user/..... in your browser after your virtual host or your domain, etc. otherwise you can replace the **default** value with your domain name.

Thanks
> 0 votes

---
Tags: 8, users, drush
---


# Question
Title: Dynamicaly add ajax form item and add event on checkbox
I've added an ajax callback to my form to add some data on it :

```
$form['add'] = [
    '#type' => 'button',
    '#value' => t('add'),
    '#ajax' => [
        'callback' => [$this, 'ajaxFormAdd'],
        'event' => 'click',
        'wrapper' => 'contacts',
        'progress' => [
            'type' => 'throbber',
            'message' => $this->t('Ajout d\'un contact...'),
        ],
    ],
];

```

This is how I render the new fields (they're appended into a specific div)

```
public function ajaxFormContact(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Ajax\AjaxResponse $response */
    $response = new AjaxResponse();

    $index = 0;
    $collapseId = 'collapse-contact-' . $index;
    $toggle = '<button class="btn btn-primary collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#' . $collapseId . '" aria-expanded="true" aria-controls="' . $collapseId . '">Contact ' . $index . '</button>';
    $collapse = '<div class="collapse show" id="' . $collapseId . '"><div class="card card-body"></div></div>';
    $contact = $this->buildSingleContact($index);
    $response->addCommand(new AppendCommand('#contacts', $toggle . $collapse));
    $response->addCommand(new AppendCommand('#' . $collapseId . ' > .card', $contact));
    $form_state->setRebuild();
    return $response;
}

```

And those are the fields added :

```
public function buildSingleContact(int $index) {
    $contact_single['contacts'][$index]['firstname'] = [
        '#type' => 'textfield',
        '#title' => 'firstname',
        '#attributes' => [
            'data-drupal-selector' => "edit-contacts-$index-firstname",
            'id' => "edit-contacts-$index-firstname",
            'name' => "contacts[$index][firstname]",
        ]
    ];
    $contact_single['contacts'][$index]['extraInfo'] = [
        '#type' => 'checkbox',
        '#title' => $this->t('Add info'),
        '#prefix' => '<div class="form-check form-switch">',
        '#suffix' => '</div>',
        '#attributes' => [
            'data-drupal-selector' => "edit-contacts-$index-extraInfo",
            'id' => "edit-contacts-$index-extraInfo",
            'name' => "contacts[$index][extraInfo]",
        ],
        '#ajax' => [
            'callback' => [$this, 'ajaxFormExtra'],
            'event' => 'change',
            'progress' => [
                'type' => 'throbber',
            ],
        ],
    ];
    return $contact_single;
}

```

So this is my problem:

The ajax on my button is working because the button is on the page when the page is loaded.

But the checkbox *extraInfo* has no event, because the contact is created after the js is loaded.

So how do I add the change event on my newly added checkboxes ? Is it possible to add like a "`$(selector).on('click')`" instead of "`$(selector).click()`" ?

# Answer
> Nop :) the problem on your link is that the input are not submitted, my problem is that the checkbox doesn't have the event because it's generated after the page is loaded

When adding form elements too late in an ajax callback you're not only preventing input values to be submitted, but also you're bypassing the processing steps.

For a checkbox element these are:

```
  '#process' => [
    [$class, 'processCheckbox'],
    [$class, 'processAjaxForm'],
    [$class, 'processGroup'],

```

In your case you need `processAjaxForm` calling preRenderAjaxForm to attach the necessary JavaScript.

So add the form elements already in buildForm():

```
$form['contact'][$index] = $this->buildSingleContact($index);

```

Check `$form_state->getTriggeringElement()` for the right time to add the new fields.

The ajax callack is then only a delivery method for the dynamically added parts

```
$response->addCommand(new AppendCommand('#' . $collapseId . ' > .card', $form['contact'][$index]));

```

instead of the entire $form in a non-Ajax rebuild.
> 1 votes

---
Tags: forms, javascript, ajax
---


# Question
Title: The missing modules don't get installed after updating with Composer
To update a site locally, I cloned the code base with git to my local computer and imported the database, then ran "composer update --with-dependencies", there were no errors, then I went to /web directory and ran "drush updb -y", it showed me 8 missing modules:

```
The following module is missing from the file system: add_to_head    [warning]
bootstrap.inc:276
The following module is missing from the file system: context        [warning]
bootstrap.inc:276
The following module is missing from the file system: context_ui     [warning]
bootstrap.inc:276
The following module is missing from the file system: libraries      [warning]
bootstrap.inc:276
The following module is missing from the file system: menu_target    [warning]
bootstrap.inc:276
The following module is missing from the file system: panelizer      [warning]
bootstrap.inc:276
The following module is missing from the file system: phpmailer      [warning]
bootstrap.inc:276
The following module is missing from the file system: site_verify    [warning]
bootstrap.inc:276
The following module is missing from the file system:                [warning]
special_menu_items bootstrap.inc:276
No database updates required                                         [success]

```

I tried to log in to the local site, but first ran "drush pm-uninstall captcha", but the site returned the white screen and:

> "The website encountered an unexpected error. Please try again later."

I thought that the problem was due to the missing modules and started running "composer require" for each of them. But they either didn't get installed or returned:

```
 Using version ^3.0@beta for drupal/phpmailer
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Updating drupal/phpmailer (dev-3.x 950f2af => 3.0.0-beta2):     Update failed (The .git directory is missing from web/modules/contrib/phpmailer, see https://getcomposer.org/commit-deps for more information)
    Would you like to try reinstalling the package instead [yes]? yes
  - Removing drupal/phpmailer (dev-3.x)
  - Installing drupal/phpmailer (3.0.0-beta2): Cloning 8.x-3.0-beta2 from cache
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

```

I don't what else to do. Is the "unexpected error" caused by those missing modules? What should I do to fix it?

UPDATE: I looked at /admin/reports/dblog and here's the php error I saw:

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 201 of /sites/bak/web/core/lib/Drupal/Core/Routing/RouteProvider.php).

# Answer
> 0 votes
I faced Same error before so what you have to do is for example let's say it is panelizer.

# The following module is missing from the file system: panelizer \[warning\]bootstrap.inc:276

1) use composer and say composer require drupal/panelizer in the terminal.

2)After installing the module now try to uninstall the module right away using the command below

drush pm-uninstall panelizer

Now go to your site and do following operations. Configuration\>Development\>Performance and now do the Clear-Cache. If you come back to your site you will not find an error.

# Answer
> 0 votes
I managed to solve this issue by executing the following steps:

* `composer clear-cache`
* `rm -r vendor/`
* `rm -r web/sites/modules/contrib`
* `composer install`

# Answer
> -1 votes
Remove your Composer lock file and run following command in sequence:

* `composer clear-cache`
* `composer install`
* `composer require Drupal/module`

# Answer
> -1 votes
Remove your Composer lock, vendor folder and run 'composer install' again

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


# Question
Title: How to POST file with JSON:API in /jsonapi/file/file?
I tried with POSTMAN to upload a file to my endpoint host/jsonapi/file/file, the POST method is available but when I try to upload something, drupal gives me a 415 unsupported media type error. I tried with the binary option and with the data-form option using the next headers:

```
"Accept: application/vnd.api+json"
"Content-Type: application/octet-stream"
'Content-Disposition: file; filename="test.jpg"'

```

The GET method works well. It returns me all the files.

What is wrong?

# Answer
> 0 votes
To upload a file I just change the endpoint "host/jsonapi/file/file" for "host/jsonapi/node/\[my\_specific\_name\]/\[relationship\_field\_name\]" with the binary option in the body of the POST in POSTMAN.

Also this documentation was really helpful docs

---
Tags: http-request
---


# Question
Title: Facet blocks in a dialog don't retain applied facets
Cross posting an issue I posted from Drupal.org in the hope that it gets a bit more visibility here.

I'm currently loading facet blocks via AJAX into an off canvas dialog provided by the core Dialog API. To achieve this, I have a controller set up that accepts a facet ID as a parameter, and then loads the block (I've attached the code at the end of this question as an example).

This works perfectly on the face of it (all of my facets are listed, the dialog works and shows the facet widgets for each facet). However, what I've noticed is that if I have a facet enabled, this isn't taken into account when generating facet links. For example; if I have a facet applied for *language*, and then look at the link generated for my *collection* facets, the facets link to my search page with the *collection* facet applied, but without the existing *language* facet.

The search view itself is not an AJAX view, it's just the loading of the facet blocks. Unfortunately, this is a requirement as we have a large amount of facets that kill the performance if loaded as part of the main request.

Here are some things I've tried:

1. Adding the main page parameters to my dialog links
2. Using these query parameters to configure, load, and execute my search view during the AJAX request before the facet block is generated (see following example)

These facet blocks are only ever rendered on the same page as the facet source View, however as it's not the same *request* it may as well be on a different page.

I guess my question is one of multiple parts:

1. Am I missing something obvious in my approach
2. Is it possible to do what I'm trying to achieve
3. If it is and I'm going the wrong way about it, what's the right way to go about it

As an aside, I'm rendering the blocks isn't a requirement if it's easier to render the facets themselves - it just felt like it would be easier.

As promised, here's my controller code. As mentioned, the facet blocks display, but already-applied facets aren't taken into account during link generation.

## MY\_MODULE.routing.yml

```
my_facets.ajax_facet_block:
  path: '/ajax/my-facets/{facet_id}'
  defaults:
    _title: 'Filter by'
    _controller: '\Drupal\my_facets\Controller\AjaxFacetBlockController::renderFacetBlockAction'
  requirements:
    _permission: 'access content'

```

## Controller

```
<?php

namespace Drupal\my_facets\Controller;

use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Render\RendererInterface;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Returns responses for Facets routes.
 */
class AjaxFacetBlockController extends ControllerBase {

  public function __construct(
    protected BlockManagerInterface $blockManager,
    protected RendererInterface $renderer,
    protected Request $request
  ) {
  }

  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('plugin.manager.block'),
      $container->get('renderer'),
      $container->get('request_stack')?->getCurrentRequest()
    );
  }

  /**
   * Builds the response.
   */
  public function renderFacetBlockAction(string $facet_id) {
    // We need to execute the search view to correctly generate links.
    // @ToDo: Once this is working inject the entity type manager rather than calling `Views::getView`
    $search_view = Views::getView('search');

    if (!$search_view) {
      throw new NotFoundHttpException();
    }

    $search_view->setDisplay('search_page');

    $search_view->setExposedInput(array_filter(
      $this->request->query->all(),
      static fn ($k) => !str_starts_with('_', $k),
      ARRAY_FILTER_USE_KEY
    ));

    $non_facet_params = array_filter(
      $this->request->query->all(),
      static fn ($key) => $key !== 'f' && !str_starts_with($key, '_'),
      ARRAY_FILTER_USE_KEY
    );

    $search_view->exposed_raw_input = array_merge(
      $search_view->exposed_raw_input,
      $non_facet_params
    );

    $search_view->exposed_data = array_merge(
      $search_view->exposed_data,
      $non_facet_params
    );

    $search_view->preExecute();
    $search_view->execute();

    try {
      /** @var \Drupal\facets\Plugin\Block\FacetBlock $block */
      $block = $this->blockManager->createInstance(
        'facet_block' . PluginBase::DERIVATIVE_SEPARATOR . $facet_id, []
      );
    }
    catch (\Exception) {
      throw new NotFoundHttpException();
    }

    if (!$block || !$block->access($this->currentUser())) {
      throw new NotFoundHttpException();
    }

    return $block->build();
  }

}

```

# Answer
This ended up being due to the QueryString processor provided by the Faces module performing a check for XmlHttpRequests as it's very first step (I assume to cover ajax based Views). If it finds that a request is an XmlHttpRequest, then it'll act on a subrequest (which in my case doesn't exist).

My rather rudimentary fix was to strip the `X-Requested-With` header from the request with an event listener on the `KernelEvents::REQUEST` event. This makes the underlying Symfony request respond as a standard request (read: non-XMLHttpRequest), and allowed the query string processor to act on the correct response instead of the sub-response.
> 0 votes

---
Tags: 9, search
---


# Question
Title: Get path to theme assets in Twig template
I have a question about getting a path to an image in a Twig template. The image is not assigned to a field or something. Just a static image which is stored in "MYTHEME/image/icon/my-icon.png".

In Drupal 7 I get the path in my node.template with the following code:

```
<img src="<?php print base_path() . path_to_theme(); ?>/image/icons">/my-icon.png

```

How does it work with in Drupal 8? I tried to pass a variable in `template_preprocess_node()`.

**MYTHEME.theme:**

```
$variables['images_path'] = \Drupal::theme()->getActiveTheme()->getPath() . '/image/';

```

**Twig template:**

```
<img src="{{ images_path  ~ 'icons/' ~ 'my-icon.png' }}">

```

It doesn't work. There is no PHP error, but the path is wrongly said to be http://localhost/node/themes/template/image/icons/my-icon.png.

# Answer
> 71 votes
you can use `{{ base_path ~ directory }}` which will fix the absolute problem, no need to do any preprocessing, both of these variables are included by core.

For example

```
<img src="{{ base_path ~ directory }}/images/logo.png" alt="My Logo" />

```

*PS. the `~` helper in twig is concatenate.*

Edit: at least in the page\*.html.twig templates base\_path variable is included, possibly you will need to do preprocessing for other templates, you can easily check with `{{ dump() }}` if the variables are present

```
// File: THEMENAME.theme in your theme's root directory
function THEMENAME_preprocess(&$variables, $hook)
{
    $variables['base_path'] = base_path();
}

```

# Answer
> 18 votes
```
<img src="/{{ directory }}/images/logo.png"/>

```

worked for me when

```
<img src="{{ base_path ~ directory }}/images/logo.png" alt="My Logo" />

```

did not

for content template, i had to use in .module

```
   function hook_preprocess(&$variables, $hook) {

  $module_handler = Drupal::service('module_handler');
  $path = $module_handler->getModule('myModuleName')->getPath();

  if(isset($variables['region']) && $variables['region'] == 'content'){
    $variables['module_path'] = $path;
    $variables['http_host'] = $_SERVER['HTTP_HOST'];

```

and

```
  <img src="{{ module_path }}/images/error404.png" />
  <img src="//{{ http_host }}/{{ module_path }}/images/error403.png" />

```

# Answer
> 11 votes
There is by default a `{{ directory }}` variable that you can use that points to your theme directory. The problem is, it's not absolute, just like the one you added. I think that's a bug in core because it should include the base path, but changing that would of course break existing sites that use it.

So you need to add a / in front of it; this would break if Drupal is installed in a subfolder. You can either hardcode that in your template or keep using `base_path()` as you did in 7.x in a custom variable.

# Answer
> 5 votes
To print an image url that is inside your custom theme use the following construction:

```
{% set icon_path = [
  url('<front>')|render|trim('/', 'right'),
  active_theme_path(),
  'relative/path/to/image.png'
]|join('/') %}

<img src="{{ icon_path }}" alt="uncategorized"/>

```

If you have already installed twig\_tweak module then you can reuse `drupal_url` function:

```
<img src="{{ drupal_url(active_theme_path() ~ '/relative/path/to/image.png', {absolute: true}) }}" alt="uncategorized"/>

```

# Answer
> 0 votes
```
<img src="{{ base_path ~ '/modules/custom/YOUR_MODULE_NAME/images/logo.png' }}" />

```

The above line works for loading images in Twig template where both are placed in your custom module without any need to add $base\_path to hook\_preprocess.

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


# Question
Title: How can I alter the response headers for error pages?
Same question as a few years back for Drupal7 - but the offline maintenance page seems a little different in Drupal 8/9/10 - and still a work in progress:

https://www.drupal.org/project/drupal/issues/2720109

We have Cloudflare sitting in front of our Drupal sites - and in order to take advantage of their "AlwaysOnline" feature - we need to alter the response code sent in the event of an error - we need a 504 code.

I want to cater for when the database is unavailable - as this can sometimes happen when upgrading the MySQL server.

I did this in Drupal 7 using:

```
function MYTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_http_header('Status', '504 Service unavailable (with message)');
}

```

How do we alter the response code in Drupal 9 when the database connection is down without hacking core?

# Answer
As @Jaypan commented, normally you are able to catch database exceptions in a Symfony event subscriber, but Drupal has made the bootstrap process depending on the database before Symfony could even load the container. The only non-core files available so early are in the sites folder. Modules are not initialized at this point.

To catch database exceptions during the bootstrap process put this PHP file in the sites folder:

*/sites/exception.inc*

```
<?php

use Drupal\Core\Database\DatabaseException;
use Symfony\Component\HttpFoundation\Response;

function _db_exception_handler($exception) {
  if ($exception instanceof \PDOException || $exception instanceof DatabaseException) {
    $response = new Response('Service not available!', 504);
    $response->send();
    exit;
  }
  _drupal_exception_handler($exception);
}

set_exception_handler('_db_exception_handler');

```

and this line in settings.php:

```
include DRUPAL_ROOT . '/sites/exception.inc';

```
> 0 votes

---
Tags: 9
---


# Question
Title: Convert Drupal 8.6 site to Composer (after D8 end of life)?
Client has a sqldump and a tarball of a broken Drupal site.

Instead of using Composer to set up the recommended project, it looks like the previous developer performed a git checkout of http://git.drupal.org/project/drupal circa Drupal 8.6.15 `:anguished:`.

I'd like to Composerize the project before attempting to update Drupal from D8 to D9, but it looks like I can no longer `composer require "drupal/core-recommended": :8.6.15"`:

```
$ ddev composer install
No composer.lock file present. Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - composer/installers v1.5.0 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.3.0] but it does not match the constraint.
    - drupal/core-recommended 8.6.15 requires composer/installers v1.5.0 -> satisfiable by composer/installers[v1.5.0].
    - Root composer.json requires drupal/core-recommended 8.6.15 -> satisfiable by drupal/core-recommended[8.6.15].

composer [install] failed, composer command failed: exit status 2. stderr=

```

What's the best practice here?

# Answer
> 1 votes
Steps to create locally in DDEV:

```
mkdir testd9
cd testd9
ddev config
# defaults to: testd9, current folder, PHP
ddev composer create drupal/recommended-project:9.5.1 --no-install
nano composer.json
# change composer/installers to 1.5
# temporarily remove drupal/core-composer-scaffold to 8.6.15
# temporarily remove drupal/core-project-message to 8.6.15
# change drupal/core-recommended to 8.6.15
# save
nano .ddev/config.yaml
# change php_version to 7.4
# change composer_version to 1
# save
rm composer.lock
ddev restart
ddev composer install
ddev config
# defaults to testd9, web, drupal8
# load database
# load files folder
# test install
# upgrade to different drupal version.
# composer/installers will need to be upgraded occaisionally.
# at 8.8 it will require the drupal-core-composer-scaffold Keep in sync with drupal/core-recommended
# drupal/core-project-message is not needed.

```

resulting composer.json:

```
{
    "name": "drupal/recommended-project",
    "description": "Project template for Drupal 9 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.5",
        "drupal/core-recommended": "8.6.15"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "stable",
    "prefer-stable": true,
    "config": {
        "allow-plugins": {
            "composer/installers": true,
            "drupal/core-composer-scaffold": true,
            "drupal/core-project-message": true,
            "dealerdirect/phpcodesniffer-composer-installer": true
        },
        "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/profiles/custom/{$name}": [
                "type:drupal-custom-profile"
            ],
            "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/installing-drupal",
                "  * 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"
            ]
        }
    }
}

```

---
Tags: 9, composer, upgrading
---


# Question
Title: Migrate webform directory with Composer from manual installation
I'm started drupal project (core 9.5.2) installing modules manually (it is not good, i know). After the website is deployed in production, I made changes for configuring composer and all worked well.

As new versions of modules come out, I install them through composer. I use composer require (and the module is installed in /modules/contrib) and then I remove the module folder in /modules, clear the cache and everything works fine. I did this with several modules, such as: ctools, icme, panels, slick, symfony\_mailer and others. However, when trying to perform this procedure with the webform, things do not go well (error below). I know that correct way would be to uninstall the module and reinstall it with composer, however, I would lose all the forms created, and all submissions already made. Is there a workaround for this problem?

```
The website encountered an unexpected error. Please try again later.
Error: Class "Drupal\webform_ui\PathProcessor\WebformUiPathProcessor" not found in Drupal\Component\DependencyInjection\Container->createService() (line 259 of core/lib/Drupal/Component/DependencyInjection/Container.php).

Drupal\Component\DependencyInjection\Container->createService() (Line: 177)
Drupal\Component\DependencyInjection\Container->get() (Line: 434)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() (Line: 273)
Drupal\Component\DependencyInjection\Container->createService() (Line: 177)
Drupal\Component\DependencyInjection\Container->get() (Line: 434)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() (Line: 237)
Drupal\Component\DependencyInjection\Container->createService() (Line: 177)
Drupal\Component\DependencyInjection\Container->get() (Line: 434)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() (Line: 237)
Drupal\Component\DependencyInjection\Container->createService() (Line: 177)
Drupal\Component\DependencyInjection\Container->get() (Line: 136)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch() (Line: 145)
Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 81)
Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 58)
Drupal\Core\StackMiddleware\Session->handle() (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass() (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 23)
Stack\StackedHttpKernel->handle() (Line: 713)
Drupal\Core\DrupalKernel->handle() (Line: 19)

```

I tried clear cache with "drush cc" but have same error.

# Answer
> 0 votes
After install module via composer (/modules/contrib/webform) and remove manually /modules/webform, execute:

```
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_config;
TRUNCATE TABLE cache_container;
TRUNCATE TABLE cache_data;
TRUNCATE TABLE cache_default;
TRUNCATE TABLE cache_discovery;
TRUNCATE TABLE cache_dynamic_page_cache;
TRUNCATE TABLE cache_entity;
TRUNCATE TABLE cache_library;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_render;
TRUNCATE TABLE cache_toolbar;

```

If you use drush, u can use: `drush cache-rebuild`

---
Tags: webforms, composer
---


# Question
Title: How to programmatically invalidate the cache of every node
I have a form submit function that is meant to invalidate the cache of every node if a specific field is altered. Here's how I'm attempting it.

```
$config = $this->configFactory
  ->getEditable('my_config.settings')
  ->get();
if ($form_state->getValue('global')['header_button'] != $config['global']['header_button']){
  // Header Button Changed
  \Drupal\Core\Cache\Cache::invalidateTags(['node_list']);
}

```

From what I've researched I assumed `\Drupal\Core\Cache\Cache::invalidateTags(['node_list']);` would invalidate the cache on every node, but the changes to the nodes are not appearing to anonymous users. Not sure if it matters but the change that is made affects what is rendered in `region--header.html.twig` rather than `node.html.twig`.

I've looked at How do I invalidate the cache of an entity? but the answers there did not work.

# Answer
> 1 votes
The `node_list` cache tag is indeed invalidated by every node change but it's not the other way, that it invalidates every node. The cache tag is only added to the result of node entity queries, not to single nodes.

For a configuration change, it's OK to invalidate the entire render cache, at least for a typical configuration option not changed in the normal operation of the website. For example, Drupal core does the same when theme settings are saved. This is not as time-consuming as clearing the entire Drupal cache:

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

```

---
Tags: 9, caching
---


# Question
Title: Setting SameSite=None on a session cookie
I have a custom endpoint which stores a value in a session cookie, using this code:

```
$session = $this->request->getCurrentRequest()->getSession();
$session->set('test.email', $data['email']);

```

I'm calling this endpoint from a decoupled frontend.

This works fine in Firefox, but in Chrome it looks like the session cookie is being blocked because SameSite is set to Lax. How would I set SameSite to be None? Ideally I only want to do that for this cookie, not all cookies.

# Answer
You can change the session cookie settings in services.yml. See How do I set the cookie lifetime?

This is not only possible for the default parameters defined by Drupal but for any parameter listed in the PHP docs:

https://www.php.net/session.configuration

So you can add SameSite=None to the session storage options:

*sites/default/services.yml*

```
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 100
    gc_maxlifetime: 200000
    cookie_lifetime: 2000000
    sid_length: 48
    sid_bits_per_character: 6
    cookie_samesite: none

```

These options only apply to the session cookie, not to any cookie set by your site. To change the options dynamically see How do I dynamically change cookie\_lifetime?
> 3 votes

---
Tags: 9, cookies
---


# Question
Title: Is there a way to programmatically add translations for strings?
Is there a way to programmatically add translations for strings (user interface translation), for example in `hook_update_N()`?

With Drupal 7, I could use the following code.

```
/**
 * Helper to manually add a single translation string.
 *
 * After adding strings use locale_clear_cache() for clearing caches.
 */
function locale_add_translation($source, $langcode, $translation, $context = '', $textgroup = 'default') {
  require_once DRUPAL_ROOT . '/includes/locale.inc';

  $report = &drupal_static(__FUNCTION__, array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0));
  _locale_import_one_string_db($report, $langcode, $context, $source, $translation, $textgroup, 'Manual import via helper ' . __FUNCTION__ .'().', LOCALE_IMPORT_OVERWRITE);
}

/**
 * Helper to clear the locale cache.
 */
function locale_clear_cache() {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  // Clear locale cache.
  _locale_invalidate_js();
  cache_clear_all('locale:', 'cache', TRUE);
}

```

# Answer
Put the following helper function in your custom module.

```
use \Drupal\locale\SourceString;

function mymodule_add_translation($source_string, $translated_string, $langcode) {
  // Find the existing source string.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(array('source' => $source_string));
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // Create the translation. If it already exists, it will be replaced.
  $storage->createTranslation(array(
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ))->save();
}

```
> 14 votes

# Answer
Here is a function to create plural translations.

```
use Drupal\Component\Gettext\PoItem;
use Drupal\locale\SourceString;

function mymodule_add_plural_translation(array $source_strings, array $translated_strings, string $langcode): void {
  /** @var \Drupal\locale\StringStorageInterface $storage */
  $storage = \Drupal::service('locale.storage');

  $source_string = implode(PoItem::DELIMITER, $source_strings);

  $string = $storage->findString(['source' => $source_string]);

  // If the string is not yet translated, create a new source string.
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }

  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation([
    'lid' => $string->lid,
    'language' => $langcode,
  ]);
  $translation->setPlurals($translated_strings);
  $translation->save();
}

```

Use it like this:

```
$source_strings = [
  'Discounted product',  // Singular string first.
  'Discounted products', // Plural string second.
];
$translated_strings = [
  'Reduziertes Produkt', // Singular string first.
  'Reduzierte Produkte', // Plural string second.
];
$langcode = 'de';

mymodule_add_plural_translation($source_strings, $translated_strings, $langcode);

```
> 1 votes

# Answer
Another sample with string context, like from `$this->t('Weight', [], ['context' => 'Physical weight'])`.

```
use Drupal\locale\SourceString;

/**
 * Fix "weight" translation.
 */
function MYMODULE_update_N(&$sandbox) {
  $source_string = 'Weight';
  $context = 'Physical weight';
  $langcode = 'de';
  $translated_string = 'Gewicht';

  // Find existing source string. If it doesn't exist, it will be created.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(['source' => $source_string, 'context' => $context]);
  if (is_null($string)) {
    $string = new SourceString();
    $string
      ->setString($source_string)
      ->setValues(['context' => $context])
      ->setStorage($storage)
      ->save();
  }

  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation([
    'lid' => $string->getId(),
    'language' => $langcode,
    'translation' => $translated_string,
    'context' => $context,
  ])->save();
}

```
> 0 votes

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


# Question
Title: I'm trying to configure memcache module and failed to load dmemcache.inc
Anybody could have an Idea why I get this error Failed to load required file sites/all/modules/memcache/dmemcache.inc.

I installed memcache properly on my server, but when I go to drupal Report, I got the above message

I'm using drupal 7

```
This is from my PHPInfo()
memcached
memcached support   enabled
Version     2.1.0
libmemcached version    1.0.8
Session support     yes
igbinary support    no
json support    no

Directive   Local Value Master Value
memcached.compression_factor    1.3 1.3
memcached.compression_threshold 2000    2000
memcached.compression_type  fastlz  fastlz
memcached.serializer    php php
memcached.sess_binary   0   0
memcached.sess_lock_wait    150000  150000
memcached.sess_locking  1   1
memcached.sess_prefix   memc.sess.key.

```

\**** UPDATE \**** in order to make it work, I added that to the settings file

```
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;

```

thanks a lot

# Answer
> 7 votes
Modifications to settings.php are required. Read the docs on how to configure it. Here is an example configuration I use with two memcached servers:

```
$conf['memcache_key_prefix'] = __FILE__;
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;
$conf['memcache_servers'] = ['172.16.12.51:11211' => 'default', '172.16.12.52:11211' => 'default'];

```

# Answer
> 0 votes
In my case there was a problem with the `domain` module which required to include in *settings.php* line:

```
include_once DRUPAL_ROOT . '/sites/all/modules/domain/settings.inc';

```

As it is internally calling `drupal_bootstrap()` then every change of `$conf` after that line is ignored. Solution was to define `$conf` variables before the mentioned line.

---
Tags: caching
---


# Question
Title: Is there a simple way to add a core themes css file to your custom theme?
Is there a way to declare a css dependency in a custom themes libraries.yml similar to adding core js dependencies?

If I can avoid it, I'd rather not just copy a core themes css into my custom theme in Drupal 9 (more specifically latest Drupal 9.5.2)

I tried under dependencies to add a css file from a core theme but it doesn't do anything. So I'm guessing that isn't the way to do it or I wrote it incorrectly.

What I tried was:

```
global-components:
  version: 1.x
  css:
    theme:
      css/theme-global.css: {}
      css/custom.css: {}
  js:
    js/theme-global.js {}
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
    - core/themes/claro/css/components/pager.css

```

Note the last line: attempting to include claro themes pager.css!

Now this didn't break anything, but it also didn't include pager.css in my theme (so obviously this is not the way)

I've spent about an hour searching anyway I could think of without finding an answer - I'm assuming dependencies don't/won't work like this.

Is there a css equivalent to dependencies?

I did also try adding the same path under css: -\> theme: followed by : {} which just produced a 404 error because it looked in my theme for directory core/themes/claro/css/components "which obviously doesn't exist."

It's the only css I want from that theme so it would be overkill to add claro as a base theme to my custom theme.

For now I've copied the file into my themes css directory to be able to use it. However I feel there has to be a better more Drupal like way - is there?

# Answer
> 2 votes
I think you should be able to reference this file directly starting with a slash like that:

```
global-components:
  version: 1.x
  css:
    theme:
      css/theme-global.css: {}
      css/custom.css: {}
      /core/themes/claro/css/components/pager.css: {}
  js:
    js/theme-global.js {}
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

Flush cache.

---
Tags: theming
---


title: How do I install the database drivers?

text:
# Question
Title: How do I install the database drivers?
I'm trying to use Drupal 9 framework, and I'm stuck when setting up the database: I get the infamous error `Error: Class 'Drupal\pgsql\Driver\Database\pgsql\Connection' not found`.

When looking at the Drupal Core module `composer.json`, I see that the module expects a `drivers` directory to exist under `vendor/drupal`:

```
"autoload": {
        "psr-4": {
            "Drupal\\Core\\": "lib/Drupal/Core",
            "Drupal\\Component\\": "lib/Drupal/Component",
            "Drupal\\Driver\\": "../drivers/lib/Drupal/Driver"
        },

```

Which seems to be confirmed by this issue:

https://www.drupal.org/node/3129492

Which clearly establishes that Database drivers are now provided by their own dedicated module.

The question is: where is this module and how can it be installed? I searched packagist for `drupal/drivers` but it doesn't exist.

# Answer
> 2 votes
> where is this module and how can it be installed?

It's not a single module containing all the drivers - each driver has its own module, already included with core.

For Postgres that's the `pgsql` module (for MySQL it's `mysql`). That's the module you need to enable, nothing else to download.

---
Tags: 9
---


title: Naming conventions for permissions

text:
# Question
Title: Naming conventions for permissions
Looking through the Drupal coding conventions on Coding standards / Naming Conventions, I have seen module, variable, function, and many other areas but not for permission names.

Is there any convention to avoid creating permission names that might interfere with others?

# Answer
AFAIK there's no official recommendations.

Given that all permissions share the same namespace it's a good idea to avoid generic names. You can include the name of the module that defines the permissions to minimize collision risk.
> 1 votes

# Answer
The Drupal coding standards do not say how permissions should be named, especially to avoid collisions between permissions defined from different projects.

The permission names used by Drupal core follow the schema `<verb> <object>`, as *administer users*, *view user email addresses*, *administer nodes*, and *administer content types*.
Usually, `<object>` is derived from the module name, and that avoids conflicts, but that is not always true.
> 0 votes

---
Tags: coding-standards
---


# Question
Title: ReCaptcha doesn't show on Simplenews Subscription Block
I have the subscription form of Simplenews in the footer, which should be protected with reCaptcha. I installed reCaptcha and created a captcha point with the form ID of the Simplenews block. Unfortunately, I don't see the recaptcha on the Simplenews registration block in the footer.

What am I doing wrong?

# Answer
I was able to fix the problem. The ID of the form was too long. It seems that the ID can be a maximum of 64 characters long.
> 2 votes

---
Tags: 8, captcha
---


# Question
Title: Getting the image URL from a field_image on a node
So I have this Node:

```
object(Drupal\node\Entity\Node)[1862]
  protected 'values' =>
    array (size=17)
      'vid' =>
        array (size=1)
          'x-default' => string '7' (length=1)
      'langcode' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=1)
                  'value' => string 'en' (length=2)
      ... (more fields)
      'field_image' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=5)
                  'target_id' => string '1' (length=1)
                  'alt' => string '' (length=0)
                  'title' => string '' (length=0)
                  'width' => string '150' (length=3)
                  'height' => string '120' (length=3)

```

Now the field\_image has an array with x-default and some basic image data. How do I show the image, or create a link to the image inside the Twig template?

# Answer
Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment.

```
{{ file_url(node.field_image.entity.fileuri) }}

```
> 67 votes

# Answer
I don't know about Twig, but you get the file URI with `$node->field_image->entity->getFileUri()` in PHP, and the you need to call `file_create_url()` on that:

```
file_create_url($node->field_image->entity->getFileUri())

```

I don't know if that is possible in twig. If it's not possible, you can always calculate it in preprocess and add as a new variable.
> 51 votes

# Answer
If someone needed a styled image:

```
$styled_image_url = ImageStyle::load('large')->buildUrl($node->field_image->entity->getFileUri());

```
> 33 votes

# Answer
None of the above twig solutions worked for me (perhaps those worked for older 8.x versions but not for 8.5 version

```
{{ file_url(node.field_image['#items'].entity.uri.value) }}

```

NOTE: should be working for Drupal **8.5+**
> 16 votes

# Answer
This is the way if you want to get the image URL with the associated image style for any image field in a twig template:

First install the Twig Tweak module

Then set the image URI as a variable. With the URI, you can use a twig tweaks pattern to get the path with whatever image style you want. See below:

```
{% set image_uri = content.field_feature_row_image['#items'].entity.uri.value %}

<img src="{{ image_uri|image_style('image1200x1103') }}"/>

```

Twig Tweak v2.4+ offers `file_url` filter to extract file URL from an entity.

```
<img src="{{ node.field_image|file_url }}"/>

```

And as of Twig Tweak v2.6 you can use `file_uri` filter in conjunction with `image_style`.

```
<img src="{{ node.field_image|file_uri|image_style('image1200x1103') }}"/>

```
> 13 votes

# Answer
What ended up working for me in D8 is:

```
$imageUrl = $node->get('field_image')->entity->uri->value;

```

Using `kint($node->get('field_image')->entity)` and looking through the array was very helpful

Then in my twig file I used:

```
<img class="top-article-image" src="{{ file_url(imageUrl) }}" />

```
> 9 votes

# Answer
So I've found out the answer with the help of Clive.

Getting the image URI in a template file is done using `node.field_image.0.entity.uri.value`. Provide a Twig extension for `file_create_url()`, closed as fixed on January, 2015, made possible to use `file_url()` in a template file.

```
{{ file_url(node.field_image.0.entity.uri.value) }}

```
> 7 votes

# Answer
I'm always using a helper function

```
  /**
   * Get the Image URI.
   *
   * @param \Drupal\Core\Entity\Entity $entity
   * @param $fieldName
   * @param bool $imageStyle
   * @return mixed
   */
  public function getImageUri(\Drupal\Core\Entity\Entity $entity, $fieldName, $imageStyle = FALSE) {
    $imageField = $entity->get($fieldName)->getValue();
    if (!empty($imageField[0]['target_id'])) {
      $file = File::load($imageField[0]['target_id']);
      if ($imageStyle) {
        return ImageStyle::load($imageStyle)->buildUrl($file->getFileUri());
      }

      // Original URI.
      return file_create_url($file->getFileUri());
    }
  }

```
> 5 votes

# Answer
you can get the url directly by using field\_image.entity.url
> 2 votes

# Answer
I would highly recommend using the Twig Tweak module to get the URL from an image field in your twig template. Once you have installed the module you can then use various methods for extracting the URL from the image field. The following worked for me:

```
{{ node.field_main_image.0 | file_url }}

```

I set the background image of a `<div>` with the following:

```
<div style="background-image: url({{ node.field_banner_image.0 | file_url }})">
...
</div>

```

**Make sure to add style for width and height or you won't see if it's working**

**IF THIS DOES NOT WORK FOR YOU**, or if you want to learn all about the other great things twig tweak can do, reference this cheat sheet. This helpful document will save you a ton of time. I wish I knew about it earlier.
> 2 votes

# Answer
Gosh, it actually took my ages to find out why my resulting URLs didn't work. The all 404'ed. **You need to create a derivate first if it doesn't already exist**.

So for example when you add an image style later, after the original image was uploaded, then there's no styled image file yet (the image derivate). It needs to be created first.

Replace `field_MYIMAGE` and `MYSTYLE` as you need.

```
$original_image = $node->field_MYIMAGE->entity->getFileUri();
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('MYSTYLE');

$destination = $style->buildUri($original_image);
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}

$url = $style->buildUrl($original_image);

```

---

I wish this would happen automatically.
> 1 votes

# Answer
To Get image attribute like URI, alt, title etc use the syntax like below template wise

In node twig template

```
{{node.field_name.entity.fileuri}}

```

In field twig template

```
{{content.field_name.entity.fileuri}}

```

In other field twig template

```
{{element['#object'].field_name.entity.fileuri}}

```

**Note:** Also check twig\_tweaks module cheat sheet for detail related to twig related issue.
> 1 votes

# Answer
This adds a drupal image style and the image alt test

```
{{ file_url(content.field_featured_image|field_target_entity.field_media_image.entity.uri.value| image_style('featured_image')) }}" alt="{{ content.field_featured_image|field_target_entity.field_media_image.alt }}

```
> 1 votes

# Answer
I'll probably thank me in the future:

```
content.field_name['#items'][0]|file_uri|image_style('style_name')

```

(with Twig Tweak)
> 1 votes

# Answer
somewhat related, here is what I used (thanks to all previous answers to get me there) to get an image file URL from a media entity's image field in twig:

```
{% set media_img_url = file_url(content.field_media_image.0['#item'].entity.uri.value) %}

```

now I can use this variable in my twig template

```
{{ media_img_url }}

```
> 0 votes

# Answer
You can use the `url()` method that is on the File class as a shortcut so:

```
{{ file_url(node.field_image.entity.fileuri) }}

```

can be shortened to:

```
{{ node.field_image.entity.url }}

```

This works in preprocess functions but triggers a `Twig_Sandbox_SecurityError` when called in a twig template.

If you receive `Twig_Sandbox_SecurityError` you can tell twig to allow `url` in your settings.php file as mentioned in this Stackoverflow post

See documentation on File::Url() https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/function/File%3A%3Aurl/8.6.x
> 0 votes

# Answer
Just noting: use file\_uri, not file\_url.

```
{{ node.field_image|file_uri|image_style('content_header') }}

```
> 0 votes

---
Tags: 8, media
---


# Question
Title: How to print custom date format in Twig?
How can I print a custom date format in Twig? First of all my I am trying to edit the `field.html.twig` of the field called `field_publication_date`, in that file I find this variable `{{ item.content }}` which prints `Jun, 12/06/2016 - 12:29`.

This is what I have tried: `{{ item.content.field_publication_date|format_date('M') }}`

# Answer
> 19 votes
**Try to use this** -

```
{{ item.content.field_publication_date|date("M") }}

```

But, I think you will get your solution in

```
{{ item.content|date("M") }}

```

Where `item.content` contains the date string inside **field--node--field-publication-date.html.twig**.

# Answer
> 24 votes
First, create the custom date format `my_custom_date_format` in the configuration section of the drupal admin.

Second, use the `format_date` Twig filter, like here:

```
{{ node.created.value|format_date('my_custom_date_format') }}

```

It might be necessary to convert the date to a unix timestamp, first. That will look like this:

```
{{ node.my_date_field.value|date('U')|format_date('my_custom_date_format') }}

```

# Answer
> 5 votes
The `\Drupal\datetime\Plugin\Field\FieldType\DateTimeItem` has a value and a date property. The `value` is UTC and the `date` is computed. Use the date property to avoid having to deal with the timezone, and you can use a created format or a custom one:

`{{ node.field_publication_date.date|format_date('custom', 'F j, Y') }}`

Date format in Drupal:

`{{ node.field_publication_date.date|format_date('my_custom_date_format') }}`

# Answer
> 4 votes
None of the above answers worked when setting a datetime attribute on a time element. the closest was @Marcos Buarque's answer.

Instead of a formatted date, the rendered output would either print the unix timestamp or a wrongly-formatted date like "2020-09-03ADT00:00:00".

In order to get the proper format for a full date time, I couldn't use `Y-m-d\TH:i:s` or `Y-m-dTH:i:s`. I needed to split the format into two variables. This is probably some quirk with format\_date and twig.

```
{% set htmlDate = node.getCreatedTime|format_date('custom', 'Y-m-d') %}
{% set htmlTime = node.getCreatedTime|format_date('custom', 'H:i:s') %}
<time datetime="{{ htmlDate }}T{{ htmlTime }}">{{ date }}</time>

```

# Answer
> 3 votes
I know this question refers specifically to formatting the value of a given date field, but I needed to format the date the node was created. In case you need that, this is what works for me (after trying several different options):

```
{{ node.getCreatedTime|format_date('medium') }}

```

This is where I got this solution from: https://www.drupal.org/forum/support/theme-development/2016-02-17/how-to-get-formatted-node-creation-date-in-d8#comment-10865464

# Answer
> 1 votes
This worked for me. The date value with twig's own date() format function:

```
{{ content.field_arrival_date.value | date("Y/m/d") }}

```

# Answer
> 1 votes
To convert from a DateTime string (e.g. `2022-03-03T01:53:06`) in UTC to the current timezone, I had to use:

```
{{ (datetimeStr ~ '+00:00')|date('U')|format_date('medium') }}

```

# Answer
> -1 votes
You can modify your **Authored on** date format in your custom node twig

`{{ item.content|date("F j, Y") }}`

You will get the result like this **January 30, 2023**

---
Tags: theming, 8, datetime
---


title: Fetch select label via GraphQL

text:
# Question
Title: Fetch select label via GraphQL
My nodes have an "articleType" property, which is a select field with ~10 options ("article|Article", "training|Web based training" etc).

Fetching the property via GraphQL (8.x-3.1) works, but this gives me the key of the selected option (`training`):

```
    [...]
    results {
      entityLabel
      ...on NodeArticle {
        fieldArticleType
      }
    }
    [...]

```

I would like to retrieve the label of the selected option (`Web based training`). How can I do that?

(Related, but without GraphQL: How to access a selected label instead of value)

# Answer
I solved it by adding a new GraphQL field:

```
<?php

namespace Drupal\mymodule\Plugin\GraphQL\Fields;

use Drupal\graphql\GraphQL\Execution\ResolveContext;
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
use Drupal\node\Entity\Node;
use GraphQL\Type\Definition\ResolveInfo;

/**
 * Returns the label for the "article type" field
 *
 * Example: "Themendossier" label instead of "dossier" key.
 *
 * @GraphQLField(
 *   id = "article_type_label",
 *   type = "String",
 *   name = "articleTypeLabel",
 *   nullable = true,
 *   multi = false,
 *   parents = {"NodeArticle"}
 * )
 */
class ArticleTypeLabel extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function resolveValues(Node $value, array $args, ResolveContext $context, ResolveInfo $info) {
    $options = $value->field_article_type->getFieldDefinition()->getFieldStorageDefinition()
        ->getSetting('allowed_values');

    yield $options[$value->field_article_type->value];
  }
}

```
> 0 votes

---
Tags: 9
---


# Question
Title: My log is filling up with "Missing filter plugin: filter_null." messages
When I googled for this error, I found numerous hits mentioning the error message appearing during a migration, even stopping it. While I have done a migration from Drupal 7 to 9 that ran smoothly, this is during normal running of the now Drupal 9-based site.

E.g. I create a new content. As soon as I select the content type and the content form appears, I get this error. So it is probably not related to text formats.

I have no idea how to provide the missing filter plugin. I searched a database dump and found several occurrences of "filter\_null". Most notably in the tables "config", "key\_value" and "key\_value\_expire"(!).

But I did not find "filter\_null" or any other "filter\_\<something"\> in the Drupal user interface. I did find code related to it, most notably the file `core/modules/filter/src/Plugin/Filter/FilterNull.php`.

Can anyone tell me the trick to provide that filter? I'm still running 9.3.7, installing 9.3.8 is next on my agenda. But it does not look like there is any changed that relates to this error.

# Answer
This is what happens when a filter in the Drupal 7 site doesn't exist in the Drupal 9 site: It gets replaced in the configuration by a *filter\_null* reference. If you need the functionality of the missing filter, you should find a Drupal 9 equivalent and install it.

To solve your immediate problem, you can very easily remove the *filter\_null* references by simply editing each of your text formats listed on *Administration \> Configuration \> Content authoring \> Text formats and editors* and saving them. There is no need to make any change; just click on the *Save* button.
> 8 votes

# Answer
If you work with the Drupal config files, you can check files such as config/filter\_format\*.yml

You can replace the filters value from

```
filters:
  filter_null:
    id: filter_null
    provider: filter
    status: true
    weight: 0
    settings: {  }

```

to

```
filters: { }

```

Then import back the config (drush cim).
> 2 votes

# Answer
Go to /admin/config/content/formats and ensure that all of your text editors read CKEditor. That corrected it for me as many were reading "none" after migration.
> 0 votes

---
Tags: migrations, 9
---


# Question
Title: Javascript "once is not a function" errors after library include
I have a small module which contains the javascript library JSmol. This library renders molecular structures onscreen. The main module is called jmol. It contains an element, a twig template, a small javascript file, and the official JSmol library.

When I create an element on the page the element renders correctly, but the admin toolbar does not. Javascript console highlights 4 places that the "once" function is used, all in the code after the vendor library was included. One example is this:

TypeError: $(...).once is not a function

```
  Drupal.behaviors.escapeAdmin = {
    attach: function () {
      var $toolbarEscape = $('[data-toolbar-escape-admin]').once('escapeAdmin');

```

my javascript file is quite simple:

```
(function ($, Drupal, drupalSettings, Jmol) {
  'use strict';
  Drupal.behaviors.jmol = {
    attach: function () {
      var Info = drupalSettings.jmol.mydiv.info;
      $('#mydiv').html(Jmol.getAppletHtml("jmolApplet0", Info))
    }
  };
}(jQuery, Drupal, drupalSettings, Jmol));

```

Is it possible that the vendor code breaks this, or is it something that I have done?

Edit: here's my jmol.libraries.yml file:

```
jmol:
  version: 1.x
  js:
    lib/JSmol.min.js: {}
    js/jmol.js: {}
  dependencies:
    - core/drupalSettings
    - core/jquery
    - [I've tried adding core/jquery.once here to no avail]

```

# Answer
I had this happen in my custom module as well. I then noticed it worked when logged in but once I was unauthenticated my code would throw this JS error. In the end it was simply an issue where I needed the dependency you listed already in my custom module library file dependencies:

```
dependencies:
- core/drupalSettings
- core/jquery
- core/jquery.once

```

Once I added this the required JS file was included when unauthenticated as well.

For a little extra information that forced the following JS file to be included as well:

It looks like you solved your specific instance which ended up being multiple versions of jQuery being installed. I would avoid that if possible as it complicates things a bit.
> 21 votes

# Answer
As we go from d9 to d10, modules are starting to remove the jquery.once dependency en masse. When a site has finally upgraded all of their modules, the dependency will be gone and any custom code that was using .once will no longer work. Anyone searching for this issue should refer to https://www.drupal.org/node/3158256 where it shows us that it's not enough to just swap out the libraries reference, but also to change how the function is used in the code itself.
> 2 votes

# Answer
I'm not a Drupal 8 guy just yet. Still very much using 7 However I did find some items that may be helpful.

`once()` is not a core jquery method. I think it's a jquery plugin made for drupal 7 (Source). I don't know if this plugin is included in Drupal 8.

Is this library meant to work on drupal 7 and not fully ported to drupal 8?

A simple version of `once()` I built for my own (non drupal) site looks like:

```
$.fn.once = function(processed_class)
{
  if (typeof processed_class == 'undefined')
  {
    processed_class = 'processed';
  }
  return this.not('.' + processed_class).addClass(processed_class);
};

```

You could add this to your code outside of any document.ready or drupal.behaviors stuff (global scope) and it may work. You may also need to include your js file before your plugin.

As for your errors and missing menu a single javascript error can block the remaining javascript form loading on the page. As admin toolbar is js it's probably never getting called.
> 0 votes

---
Tags: 8
---


# Question
Title: Is there a way to validate access & refresh tokens issued using the Simple OAuth module?
I am using the OAuth2 authorization code grant with the Simple OAuth module. Everything is working, however I would like to be able to validate access and refresh tokens from my frontend NodeJS server. Is there an API endpoint to which I can send a token to, and in the response I get information about that token (aka token introspection)? For example, a response telling me the token is expired.

Thanks for all the help in advance, and let me know if I need to clarify the question in any way!

# Answer
I am fairly sure the answer is "no". There is no such route provided by the module.

At this stage this looks like a feature request for the module.
> 1 votes

---
Tags: authentication-authorization
---


# Question
Title: Form builder not getting checkbox values
I cannot determine why the form state seems to fail to get the values of the checkboxes on a form I'm building.

In my `buildForm()`, after submission, I am returning a result set. Each result that is built includes a checkbox form element.

```
$form['main_container']['grid'] = [
  '#type' => 'container',
];

foreach ($title_list as $title => $row) {

  //...some code here...

  $form['main_container']['grid'][$row['div_id']] = [
    '#type' => 'fieldset',
    '#collapsible' => FALSE,
    '#attributes' => [
      'class' => [
        'grid-item-fieldset',
      ],
      'id' => $row['div_id'] . '-fieldset',
    ],
  ];

  $form['main_container']['grid'][$row['div_id']][$row['cn'] . '-selector'] = [
    '#type' => 'checkbox',
    '#return_value' => $row['div_id'],
    '#attributes' => [
      'class' => [
        'item-selector',
      ],
      'id' => $row['div_id'] . '-selector',
      'name' => 'cn-' . $row['cn'],
    ],
    '#default_value' => $row['div_id'],
  ];
}

```

With this rendering, I tried to get the value using `$form_state->getValue($row['cn'] . '-selector);` to get the value after submission and all I can get is `NULL`, despite the fact that the UI of the form confirms the boxes are checked.

I have also tried adding the #tree property to the 'grid' element (shown below), then using `$form_state->getValue([$row['div_id'], $row['cn'] . '-selector']);` and this also resulted in `NULL`.

```
$form['main_container']['grid'] = [
  '#type' => 'container',
  '#tree' => TRUE,
];

```

When I dump the `$form_state->getValues()` with Kint using Devel after the form's been rebuilt, I can see all the checkbox values, but they all have the value of `0`, despite their value being set.

Does anyone have any insight into why I'm unable to get these values from the form state despite them existing in the form and being checked in the UI?

# Answer
**It's due to overriding the name attribute.**

Drupal's `$form_state` relies on this name, so it needs to have the specific name that is automagically determined by the Form API.

Remove `'name' => 'cn-' . $row['cn'],`
> 1 votes

---
Tags: forms, 9
---