# Question
Title: Where is it documented that fields included in the entity_keys are 'required' regardless of the required property value in the field definition?
I've created a custom entity. One of the fields I've added is an entity reference field that was created calling `BaseFieldDefinition::setRequired(FALSE)`. When I installed my module and tried to add a new instance of my custom entity, I got an error when that field was not set, even though it was defined as not required.

For reference, this is the field definition I'm using.

```
$fields['publisher'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Publisher'))
  ->setRequired(FALSE)
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings', array(
    'target_bundles' => array(
      'publisher' => 'publisher'
    ),
    // 'sort' => array(
    //  'field' => 'name'
    // )
  ))
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'title' => t('Pubs'),
    'type' => 'options_select',
    'weight' => 4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

This is the error I got.

> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'publisher' cannot be null: INSERT INTO "series"...

The database table for this custom entity contains the following fields.

>

It's evident that, even though this field has been created calling `setRequired(FALSE)`, it must be set.

To solve this issue, I found that I can manually update my database table's properties so that the field's 'Null' property is set to 'Yes', though this is clearly not a preferred approach.

Then I found How do I allow an entity reference to be null in my custom entity? where one of the answer states that fields included in the *entity\_keys* annotation must be set, regardless of the value set with `setRequired()`.

Where is this kind of information documented?

This isn't documented in Creating a content entity type in Drupal 8. In fact, I had the impression it was mandatory to list all the fields in this annotation array.

# Answer
The Drupal documentation - as the Drupal source code itself - has been provided by the contribution of the Drupal developer community. You will find, that it oftentimes isn't 100% complete nor up-to-date, as many of the developers ensure that code is working and more or less documented in the source code, but neglect the online documentation a bit while going on solving other issues or implementing different features. The documentation you mentioned even has a banner stating

> This documentation needs work. See "Help improve this page" in the sidebar.

An experienced Drupal developer "just knows" such details from previous encounters with similar issues. If not sure, such a developer would also search the Drupal code base to see how the properties are used. Thanks to generally applied coding standards, extended source code documentation, and search features of modern IDEs, it's quite easy to read the Drupal code for any PHP developer; even easier for those that work with Drupal on a daily base.

If the source code doesn't offer answers, this StackExchange group or using a proper search engine may help to answer some Drupal questions relatively quick as well. The best explanation I found using a simple search is a citation from Daniel Siphos excellent "Drupal 8 Module Development" book:

> **Entity keys**
> The entity API defines a set of keys that are consistent across all entity types and by which common entity information can be retrieved. Since not all entity types need to have the same fields for storing that data, there is a mapping that can be done in the annotation for these

Which means, that the annotation property `entity_keys` is there to translate commonly used properties of entities (such as their ID, label or bundle) to their corresponding database fields that may be named differently for any entity type (e.g., `nid`/`pid`/..., `title`/`name`/..., `type`/`variant`/...). This allows the entity API to define common getter methods like `::id()`, `::getLabel()` or `::bundle()` that can be used throughout the entire Drupal application in entity listing classes, the fields API, condition plugins, and so on, and therefore *shouldn't* be empty.

If you ever encounter a piece of Drupal documentation that appears to be incomplete, is missing cruicial information, or lacks information that the original contributors of the documentation page didn't deem worth mentioning, you can

* Log in, click Edit, and edit this page
* Log in, click Discuss, update the Page status value, and suggest an improvement
* Log in and create a Documentation issue with your suggestion

(Shamelessly copied from the sidebar of beforementioned article in the Drupal documentation. ;)
> 3 votes

# Answer
There isn't any documentation about that.
In `SqlContentEntityStorageSchema::getSharedTableFieldSchema()`, there is the following comment. (The relevant part is *For now, we only hardcode 'not null' to a few "entity keys", in order to keep their indexes optimized.*)

```
// A shared table contains rows for entities where the field is empty
// (since other fields stored in the same table might not be empty), thus
// the only columns that can be 'not null' are those for required
// properties of required fields. For now, we only hardcode 'not null' to a
// few "entity keys", in order to keep their indexes optimized.
// @todo Fix this in https://www.drupal.org/node/2841291.

```

Fix NOT NULL handling in the entity storage and 'primary key' changes when updating the storage definition of an identifier field has been opened to remove the code that mark as `NOT NULL` some of the entity keys given for an entity type.

As a side note, the current workaround isn't to manually edit the database schema, but to override the `getSharedTableFieldSchema()` method implemented by the entity *storage\_schema* handler.
This is what done by the `File` entity type, for example.

```
handlers = {
  "storage" = "Drupal\file\FileStorage",
  "storage_schema" = "Drupal\file\FileStorageSchema",
  "access" = "Drupal\file\FileAccessControlHandler",
  "views_data" = "Drupal\file\FileViewsData",
},
base_table = "file_managed",
entity_keys = {
  "id" = "fid",
  "label" = "filename",
  "langcode" = "langcode",
  "uuid" = "uuid",
  "owner" = "uid",
}

```

`Drupal\file\FileStorageSchema::getSharedTableFieldSchema()` contains the following code.

```
// Entity keys automatically have not null assigned to TRUE, but for the
// file entity, NULL is a valid value for uid.
if ($field_name === 'uid') {
  $schema['fields']['uid']['not null'] = FALSE;
}
return $schema;

```
> 3 votes

---
Tags: database
---


title: Trouble adding modules with Composer

text:
# Question
Title: Trouble adding modules with Composer
I created a Drupal 8 site through the manual install process and configured the site through the admin UI for a while. However, I quickly discovered how critical it was to use Composer to add modules due to the prevalence of third-party libraries. But I am getting the following error whenever I try to add any new module, and I will use Drupal Commerce module as an example (note that my production site is currently housed in the /public\_html/main directory):

```
username@mydomain.com [~/public_html/main]# php
/home3/username/public_html/composer require drupal/commerce
Using version ^2.7 for drupal/commerce
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 14 installs, 1 update, 0 removals
 - Installing drupal/coder (8.2.12): Cloning 984c54a7b1 from cache

[RuntimeException]
Failed to execute git clone --no-checkout
'/home3/username/.composer/cache/
vcs/https---git.drupal.org-project-coder.git/'
'/home3/username/public_html
/main/vendor/drupal/coder' --dissociate --reference
'/home3/username/.compo
ser/cache/vcs/https---git.drupal.org-project-coder.git/' && cd
'/home3/username/public_html/main/vendor/drupal/coder' && git remote
set-url origin
'https://git.drupal.org/project/coder.git' && git remote add composer
'https://git.drupal.org/project/coder.git'

Cloning into '/home3/username/public_html/main/vendor/drupal/coder'...
done.
fatal: unable to create thread: Resource temporarily unavailable
fatal: cannot repack to clean up

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--
no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-
with-dependencies] [--update-with-all-dependencies] [--ignore-platform-
reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--
optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader]
[--] [<packages>]...

```

Thanks for any help.

# Answer
> 1 votes
I have successfully battled this error into submission over the past six hours.
I pieced together what I believe were the contributing problems and found a way for things to work correctly in a remote hosted (Bluehost) Drupal installation.

1. You must be able to use composer commands. If composer is not installed on your remote host, you will need to install ssh and then install composer. SSH lets you use command line typing so you can interact/execute composer commands
2. login to composer (I opened up Windows powershell and used SSH from there). You will be challenged to put in your password for ssh the first time you use it. If you have it configured tightly, you will be asked everytime.
3. `cd www/your-drupal-directory` If you don't start off in the drupal directory, you will not get code dropped into modules/contrib which means nothing will show up in your administration 'install' link from your site. Specifically, you login into composer and then just type the command and hit enter. You'll then see your composer line now has your drupal path showing. My path was www/d8 because Bluehost serves pages from www and I installed drupal in the d8 subdirectory. I'm sure public\_html would have worked as well.
4. Commerce requires more than one module to run properly. When you visit the Commerce installation page, pay careful attention to the Ludwig installation information. The list of seven dependent modules is there. You will need to be sure each dependent module is installed (some may already be installed).
5. `--update-no-dev` is the key to success. Adding this option on your composer command will stop the addition of development packages during your module install. A composer command for the general commerce package would be `composer require drupal/commerce --update-no-dev` then hit enter
6. Your next problem will be inconsistent 'stability' releases. I used the default settings when I installed composer. You can get around that problem by explicitly referencing the module version you want to install. For example, Commerce requires the Entity module. I used `composer require drupal/entity:1.0-beta4 --update-no-dev`

The issue of coder not being found seems to come from a difference between what is found in the composer.json file and the composer.lock file. The `update-no-dev` is telling composer not to require the drupal/coder (and other things)

I am no expert on composer or drupal development. I'm sure others can provide a more technical explanation. It is always a good idea to check for updates periodically for all installed modules and themes. You should have a report in your administration link on your site that gives you an idea of available updates.

# Answer
> 0 votes
Putting --update-no-dev to the failed composer packages works for me.

For example I was facing the same error while trying to install drupal with composer and was showing me this error in the package vlucas/phpdotenv and this fix the issue:

* cd to-your-drupal-path
* composer require vlucas/phpdotenv --update-no-dev

Works.

---
Tags: composer
---


# Question
Title: Ajax validation of file upload in Commerce Product with product attributes
I am building a shop with Drupal Commerce right now. I have a product that uses an Order item type, which supports a file upload. The same product also has some product attributes that load the product variations via Ajax. When I don't use a twig theme for full products view, everything works fine.

Even if I use a product--full.html.twig theme and just render {{ product }}, everything works fine. But when I start rendering the products parts like title, images, variations, body, etc... according to this documentation, Ajax validation of the upload file stopps working.

I just have a simple theme looking similar to this:

```
<div id="slideshow">
    {{ product.variation_field_product_images }}
</div>
<div id="sidebar">
    <span>{{ product.variation_price }}</span>
    <div>{{ product.variations }}</div>
</div>
<div id="product-body">
    <p>{{ product.body }}</p>
</div>

```

This all renders well and works like desired, until I add a product attribute like e.g. "color" which loads the products variations also via Ajax. When I then change the product products attribute/variation an Ajax-event is triggered and the Ajax validation of the upload field in the product variation (order item type) stopps working.

I'd be really happy, if someone could give me a hint, since I am not sure if I really should render the product variations as {{ product.variations }}, since many things in the above linked documentation don't seem to be correct anymore.

Thank you very much in advance

# Answer
> 1 votes
In the last step render the entire `product` variable and exclude the fields rendered before, even if there is only one field left to be rendered. By this you make sure any metadata attached to the variable gets rendered as well:

```
<div id="slideshow">
    {{ product.field_a }}
</div>
<div id="sidebar">
    <span>{{ product.field_b }}</span>
    <div>{{ product.field_c }}</div>
</div>
<div id="product-body">
    <p>{{ product|without('field_a', 'field_b', 'field_c') }}</p>
</div>

```

---
Tags: commerce, ajax, files, 9
---


title: How add conditional required field

text:
# Question
Title: How add conditional required field
**Need**:

If we select a value in a drop-down list field(A), then we need to display and set as required field(B).

**Note**: the field(B) is a date range.

I tried to add states with a hook form alter

```
$form['field_b']['#states'] = [
      'visible' => [
        ':input[name="field_a"]' => ['!value' => '_none']
      ],
      'required' => [
        ':input[name="field_a"]' => ['!value' => '_none'],
      ],
  ];

```

As you see I use: '!value' to negate a value and '\_none' for no value. So, It will not be required if there is no value selected

**This code didn't work.** It display the field B, but it is not mandatory.

We found that there is an issue with core https://www.drupal.org/project/drupal/issues/2855139

At the end issue was closed, but it didn't work for us. It worked with texte fields but not for our rage date.

# Answer
For required state you have to target the actual input as mentioned in Drupal documentation

Example:

```
$form['field_name']['widget']['0']['target_id'['#states'] = [
  'required' => [
    ':input[name="input_name"]' => ['value' => 'value']
  ],
];

```
> 1 votes

# Answer
So, if dont want to use conditional\_fields module and only conditional fields core You can do it, but required field have sometime a little bug.

In the issue someone take some code from conditional\_fields that fix this issue, and use it.

your\_module/js/conditional\_fields.js

```
(function ($, Drupal) {

// Fix core's required handling.
$(document).bind('state:required', function (e) {
  if (e.trigger) {
    var fields = $(e.target).find('input, select, textarea, fieldset');
    fields.each(function() {
      var label = 'label' + (this.id ? '[for=' + this.id + ']' : '');
      var $field_labels = $(e.target).find(label);
      var $fieldset_legends = $(e.target).find('legend span.fieldset-legend');
      var $labels = $field_labels.add($fieldset_legends);
      if (e.value) {
        $(this).attr({ required: 'required', 'aria-required': 'aria-required' });
        $labels.each(function() {
          $(this).addClass('js-form-required form-required');
        });
      } else {
        $(this).removeAttr('required aria-required');
        $labels.each(function() {
          $(this).removeClass('js-form-required form-required');
        });
      }
    })
  }
});

})(jQuery, Drupal);

```

In your\_module.module in a form alter add:

```
$form['#attached']['library'][] = 'your_module/conditional_fields';

$form['field_b']['#states'] = [
      'visible' => [
        ':input[name="field_a"]' => ['!value' => '_none']
      ],
      'required' => [
        ':input[name="field_a"]' => ['!value' => '_none'],
      ],
  ];

```

**Don't forget add the js code in your\_module.libraries.yml file**

Adding JS to a Drupal module

With our above code it worked!.
> 0 votes

# Answer
In Drupal 9, there's no need to add so much custom code like the other answer.

Here's an easy example, with the condition being a checkbox checked/unchecked:

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

    $form['api'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Use the API'),
      '#description' => $this->t('Uncheck to skip the API call and fall back to a hard-coded response.'),
      '#default_value' => $config->get('api'),
    ];

    $form['appid'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Key'),
      '#default_value' => $config->get('appid'),
      '#description' => $this->t('The API key'),
      '#states' => [
        'visible' => [
          ':input[name="api"]' => ['checked' => TRUE],
        ],
        'required' => [
          ':input[name="api"]' => ['checked' => TRUE],
        ],
      ],
    ];

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

```
* You can use `value` instead of `checked`, or some other property.
* Use `!` to negate it, like `!value`
* Use `_none` to represent no value, so use `['!value' => '_none']` to ensure there's a value
> 0 votes

# Answer
So for fields having required attribute in widget array, You may use below code :

```
  $form['field_name']['widget']['#states'] = [
    'required' => [
      ':input[name="conditional_field_name[$option_id]"]' => ['checked' => TRUE],
    ],
  ]
  //Please vote if it works.

```
> 0 votes

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


# Question
Title: How can I programmatically create a revision for a node?
I have a `node` object and I need to create revisions for that node programmatically. When I tried as follows it's not working. Instead it's creating new nodes. What am I doing wrong? How can I fix this?

```
$node = Node::create([
  'nid' => $nid, // My desired node ID for the revision.
  'type' => $bundle_type,
  'field1' => $value1,
  'field2' => $value2,
]);

$node->revision = TRUE;
$node->save();
$node->setPublished(true);
$nid = $node->id();
print 'Created revision for node' . $nid;

```

# Answer
```
// Make this change a new revision
  $node->setNewRevision(TRUE);
  $node->revision_log = 'Created revision for node' . $nid;
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setRevisionUserId($user_id);
  $node->save();

```

Use Above Code to create a revision. :)
> 28 votes

# Answer
For language specific revisions you can use below code sample:

```
$storage =\Drupal::entityTypeManager()->getStorage('node');
$revision = $storage->load($nid);
$revision = $revision->getTranslation($languageCode);
$revision->setRevisionCreationTime(\Drupal::time()->getCurrentTime());
$revision= $storage->createRevision($revision);
$revision->save();

```
> 2 votes

# Answer
If you have enabled the content moderation module, you must set the moderation state like this:

```
$node->moderation_state->value = 'draft';

```
> 1 votes

---
Tags: entities
---


# Question
Title: Contextual filter from Taxonomy inside a paragraph
I have content-type (Destination) with a paragraph added as a component. This paragraph has a referenced taxonomy vocabulary (location). I want to display a list of nodes from another content-type (Blogs) filtered by location.

I created a custom template for this paragraph and I want to send the taxonomy term as an argument to a view. In my twig template and using twig\_tweaks, I set the location id as follow:`{% set location = content.field_my_location[0]['#plain_text'] %}` and I display the view with  `{{ drupal_view('my_view', 'my_view_display', location) }}`.

The view displays when the contextual filter is set to display all results. I do not know how to filter by location.

I added my field that contains the paragraph as a relationship (field\_components), then I added the location field (field\_my\_location) as a contextual filter. It does not work and I'm not sure what I'm doing wrong.

# Answer
> 0 votes
I was able to solve this by adding three relationship.

The first relationship is my blog location taxonomy term field "field\_blog\_location".

The second relationship I added is a referenced taxonomy term to the location field in the paragraph "Paragraph using field\_my\_location" This relationship is required.

The third relationship to add is the bridge to the Content entity that is referencing Taxonomy term via field\_my\_location\_field\_on\_the\_paragraph'. You set it up to use the second relationship as its relationship.

Last, you set up a contextual filter on field\_my\_location using the third relationship.

Hope it helps someone!

---
Tags: views, paragraphs
---


# Question
Title: In a View, how I display only the first image from a field that allows multiple?
I have a very basic view, that outputs the title and images. Some nodes have 2-3 images in them, but when I create a view it outputs all the images. How do I display only the first image?

# Answer
Currently it will display all images if you have multiple in the node. The only option is to set the settings in the "Content: Image" setting to show only 1 under multiple image settings.
> 1 votes

---
Tags: views, 9
---


# Question
Title: Why can’t I disable the Update Manager module?
In drupal 7 we had the ability to disable the update module, but in Drupal 8,9+ we can't do that.

How do we disable the message:

> There is a security update available for your version of Drupal.

# Answer
You cannot disable any module in Drupal 9—"disabling" modules is no longer possible. You uninstall them. Uninstall the Update Manager module.
> 4 votes

---
Tags: 9
---


# Question
Title: How to load a customer profile from address module
I'm using Drupal 8 with the module Commerce and I have an issue with the customer address.

I'm developing an export custom module in D8, and I'm stuck trying to load the profile (to access billing and shipping address) of a customer.

I'm not able to access this data from the custom module. And there is no documentation about the address pluggin ( https://www.drupal.org/project/address )

I have tried to load the order and the user data but there is no relevant field that helps me to achieve this.

Can anyone give me a hint?

Thanks in advance.

# Answer
> 2 votes
you can try get profile by order and can try the code below:

```
$order_id =1;
$entityManager = \Drupal::entityTypeManager();
$order = $entityManager->getStorage('commerce_order')->load($order_id);

```

get address by field `billing_profile`

```
$address = $order->billing_profile->entity->address->getValue();

```

# Answer
> 1 votes
Since the customer profile is a content entity you can access customer profile information by using the entityTypeManager() function.

```
$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($profile_id);

```

# Answer
> 1 votes
Starting from the order, this may help you:

```
if ($this->order->hasField('shipments') && !$this->order->get('shipments')->isEmpty() ) {
  $order_shipments = $this->order->get('shipments')->referencedEntities();
  $order_shipment = reset($order_shipments);
  $shipment_profile = $order_shipment->getShippingProfile();

  // Prepare shipment information.
  $addressValues = $shipment_profile->address->getValue();
  $shipment['locality'] = $addressValues[0]['locality'];
  $shipment['administrative_area'] = $addressValues[0]['administrative_area'];
  $shipment['postal_code'] = $addressValues[0]['postal_code'];
}

```

# Answer
> 0 votes
customer profile is a entity type and can be loaded by profile\_id by using the entityTypeManager()

```
$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($profile_id);

```

if you don't know the **profile\_id** in the first place It can be also be loaded by properties using loadByProperties() method

```
$values = [
            'field_phone' => "123456789",
            "address" => [
                "country_code" => "BD",
            ]
        ];
$profile = \Drupal::entityTypeManager()->getStorage('profile')->loadByProperties($values);

```

Following fields are available for filtering for the profile

```
      "revision_id"
      "type"
      "uuid"
      "status"
      "uid"
      "is_default"
      "data"
      "created"
      "changed"
      "revision_created"
      "revision_user"
      "revision_log_message"
      "revision_default"
      "isDefaultRevision"
      "address"
      "field_phone"

```

last field is **field\_phone** is created from cms which located in Profile config page **(/admin/config/people/profile-types/manage/customer/fields)**.

---
Tags: 8, users, commerce
---


# Question
Title: Can a template file write, copy, or rename files?
Can code put in a template file write, copy, rename files, or read files that aren't template files?

# Answer
> 2 votes
Twig is extendable, so it can do whatever it's given the ability to do.

But no, core Twig and core Drupal do not include extensions for manipulating files.

Templates are for displaying things, it wouldn't make conceptual sense for them to be able to manipulate the file system (even if you could technically provide an extension to give them that ability).

---
Tags: 8, files
---


# Question
Title: How to avoid submissions with the same e-mail address?
How can I prevent that someone submits a form with the same address in an e-mail field again?

# Answer
> 3 votes
Check the unique box in the Form validation settings.

---
Tags: webforms, 9
---


# Question
Title: Drush installed in local directory but command not found?
I know that Drush is a huge time saver so I'm trying to get familiar with it but I keep getting

> command not found

error after installation. I've required and removed Drush a couple of times just to make sure I'm doing this correctly.

Here's what I did:

```
$ cd mydrupal
$ composer require drush/drush

```

After I run the above command many things install:

> Using version ^9.3 for drush/drush
>
> ./composer.json has been updated
>
> Loading composer repositories with package information
>
> Updating dependencies (including require-dev)
>
> Package operations: 57 installs, 0 updates, 0 removals
>
> * Installing... (many things download and install (100%))

And I end up with this:

> Writing lock file
>
> Generating autoload files
>
> > Drupal\Core\Composer\Composer::preAutoloadDump Drupal\Core\Composer\Composer::ensureHtaccess

Then I get my command line prompt and I run

```
$ drush status

```

and I get this:

> -bash: drush: command not found

Any ideas?

# Answer
> 1 votes
You are calling a global command. Which is not installed or symlinked into one of your Mac's autoloaded `bin` directories (or is not added to your global `$PATH`).

Simplest option you have now is to use the local command:

```
$ cd mydrupal
$ vendor/drush/drush/drush status

```

Alternatively you may want to install Drush Launcher on your Mac (to be used together with the Composer template for Drupal projects). Which when you are inside a project that has a local Drush installed automatically associates the global `drush` command to the project's local Drush.

# Answer
> 0 votes
I had this issue and it was due to config\_sync\_directory not being defined in settings.php. Example...

```
  $settings['config_sync_directory'] = 'sites/default/files';

```

---
Tags: drush
---


# Question
Title: How do I perform a "contains" match with #states?
I use the same form for different events. Previously I have set up a conditional email to be sent based on the exact title of the event. However, I would like to have the conditional email be sent based on one specific word in the event title. Is there a way to set up the logic to base it on a partial text match? The attached image, is an example of when I do an exact title match. However, I would like to set up the logic to be conditional on a single word, "MBA" to catch all signups related to any event related to "MBA" instead of setting up the logic for each specific event.

Essentially, I would like the option of "contains" instead of "is" but not sure how to write it.

# Answer
You can use the 'Pattern' trigger which can be a string or regular expression.

```
textfield:
  '#type': textfield
  '#title': textfield
  '#description': 'Enter a value that contains the letter a.'
markup:
  '#type': webform_markup
  '#states':
    visible:
      ':input[name="textfield"]':
        value:
          pattern: a
  '#markup': 'Text field contains the letter <strong>A.</strong>'

```
> 4 votes

---
Tags: webforms, emails
---


# Question
Title: Feeds: import content from CSV url list with QueryPath or alternative to find image or body in external HTML
The situation:

Partner provides us with relatively simple CSV that only has title and url to article with permission to use images or body of that article, but... "not a tech person, no idea how to export everything".

Task:

Import some divs/imgs from external website with Feeds module just using that CSV url list.

I'm quite familiar with Feeds, at least when all data is provided within CSV/XML, with img URLs available. But here I'm a bit lost how to achieve that with some HTML lookup.

UPDATE:

The CSV I have is something like that:

```
"Article 1 title", "https://example.com/article-1"
"Article 2 title", "https://example.com/article-2"

```

HTML at target:

```
<article class="article">
  <img class="article-image" src="...">
  <div class="body">...</div>
</article>

```

What I want to achieve is that Feeds would create a node with fields:

```
1. Title
2. Article image (image from class "article-image")
3. Article body (html inside class "body")

```

I hope that clarifies the situation.

I guess what @Patrick Kenny suggested is the way to go, but maybe there are some other ideas.

# Answer
> 1 votes
Requirements

* There is a CSV file with a list of URLs.
* You need to get image files used in `<img>` tags on that list of URLs.

So you need to parse the URLs listed in the CSV file. You will need to extend Feeds to do this with custom code.

However, you can get a head start by using the Feeds Tamper module, which gives you a way to process the CSV columns with your custom code.

The way to implement this:

1. Create your own Feeds Tamper plugin.
2. Write custom code to extract the images you need from a given URL. (This is a Stack Overflow question and off topic for this site.)
3. On the settings page for your feed, add your custom tamper plugin.
4. Import the feed.

---
Tags: 9, feeds
---


# Question
Title: How do I alter the form submission handler?
For some reason I need to replace some characters (if exist) in every single textfields in any form just right before they stored in database. In other words I need a hook in which I could get all submitted data and replace their characters.
I found this solution:

```
function hook_form_alter($form, $form_state, $form_id) {
  $form['#submit'] = 'my_custom_submission_function';
}

```

But this isn't a good idea since I have to take care of the rest of the submission progress too. I just need to replace some characters. Is there any hook to do this? What are the solutions?

# Answer
`$form['#submit']` stores an array of form submit handlers. With the code you provided you're overwriting it by adding only your own. To get the result you want you should add your submit handler as the first element in the array like this:

```
array_unshift($form['#submit'], 'mymodule_custom_submission');

```

Getting the right values in the right forms and replacing some characters is probably a bigger issue in itself. You may want to narrow down the forms/fields you need to change to make sure you don't break anything.
> 22 votes

# Answer
Perhaps it would be better to perform these modifications during validation instead of submission as suggested by Drupal (see form\_set\_value function at https://api.drupal.org/api/drupal/includes!form.inc/function/form\_set\_value/7).

So in your hook\_form\_alter you could even add it to the end of existing validation functions if you like:

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

```
> 3 votes

# Answer
On Drupal 8 or 9 it's almost the same solution :

Add a hook in a custom module file and a custom function :

File `my_module.module` :

```
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['#submit'][] = 'submit_form_custom';
}

/**
 * Custom form submit handler.
 */
function submit_form_custom(&$form, FormStateInterface &$form_state) {
  $value = $formState->getValue('field_name');
  // Do what you need with the value...
  $value = str_replace("old", "new", $value);
  $formState->setValue('field_value', $value);
}

```
> 0 votes

---
Tags: 7, hooks, forms
---


# Question
Title: Custom Content Entity Type: links annotation
I created a Custom Content Entity Type with all the basic CRUD operations. It is working but I do not understand how the links work in the entity annotation and therefore not why they are necessary.

My annotation:

```
/**
* @ContentEntityType(
*   id = "myent",
*   label = @Translation("My entity"),
*   handlers = {
*     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
*     "list_builder" = "Drupal\myent\Controller\MyentListBuilder",
*     "form" = {
*       "add" = "Drupal\Core\Entity\ContentEntityForm",
*       "edit" = "Drupal\Core\Entity\ContentEntityForm",
*       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
*     },
*     "access" = "Drupal\myent\ContactAccessControlHandler",
*   },
*   base_table = "myent",
*   entity_keys = {
*     "id" = "id",
*     "uuid" = "uuid",
*   },
*   links = {
*     "edit-form" = "/",
*     "delete-form" = "/",
*   },
* )
*/

```

As you can see I just inserted the necessary slash at the links section. The actual routes to the operations have to be defined in the "myent.routing.yml" no matter what so I do not see why I should write them again in the annotation.

If I remove the links section completely the operations are gone too. So I have to write the links section in the annotation even though they have no additional information for the operations.

What am I missing?

# Answer
> 0 votes
Years too late but just in case anyone else comes across this issue, I have figured out the answer after much searching.

According to this section in the docs, the links defined in the `@ContentEntityType` annotation are used in the list builder class (defined by `list_builder`) to automatically add an 'Operations' dropdown with all of the links to the list.

This will work as long as you keep the parent method in the return statement of `returnHeader()`:

`return $row + parent::buildRow($entity);`

Changing this to `return $row;` would render the links section in the annotation useless.

---
Tags: entities
---


# Question
Title: "Unable to remove item at non-existing index"
I am currently working on Drupal 9 build of the Drupal 7 site along with just user migration.

The site had existing 20K users and we're migrating them with Drupal Migrate module with simple bring every user and static map old roles to new roles.

The migration is running well with success of 19K+ migrated without any errors. However on remaining about 90 users we're getting this error messages:

```
 ------- -------------- ------------------- -----------------------------------------------------------------------------------------------------------------------------------------------
  Level   Source ID(s)   Destination ID(s)   Message
 ------- -------------- ------------------- -----------------------------------------------------------------------------------------------------------------------------------------------
  1       598                                Unable to remove item at non-existing index. (C:\aba-website\public_html\web\core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php:811)
 ------- -------------- ------------------- -----------------------------------------------------------------------------------------------------------------------------------------------

```

And these users are failed and skipped. The error message doesn't make a lot of sense for us as where the issue could be.

Does anyone ever encounter this error message? What could be the possible reason behind this error messages?

# Answer
I had a similar problem, but it was also appearing when you try to save the user. Have you tried editing and saving those users with the error?

In my case we have two multi-value paragraph fields that are being kept in sync with each other (don't ask - before my time). And when those two fields get out of sync e.g. one field has 20 entries and the other has 22, I see that error. I have to manually edit them to have them match, then I'm able to save them and the user works fine after that.

Check if you have some custom that is doing something similar: adding or removing items from a multi-value field on the user profile.
> 0 votes

---
Tags: users, migrations, 9
---


# Question
Title: How do I list all the roles to assign them in the registration form?
I'm trying to alter the user registration form by adding a custom field which lists all the available roles in the site.

How can I achieve this?

# Answer
You can add an entity reference field to the user, referencing entities of type User Role. You can do this by enabling the Field UI module, and navigating to Admin -\> Configuration -\> People -\> Account Settings -\> Manage Fields (tab).
> 1 votes

---
Tags: users, 9
---


# Question
Title: remove "last saved" and "author" fields in from
How to remove "last saved" and "author" fields in from in Drupal 8?

answer over here did not help How do I remove the authoring information?

i have tried to hide it via form\_alter but no luck...

i would appreciate any help or advice... lost to much time on this already...

part of what i get in *kint($form);* if this can help:

```
→'meta' => array(10)

'#type' => string(7) "details"

'#group' => string(8) "advanced"

'#weight' => integer-10

→'#title' => Drupal\Core\StringTranslation\TranslatableMarkup(5)

        contents Available methods (14)

        protected translatedMarkup -> NULL

        protected options -> array(0)

        →protected stringTranslation -> Drupal\Core\StringTranslation\TranslationManager(4)
                contents Available methods (10)

                →protected translators -> array(2)

                    →'30' => array(1)

                        *DEPTH TOO GREAT*

                    →'0' => array(1)

                        *DEPTH TOO GREAT*

                →protected sortedTranslators -> array(2)

                    →Drupal\Core\StringTranslation\Translator\CustomStrings(4)

                        *DEPTH TOO GREAT*

                    →Drupal\locale\LocaleTranslation(9)

                        *DEPTH TOO GREAT*

                protected defaultLangcode -> string(2) "en"

                public _serviceId -> string(18) "string_translation"

        protected string -> string(6) "Status"

        protected arguments -> array(0)

→'#attributes' => array(1)

    →'class' => array(1)

        string(19) "entity-meta__header"

'#tree' => boolTRUE

'#access' => boolTRUE

→'published' => array(4)

    '#type' => string(4) "item"

    →'#markup' => Drupal\Core\StringTranslation\TranslatableMarkup(5)

            contents Available methods (14)

            protected translatedMarkup -> NULL

            protected options -> array(0)

            →protected stringTranslation -> Drupal\Core\StringTranslation\TranslationManager(4)
                    contents Available methods (10)

                    →protected translators -> array(2)

                        *DEPTH TOO GREAT*

                    →protected sortedTranslators -> array(2)

                        *DEPTH TOO GREAT*

                    protected defaultLangcode -> string(2) "en"

                    public _serviceId -> string(18) "string_translation"

            protected string -> string(9) "Published"

            protected arguments -> array(0)

    '#access' => boolFALSE

    →'#wrapper_attributes' => array(1)

        →'class' => array(1)

            string(18) "entity-meta__title"

→'changed' => array(4)

    '#type' => string(4) "item"

    →'#title' => Drupal\Core\StringTranslation\TranslatableMarkup(5)

            contents Available methods (14)

            protected translatedMarkup -> NULL

            protected options -> array(0)

            →protected stringTranslation -> Drupal\Core\StringTranslation\TranslationManager(4)
                    contents Available methods (10)

                    →protected translators -> array(2)

                        *DEPTH TOO GREAT*

                    →protected sortedTranslators -> array(2)

                        *DEPTH TOO GREAT*

                    protected defaultLangcode -> string(2) "en"

                    public _serviceId -> string(18) "string_translation"

            protected string -> string(10) "Last saved"

            protected arguments -> array(0)

    →'#markup' => Drupal\Core\StringTranslation\TranslatableMarkup(5)

            contents Available methods (14)

            protected translatedMarkup -> NULL

            protected options -> array(0)

            →protected stringTranslation -> Drupal\Core\StringTranslation\TranslationManager(4)
                    contents Available methods (10)

                    →protected translators -> array(2)

                        *DEPTH TOO GREAT*

                    →protected sortedTranslators -> array(2)

                        *DEPTH TOO GREAT*

                    protected defaultLangcode -> string(2) "en"

                    public _serviceId -> string(18) "string_translation"

            protected string -> string(13) "Not saved yet"

            protected arguments -> array(0)

    →'#wrapper_attributes' => array(1)

        →'class' => array(1)

            string(23) "entity-meta__last-saved"

→'author' => array(4)

    '#type' => string(4) "item"

    →'#title' => Drupal\Core\StringTranslation\TranslatableMarkup(5)

            contents Available methods (14)

            protected translatedMarkup -> NULL

            protected options -> array(0)

            →protected stringTranslation -> Drupal\Core\StringTranslation\TranslationManager(4)
                    contents Available methods (10)

                    →protected translators -> array(2)

                        *DEPTH TOO GREAT*

                    →protected sortedTranslators -> array(2)

                        *DEPTH TOO GREAT*

                    protected defaultLangcode -> string(2) "en"

                    public _serviceId -> string(18) "string_translation"

            protected string -> string(6) "Author"

            protected arguments -> array(0)

    '#markup' => string(5) "@dmin"

    →'#wrapper_attributes' => array(1)

        →'class' => array(1)

            string(19) "entity-meta__author"

```

# Answer
If I understand your requirement correctly, then you should go to your content type `Manage form display` configuration page, it should be under: `/admin/structure/types/manage/YOUR_CONTENT_TYPE/form-display`
Then you should disable `Authored by` and/or `Authored on` by dragging them to the disabled area in the table, then click save
> 1 votes

# Answer
The information about "last saved" and "author" is under meta in form variable.
To remove it, you need to alter form and unset these variables.

```
function MY_MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'node_CONTENT_TYPE_form'){
    unset($form['meta']['changed']);
    unset($form['meta']['author']);
  }
}

```
> 0 votes

# Answer
The following worked for me:

```
    function MY_MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'node_CONTENT_TYPE_form'){
    $form['meta']['#access'] = FALSE;
  }
}

```
> 0 votes

# Answer
I had the same problem with claro and a group content node edit form. These did NOT work https://www.drupal.org/project/simplify/issues/3207027 https://drupal.stackexchange.com/a/134540/14822 (partially worked - empty right sidebar still displayed)

what worked for me was i. create a custom module and implement form alter like this

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

/**
 * Implements hook_form_alter() for node form.
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if ( in_array('administrator', $roles)) {
    return;
  }
  $node = $form_state->getFormObject()->getEntity();
  if ( !in_array($node->bundle(), ['mycontenttype','myothercontenttype'])) {
    return;
  }

  $form['#attached']['library'][] = 'mymodule/mymodule_simplify_node_edit';
}

```

Then create a mymodule.libraries.yml file and declared this library

```
mymodule_simplify_node_edit:
  css:
    theme:
      css/simplify.css: {}

```

This allowed me to inject css for this form. Since security is not an issue and I only wanted to simplify the form for basic user this is ok.

these are the css rules i used to fix the problem

```
.layout-region--node-secondary {
    display: none !important;
}
.layout-region--node-main .layout-region__content, .layout-region--node-footer .layout-region__content {
    max-width: 80rem !important;
}
.layout-region--node-main {
    float: none !important;
    width:  100% !important;
}

```
> 0 votes

---
Tags: 8, forms
---


title: How do I set the value for field_stock?

text:
# Question
Title: How do I set the value for field_stock?
I use module commerce\_stock on Drupal 8.

I get back product data and I create a product with its data. I have to create a field field\_stock (Stock level) in variations, which I create with the following code.

```
$variation =  ProductVariation::create(['type' => 'default', 'sku' => 'sku1', 'status' => TRUE, 'price' => $price]);

```

How do I add the value to field\_stock?

# Answer
> 1 votes
I found a solution to add the value to field\_stock (Stock level).

```
$variation =  ProductVariation::create(['type' => 'default', 'sku' => $json['22107'], 'status' => TRUE, 'price' => $price]);
$variation->save();
//Stock
$stock = ['stock' => ['value' => 100]];
$var = \Drupal::entityManager()->getStorage('commerce_product_variation')->load($variation->id());
$var->set('field_stock', [$stock]);
$var->save();

```

My field\_stock in database is empty but this code create a commerce\_stock\_transaction in database with my quantity.

# Answer
> 0 votes
Assuming that field\_stock is a field on your ProductVariation, I believe you should be able to set the field value like so:

```
$variation =  ProductVariation::create(['type' => 'default', 'sku' =>
   'sku1', 'status' => TRUE, 'price' => $price]);

$variation->set('field_stock', "100"); // or w/e value or logic here
$variation->save();

```

# Answer
> 0 votes
From Commerce Stock 2, you have to adjust the stock level with transactions. So you can create an transaction in StockServiceManager:

```
public function createTransaction(PurchasableEntityInterface $entity, $location_id, $zone, $quantity, $unit_cost, $currency_code, $transaction_type_id, array $metadata = []);

```

So adding 1 to the stock level could look like:

```
$stockManager = Drupal::service('commerce_stock.service_manager');
$stockManager->createTransaction($entity, 1, '', 1, null, null, StockTransactionsInterface::STOCK_IN);

```

---
Tags: 8, commerce
---


# Question
Title: How to use Drush remote site aliases with web service or other account?
Developers are not allowed to have direct access to the Production Drupal servers, which are Linux. But, I need for developers to be able to run a limited set of Drush commands via remote site aliases.

I have this working by using Drush remote aliases and Drush policies. The Drush example docs don't go into much detail, but show `www-data` in one of the examples.

```
 * @code
 * $aliases['live'] = array(
 *   'remote-host' => 'server.domain.com',
 *   'remote-user' => 'www-admin',
 *   'root' => '/other/path/to/drupal',
 *   'uri' => 'http://example.com',
 * );

```

But, this can't be, can it? Yes, that's the "user" Apache runs as, but this user is a dummy account with no login or password credentials, or user directory, so no ssh keys.

How do you setup an account for use with the remote site aliases, or how did you modify the Apache user / process to use login credentials or ssh keys?

# Answer
You may be looking at old docs, as that is a PHP array, and newer versions of Drush use .yml.

That said, you can set set up an SSH key on your server, then set up a user in your .ssh/config file as follows:

```
Host someidentifier
HostName example.com
Port 2233
User RemoteUsername
IdentityFile ~/.ssh/id_rsa

```

Test this works by running `ssh someidentifier`. After doing this, you can set the `remote-user` key for the Drush alias to be `someidentifier`, and your alias will work.
> 1 votes

---
Tags: drush
---


# Question
Title: How to identify ajax request in the exposed form of the View?
I have a View, it is ajax View. There are exposed filters (with checkboxes). When I select a checkbox `\Drupal::routeMatch()->getRouteName()` shows general route name: `views.ajax`

I need to change **view mode** in the view:

```
function entity_product_admin_entity_view_mode_alter(&$view_mode, \Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'product' && \Drupal::routeMatch()->getRouteName() == 'views.ajax') {
    $view_mode = 'product_card_full_width';
  }
}

```

But in case `Drupal::routeMatch()->getRouteName() == 'views.ajax'` `$view_mode` will change on all ajax requests, but I need it to change only on a specific field of the form.

# Answer
> 0 votes
This hook seems to be not very useful in a Views context. You don't get much information, not even the view name. In an Ajax request Views removes any POST data from the request before executing the View.

You would need to save the view name (or any other POST data) at the start of the request in an event subscriber:

```
  public function onKernelRequest(RequestEvent $event) {
    $request = $event->getRequest();
    $view_name = $request->request->get('view_name');
    $request->attributes->set('view_name', $view_name);
  }

```

Use `drush gen service:event-subscriber` to generate the scaffolding.

Then the hook can get the view name:

```
$request = \Drupal::request();
$view_name = $request->attributes->get('view_name');

```

---
Tags: views, forms, ajax
---


# Question
Title: Is there a way to define a JS library that will use a CDN as a fallback
Is there a way to define a JS library that will use the CDN as a fallback?

**Example:** Define a billboard.js library that will use the local version of files from **libraries** directory and fall back to one provided from the CDN otherwise.

There is a possibility to have a check on the JS side and load the libraries from there, yet that does not seem to be the best solution. Another way would be to check if the library is present and then load the ones from CDN. There is a way to either include add the external assets into the render array or to define a standalone **billboard-cdn** library and make sure that the render array will get that one included if the files are not present.

Is there a standard or suggested approach for achieving just that?

I'm currently looking at doing just that for the h5p\_analytics module, where it is currently required to manually install the **d3** and **c3** library files in order to get them working (as seen from the libraries.yml file). I don't like that approach as it requires a check of the JS side to only display the graphs when the libraries are present. I'm going to replace the now abandoned **c3.js** with **billboard.js** and would prefer to make sure that the graphs will be shown in either case, with the ability to use the local version of the library.

Any suggestions are more than welcome as I would really prefer to keep it as simple as possible.

# Answer
> 3 votes
Use hook\_library\_info\_build to declare the library dynamically and use PHP's `file_exists` to detect if the local file exists.

---
Tags: javascript
---


# Question
Title: Flood Control Does Not Use Correct IP Address
In settings.php I've done the following:

```
/* Turn on reverse proxy */

$settings['reverse_proxy'] = TRUE;

/* Set reverse proxy (load balancer) address */

$settings['reverse_proxy_addresses'] = ['a.b.c.d']; //test-bnc4-web1

/* Enabled trusted headers */

$settings['reverse_proxy_trusted_headers'] = \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_FOR | \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_HOST | \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_PORT | \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_PROTO | \Symfony\Component\HttpFoundation\Request::HEADER_FORWARDED;

```

I'm still not getting the correct client IP in the log when a user fails to login because of an invalid username. It is reporting the second IP address in `$_SERVER['X_FORWARDED_FOR']` where `$_SERVER['X_FORWARDED_FOR'] = 'a.b.c.d, e.f.g.h'` The first IP is the correct one. The second is a switch.

This is important if an IP gets blocked.

# Answer
> 2 votes
Based on this Symfony Framework pull request, you have to add all intermediate proxies to `reverse_proxy_addresses` for the actual client IP to resolve properly.

The documentation in `settings.php` above `reverse_proxy_addresses` reads:

> In order for this setting to be used you must specify every possible reverse proxy IP address in $settings\['reverse\_proxy\_addresses'\].

---
Tags: 9
---


# Question
Title: Alter DrupalDateTime Timezone To Correct the Timezone
I have a situation where I need to conditionally correct the default timezone defined in a drupalDatetime object. But I'm clearly not understanding how to do it properly. Example:

```
use Drupal\Core\Datetime\DrupalDateTime;

// Sample DateTime Object
$test_date = new DrupalDateTime('2022-09-27T13:30');
// Output 2022-09-27 13:30:00-04:00 EDT

// Attempt to adjust to Central Time
$new_timezone = new \DateTimeZone('America/Chicago');
$test_date->setTimezone($new_timezone);
// Output 2022-09-27 12:30:00-05:00 CDT

```

The issue is that under some conditions the default timezone has been improperly set to EDT, and I'm trying to change it to something else (CDT for example). I'm not wanting to adjust it to display the same time, but adjusted to a different time zone. So the end result ought be 13:30:00-05:00 CDT

How do I properly do that?

# Answer
> 2 votes
The Druapl `DrupalDateTime` class is essentially a wrapper / proxy class for the PHP `\DateTime` class.

This is what is going on. When you do

```
$test_date = new DrupalDateTime('2022-09-27T13:30');

```

you are creating an object to represent a distinct point in time. The unix timestamp for this is 1664299800. This is number of seconds since midnight Jan 1, 1970 in London. But, behind the scenes it it set up so that the human readable form shows the local time in New York.

When you do

```
$test_date->setTimezone($new_timezone);

```

you are just setting the display time zone to Chicago. The actual timestamp in the object is still 1664299800. Hence, the output you see.

As the comments say, you either need to instantiate the object and pass in the time zone you want to display in, or create a new object.

---
Tags: 9, datetime
---


# Question
Title: How do I show a coupon code to customers?
I've enabled a Ubercart Discount Coupons module in my eshop site and created some coupons with multiple one-time use only codes for testing purposes.

Now I would like to get one of the active coupon codes to customer who submits a newsletter registration form. Are there any functions to retrieve one of unused coupon codes?

# Answer
> 1 votes
The UC coupon module doesn't have a general purpose coupon retrieval function.

If you're solely looking to retrieve an active coupon, you can follow what the module itself does: query the DB table `uc_coupons` for rows with column `status` = 1. Using a DB query will let you modify it to whatever your particular case (e.g. 1 or more results, bulk codes, date range, etc.).

# Answer
> 0 votes
I am also looking for this functionality because I want to create a Coupons tab in the MY ACCOUNT area of a Drupal 7 website that uses Ubercart 3 (**D7U3**).

The line of code that generates a list of system coupons starts at **line 118** in **uc\_coupon.admin.inc** with the following comment:

```
/**
 * Display a brief overview of system coupons
 *
 * @param $view_type
 *   'active' or 'inactive'
 */

```

To be able to accomplish this task, you need three things:

* **"Hook"** to a Drupal event so your code can be **"Triggered"**
* Have your **"Triggered"** code generate relevant and meaningful results
* Present your relevant and meaningful results in a human-understandable way

The first thing you need to do is figure out what event "triggers" your customization, which defines how it is then "fired". In my case, the even in question is the marshaling of information necessary to create and present the information that appears in they MY ACCOUNT screen. Your situation may differ, but the crux of this challenge is to identify the **system event** to which your custom code can be **"hooked"**.

One potential list of Drupal 7 **"hooks"** is located at: https://api.drupal.org/api/drupal/includes%21module.inc/group/hooks/7.x

The next thing you need to do is obtain and manipulate data from the back-end database of Drupal (presumably MySQL, but not strictly so) by creating a database connection, issuing a structured query through that connection and then receiving the result into a data structure that can be iterated through - because most systems have more than one active coupon at any given time.

The design pattern is this:

```
A) Establish connection
B) Issue command through connection
C) Receive results into local data structure

```

A tutorial on how to do this is available at: https://www.drupal.org/docs/7/creating-custom-modules/retrieving-data

The last thing you need to do is present the results of the above two operations in a way that the user can perceive as a meaningful response. This usually entails the creation of representative PHP and CSS code to position and then present/style the results.

A tutorial on creating an input form and producing an output form is available at: https://www.youtube.com/watch?v=EHY8McU79gc&ab\_channel=CodeKarate

## g.

---
Tags: ubercart
---


# Question
Title: How can I send an email if there are any change in fieldname values (example email, stats of task) by checking from existing database
I need your help or suggestions in create custom module where I need send an email to user and admin if there is any status change in ticket or field values changes (such as description updated) in existing database.

* **Things I know:** drupal\_mail() function helps me to send email and HOOK\_mail() helps me to format the mail structure and I need to implement these in '\<module\_name\>.module' file.

But,i need your suggestions in implementation for checking the data values of specific field(such as description field). if values are change, mail need to trigged.

I am open for any suggestions. Thank you

# Answer
> 2 votes
If I understand your question correctly, you need to know what has been changed when an entity is updated. You can do that using hook\_entity\_update() or hook\_ENTITY\_TYPE\_update():

> This hook runs once the entity storage has been updated. Note that hook implementations may not alter the stored entity data. Get the original entity object from $entity-\>original.

For instance, assuming you want to know whether the `field_description` has been changed when a node gets updated, you can do that in your `.module` file:

```
/**
 * Implements hook_ENTITY_TYPE_update() for node entities.
 */
function <module-name>_node_update(NodeInterface $node) {
  if ($node->get('field_description')->value !== $node->original->get('field_description')->value) {
    // Apply the logic when the description field changes.
  }
}

```

where `<module-name>` is the name of your module.

---
Tags: emails
---


title: Field widget depending on another field

text:
# Question
Title: Field widget depending on another field
I have two list fields with select widgets and the second select depends on the first one.

How would you do this? Is there a module already doing this at least in code?

# Answer
> 1 votes
You can use the Conditional fields module.

# Answer
> 1 votes
I recently had your doubt, in my search I came upon a very interesting module, Reference field option limit, which depends on Entity Reference and is only available for Drupal 7.

It solved my problem; I hope it will be useful to you.

# Answer
> 1 votes
This is quite complex but doable. I have two fields, one is called `parent_menu_name`, this is an entity reference field into menus and a `parent_menu_link` which is simply a string -- menu tree entries are not entities (custom menu links are but not at all tree entries are those).

I started with moving the code to a class for encapsulation:

```
function group_content_submenu_field_widget_single_element_form_alter(array &$element, FormStateInterface $form_state, array $context) {
  \Drupal::classResolver(GroupContentSubmenuAlter::class)
    ->widget($element, $form_state, $context);
}

```

This calls my `widget` method:

```
  public function widget(array &$element, FormStateInterface $form_state, array $context) {
    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    $items = $context['items'];
    $gcm = $items->getEntity();
    if ($gcm instanceof GroupContentMenuInterface && $gcm->hasField('parent_menu_link') && $gcm->hasField('parent_menu_name')) {
      $prefix  = sprintf('gcs-%s-%d-',
        $gcm->getFieldDefinition('parent_menu_link')->getUniqueIdentifier(),
        $context['delta']
      );
      $parent_menu_link_wrapper_id = $prefix . 'link';
      $parent_menu_name_wrapper_id = $prefix . 'name';
      switch ($items->getFieldDefinition()->getName()) {
        case 'parent_menu_name':
          $element['#prefix'] = "<div id='$parent_menu_name_wrapper_id'>";
          $element['#suffix'] = '</div>';
          $element['#after_build'][] = [static::class, 'afterBuildName'];
          $element['#ajax'] = [
            'callback' => [static::class, 'ajax'],
            'parent_menu_link_wrapper_id' => $parent_menu_link_wrapper_id,
          ];
          break;
        case 'parent_menu_link':
          $options = $this->getParentSelectOptions($gcm, $form_state);
          $element['value']['#type'] = 'select';
          $element['value']['#options'] = $options;
          $element['value']['#size'] = min(count($options), 50);
          $element['value']['#prefix'] = "<div id='$parent_menu_link_wrapper_id'>";
          $element['value']['#suffix'] = '</div>';
          $element['value']['#states']['invisible'][] = ["#$parent_menu_name_wrapper_id select" => ['value' => '_none']];
          $element['value']['#after_build'][] = [static::class, 'afterBuildLink'];
          break;
      }
    }
  }

```

it adds HTML wrappers around both widgets. Initially `#states` hides the parent menu link widget using the wrapper ID of the parent menu name widget. Then `#ajax` on the parent menu name widget replaces the entire parent menu link widget using the wrapper ID of it. So the frontend is done, now we need to tie them together on the backend. Let's see the method generating the options for the second widget:

```
  public function getParentSelectOptions(GroupContentMenuInterface $gcm, FormStateInterface $form_state): array {
    $menu_name = $gcm->parent_menu_name->target_id;
    // This is set in ::afterBuildName so this will only be set in form
    // rebuild which is exactly when we need it. The form parents do not
    // change from one form build to the next (hopefully).
    if ($menu_name_form_parents = $form_state->get(self::PARENT_MENU_NAME_FORM_PARENTS)) {
      $menu_name = $form_state->getValue($menu_name_form_parents);
    }
    if ($menu_name && $menu_name !== '_none' && ($menu = Menu::load($menu_name))) {
      return $this->menuParentFormSelector->getParentSelectOptions('', [$menu_name => $menu->label()]);
    }
    return [];
  }

```

As you can see it reads the value of the first widget after an AJAX submit thanks to this small after build method:

```
  public static function afterBuildName(array $element, FormStateInterface $form_state): array {
    $parents = $element['#parents'];
    $parents[] = 0;
    $parents[] = 'target_id';
    $form_state->set(self::PARENT_MENU_NAME_FORM_PARENTS, $parents);
    return $element;
  }

```

so when the parent menu name widget is built, it stores `#parents` into `$form_state` and when the form is rebuilt, the parent menu link uses this information to find the parent menu name value.

The AJAX callback is simple:

```
  public static function ajax(array &$form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    // The right element to replace was set in ::afterBuildLink.
    $parent_menu_link_widget = NestedArray::getValue($form, $form_state->get(self::PARENT_MENU_LINK_ARRAY_PARENTS));
    $parent_menu_link_wrapper_id = $triggering_element['#ajax']['parent_menu_link_wrapper_id'];
    return (new AjaxResponse())
      ->addCommand(new ReplaceCommand('#' . $parent_menu_link_wrapper_id, $parent_menu_link_widget));
  }

```

Remember, this AJAX callback is called by the parent menu name widget and needs to replace the parent menu link widget. The frontend is handled already, this is where another `#after_build` method comes to help us: the parent menu link widget conveniently stores its parent in `$form_state` -- but since we are retrieving from `$form` this needs to be `#array_parents`:

```
  public static function afterBuildLink(array $element, FormStateInterface $form_state): array {
    $form_state->set(self::PARENT_MENU_LINK_ARRAY_PARENTS, $element['#array_parents']);
    return $element;
  }

```

To recap, the lifecycle of an AJAX form is:

1. Form gets built.
2. The form and the form state is stored in the database, keyed by the build id.
3. On an AJAX request, the form and form state is restored
4. The form is rebuilt.
5. The form and the form state is stored in the database, keyed by a new build id.
6. The AJAX response is sent. This includes response provided by the callback and the new build id.

Both of our widgets store their respective locations in step #1 and then the *other* widget retrieves this in #4.

# Answer
> 0 votes
A solution could be creating a combo field that includes multiple select.

---
Tags: ajax, entities
---


# Question
Title: How can I prevent Drupal from saving the user's initial email address? (init in the users_field_data table)?
I am trying to reduce the amount of PII (personally identifiable information) that my site collects.

When a user registers an account, by default, that email address is saved twice in the `users_field_data` table-- once to the `mail` column, and again to the `init` column. This may be useful for some sites, but as far as I know core never uses the `init` value for anything, and so I would like to prevent any value being saved to `init`.

# Answer
> -1 votes
Looking into this, the initial email is only collected automatically if the user registers using the registration form; decoupled registrations do not have `init` set.

I know the general recommendation is not to patch core, but in this case it's a single line:

```
diff --git a/core/modules/user/src/RegisterForm.php b/core/modules/user/src/RegisterForm.php
index 0a4da2dcf1..cf2fdd159b 100644
--- a/core/modules/user/src/RegisterForm.php
+++ b/core/modules/user/src/RegisterForm.php
@@ -81,7 +81,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $form_state->cleanValues();

     $form_state->setValue('pass', $pass);
-    $form_state->setValue('init', $form_state->getValue('mail'));
+    // $form_state->setValue('init', $form_state->getValue('mail'));

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

```

---
Tags: users
---


# Question
Title: Column of owner of webform submission in database
I need to find the column of the owner (user\_id) of form submission in webforms. I need it in order to create some complex queries for the needs of the client. I looked in webform\_submission\_data and webform\_submission tables but I was not able to find it. Does exist in some other table?

# Answer
found it, it was uid in webform\_submission\_data table. I couldnt find it, because it was hidden from phpmyadmin
> 0 votes

---
Tags: users, webforms
---


# Question
Title: How to control pagination and data merge display when using view attachments
Now I have a requirement to display the activity data in the activity list: Judging by the current time, the activities that are about to start are sorted in ascending order; the activities that are starting or have ended are sorted in descending order. Note: Upcoming data should come first, followed by past data.

I used the view's attachment to achieve this:

1. The main view shows upcoming events
2. The attachment shows the activity that is in progress or has ended

Now there are two more questions:

1. The data of the main view and attachments are separated, but I actually want to display them together; for example: my list should display 4 pieces of data in one row, but the main view has only three pieces of data, and the result is that the data of the attachments does not follow the main The view displays, but starts to display on a new line, and the first line has only three pieces of data; what I want is that the first three pieces of the first line are the main view data, and the fourth piece is the first data of the attachment.
2. Both the main view and the attachment have a paging bar, and I only want one paging bar, and the data of the main view and the attachment are merged and paginated.

# Answer
> 0 votes
I used another method to complete my needs, I don't need multiple views：

```
function MODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'events') {
    $query->orderby = [];
    $query->addOrderBy(NULL, '(table.field_date<CURDATE())', 'ASC', 'all_date');
    $query->addOrderBy(NULL, '(greatest(table.field_date,CURDATE()))', 'ASC', 'now_date');
    $query->addOrderBy(NULL, '(least(CURDATE(),table.field_date))', 'DESC', 'old_date');
  }
}
enter code here

```

refer to: https://stackoverflow.com/questions/25892421/sort-records-by-future-asc-past-desc

---
Tags: views
---


title: Load a media entity/object from a fid?

text:
# Question
Title: Load a media entity/object from a fid?
I have the file ID (fid), and the rest of the file object.

I need to get fields from the parent media entity, but I can't find anything about loading a media entity from a file object.

Drupal 8.4.0

**Update**

I asked this question in relation to another: Media name as link to file

As far as I could find Kevin's comment is correct.

# Answer
Using the service `file.uses` you get the file media object:

Example:

```
$file is a loaded file object.
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

```

`$result` should now contain an array like so:

```
$result['file']['media']['4372'] = 2;

```

Where `4372` is the media id. and `2` the times the file is used.

From the docs of `listUsage`:

```
@return array
   *   A nested array with usage data. The first level is keyed by module name,
   *   the second by object type and the third by the object id. The value of
   *   the third level contains the usage count.

```
> 6 votes

# Answer
I recently needed to do the same, and came up with the following. First, load the file entity from the fid:

```
$fid = 1000;
$file = \Drupal\file\Entity\File::load($fid);

```

Then, call file\_get\_file\_references on the file entity:

```
$references = file_get_file_references($file);

```

Per the docs, you will get back a nested array of the referencing field names, entity types, entity ids, and finally the referencing entity itself.
> 3 votes

# Answer
```
use Drupal\media\Entity\Media;
use Drupal\node\Entity\Node;

function myFunction() {
  $node_load = Node::load($nids);
  $media_field = $node_load->get('media_field_machine_name')->getString();
  $media_entity_load = Media::load($media_field);
  $uri = $media_entity_load->field_media_video_file->entity->getFileUri();
  $banner_media_url = file_create_url($uri);
}

```
> 1 votes

# Answer
`$file` is a the loaded file object.

```
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

```

Is very relevant answer and more optimized result.
> 0 votes

---
Tags: entities, files
---


title: Default value of a 'managed file' field

text:
# Question
Title: Default value of a 'managed file' field
I created an edit custom form (of a node) via a custom module. From this form, I have a "managed file" field (for one picture) and I set his default value to a fid; However, when my form is rendered, the "managed file" field doesn't show the image ratached. I don't understand why

My code :

```
$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => 10, //Set 10 for the test, the fid "10" exist, I checked
);

```

My form rendered:

As you see, no image is loaded whereas the default\_value is set to an existing fid (10)

# Answer
> 17 votes
For a *managed file* form element, #default\_value is an array containing the file ID, as in the following code.

```
$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => array(10),
);

```

# Answer
> 1 votes
In My case i needed to add default files to a multiple managed file field element in drupal 8. my filed name was "field\_dpe\_submission\_file"

```
  $fids = [
      10,
      11,
      12,
    ];

function setDefaultsForFileField(array &$form, $fids) {
    $widget_clone = $form['field_dpe_submission_file']['widget'][0];
    $form['field_dpe_submission_file']['widget']['#file_upload_delta'] = count($fids);
    $form['field_dpe_submission_file']['widget']['#value'] = null;
    $form['field_dpe_submission_file']['widget']['#defaults_loaded'] = TRUE;
    foreach ($fids as $key => $value) {
      $value = (int) $value;
      $form['field_dpe_submission_file']['widget'][$key] = $widget_clone;
      $file_array = [
        'fids' => [
          $value,
        ],
        'display' => '1',
        'description' => '',
        'upload' => ''
      ];
      $form['field_dpe_submission_file']['widget'][$key]['#value'] = $file_array;
      $form['field_dpe_submission_file']['widget'][$key]['#default_value'] = $file_array;
      $form['field_dpe_submission_file']['widget'][$key]['#input'] = TRUE;
      $form['field_dpe_submission_file']['widget'][$key]['#delta'] = $key;
      $name = 'field_dpe_submission_file[' . $key . ']';
      $form['field_dpe_submission_file']['widget'][$key]['#name'] = $name;
      $form['field_dpe_submission_file']['widget'][$key]['#theme'] = 'file_managed_file';
      $form['field_dpe_submission_file']['widget'][$key]['#multiple'] = FALSE;
      $form['field_dpe_submission_file']['widget'][$key]['fids'] = [
        '#type' => 'hidden',
        '#value' => [
          $value,
        ],
        '#theme' => 'input__hidden'
      ];
    }
    // Add the default widget back in.
    $count = count($fids);
    $form['field_dpe_submission_file']['widget'][$count] = $widget_clone;
  }
?>

```

# Answer
> 0 votes
Simple settings form with Managed file field with default value:

Config file form:

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

$form['static'] = [
  '#type' => 'details',
  '#title' => t('Static Files'),
  '#open' => TRUE,
];

$form['static']['upload'] = [
  '#type' => 'managed_file',
  '#title' => t('File Upload.'),
  '#progress_indicator' => 'bar',
  '#progress_message'   => t('Please wait...'),
  '#upload_location' => 'public://static',
  '#description' => 'Allowed formats: jpg img png svg woff woff2, File location: public://static',
  '#upload_validators'  => [
    'file_validate_extensions' => ['jpg img png svg woff woff2'],
  ],
  '#default_value' => $config->get('upload'),
  '#multiple' => TRUE,
];
}

```

Form Submit:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);

if ($file_id = $form_state->getValue(['upload', '0'])) {
  $file = File::load($file_id);
  $file->setPermanent();
  $file->save();
}

  $config = $this->config('bk.settings');
  $config->set('upload', $form_state->getValue('upload'));
  $config->save();
}
}

```

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


title: redirection in htaccess file

text:
# Question
Title: redirection in htaccess file
I'm working on Drupal7.

I want to redirect all the URl's to external domain except some. Below rewrite I have added in .htaccess file and its working fine.

```
RewriteCond %{REQUEST_URI} !/user.*$
RewriteCond %{REQUEST_URI} !/testurl.*$
RewriteRule .* https://abcxyz.com [R=301,L]

```

But then, homepage also redirecting to https://abcxyz.com

How to stop homepage redirection or how to add homepage in the exclude list like user, testurl?

I have tried below to exclude the homepage in the redirection.

```
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !/index.php$
RewriteCond %{REQUEST_URI} !/homepage$

```

But nothing worked.

Can you help me on this please?

# Answer
> 0 votes
I had the same problem migrating to a new domain but needed to keep the services endpoints active on old domain since they were externally active. The key was including a RewriteCond for index.php:

```
RewriteCond %{REQUEST_URI} !^/services/active/endpoint$
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{HTTP_HOST} ^old-domain\.org$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://new-domain/$1 [L,R=301]

```

---
Tags: 7, redirection, .htaccess
---


# Question
Title: How to custom output a media paragraph from within a custom block?
I have a two-column custom block type that has two fields `field_content_left` and `field_content_right` which are entity reference revisions to allow the use of my other paragraph types.

One of my referenced paragraph types is a media one which allows for your standard media.

For my particular case, when I create a twig template file for this specific block (`block--homepage-blk-1.html.twig`) and use `{{ content.field_content_left }}`, the image that I placed in my left column is placed and that's great.

My only issue is that it's displaying it in the default media/image format of `Large (480x480)`.

Is there a way from within this custom block twig template for me to grab the image data and then override it with my other custom image format of `homepage`? I've tried different things with kint like `{{ kint(content.field_content_left[0]['#paragraph'].field_media[0])` to try and access the image but can't seem to get there.

Any suggestions? Am I looking at this the wrong way? Let me know if there is a better way to go about this or if I can access all the data I need (the image/alt/image URL + overriding image style).

---

My code in that part of the block currently looks like this but want to override that left section in order to customize how the image will look on the homepage.

```
<div class="row">
    <div class="col-lg-5 mb-3 mb-lg-0">
        {{ content.field_content_left }}
    </div>
    <div class="col-lg-6 offset-lg-1 mx-auto my-auto">
        <h2 class="mb-4">{{ content.field_block_title }}</h2>
        {{ content.field_content_right }}
    </div>
</div>

```

# Answer
Better start with the `block_content` entity to get the paragraph entity and then the media entity:

```
{% set paragraph = elements.content['#block_content'].field_content_left.entity %}
{% set media = paragraph.field_media.entity %}

```

Now you can render the image:

```
<img src="{{ file_url(media.field_media_image.entity.uri.value) }}">

```

For image styles you need the module Twig Tweak:

```
{% set image_uri = media|file_uri %}
{% if image_uri is not null %}
  {% set alt = media.field_media_image.alt %}
  {% set title = media.field_media_image.title %}
  <p>Image rendered via image.html.twig:
  {{ drupal_image(image_uri, 'thumbnail', {alt: alt, title: title}) }}
  </p>
  <p>Image tag placed directly in the block template:
  <img src="{{ image_uri|image_style('thumbnail') }}" alt="{{ alt }}" title="{{ title }}">
  </p>
{% endif %}

```
> 1 votes

---
Tags: theming, blocks
---


title: Views aggregation summary

text:
# Question
Title: Views aggregation summary
I am creating a stats page for a football (american) team in Drupal 7 and I am having issues summarizing the data. I have the following fields aggregated in a views table. Each is a summary of the individual players for each game.

Game 1 , Passing Yards, Long Pass, Rushing Yards, Long Rush, etc

Game 2 , Passing Yards, Long Pass, Rushing Yards, Long Rush, etc

I want to print a summary line at the bottom that totals up the season.

I have tried the views\_calc module, but I would rather print the summary as one line instead of a separate line for the sum and max fields.

Any help would be greatly appreciated

# Answer
Late but might be useful for someone, you can use views\_summarize module. Note: If you want to take export of your views using views\_data\_export module than views\_summarize will create issues.
> 0 votes

# Answer
You have two options that works for Drupal 7 and Drupal +8:
> 0 votes

---
Tags: views, css-js-aggregation
---


# Question
Title: Why does ckeditor_config make it impossible to update Composer packages?
I've got a Drupal 9.4 site that I've upgraded my database stack (XAMPP dev stack) to the latest version that is using php 8.1, but now have package incompatibilities showing up when I try to run "composer udpdate". Even trying to update with all dependencies fails. My site runs fine, however I can no longer update anything in composer without fixing whatever dependency issues there are. This is what it tells me are the problems:

```
Problem 1
- zendframework/zend-feed[dev-master, dev-develop, 2.11.0, ..., 2.13.x-dev] require php ^5.6 || ^7.0 -> your php version (8.1.6) does not satisfy that requirement.
- laminas/laminas-feed[2.12.0, ..., 2.12.x-dev] require php ^5.6 || ^7.0 -> your php version (8.1.6) does not satisfy that requirement.
- symfony/psr-http-message-bridge[v1.1.0, ..., 1.1.x-dev] require php ^5.3.3 || ^7.0 -> your php version (8.1.6) does not satisfy that requirement.
- symfony-cmf/routing[1.4.0-RC1, ..., 1.4.x-dev] require php ^5.3.9|^7.0 -> your php version (8.1.6) does not satisfy that requirement.
- symfony/psr-http-message-bridge[v1.2.0, ..., v1.3.0] require php ^7.1 -> your php version (8.1.6) does not satisfy that requirement.
- laminas/laminas-feed[2.13.0, ..., 2.14.x-dev] require php ^7.3 || ~8.0.0 -> your php version (8.1.6) does not satisfy that requirement.
- drupal/core[8.9.11, ..., 8.9.x-dev] require php ^7.0.8 -> your php version (8.1.6) does not satisfy that requirement.
- drupal/ckeditor_config[3.0.0-beta1, ..., 3.x-dev] require drupal/ckeditor ^8.5 -> satisfiable by drupal/core[8.5.0-alpha1, ..., 8.9.x-dev].
- drupal/core[8.5.0-alpha1, ..., 8.7.7] require symfony-cmf/routing ^1.4 -> satisfiable by symfony-cmf/routing[1.4.0-RC1, ..., 1.4.x-dev].
- drupal/core[8.7.8, ..., 8.9.10] require symfony/psr-http-message-bridge ^1.1.2 -> satisfiable by symfony/psr-http-message-bridge[v1.1.2, 1.1.x-dev, v1.2.0, v1.3.0].
- drupal/core[8.8.0-alpha1, ..., 8.8.x-dev] require zendframework/zend-feed ^2.12 -> satisfiable by laminas/laminas-feed[2.12.0, ..., 2.19.x-dev], zendframework/zend-feed[2.12.0, 2.12.x-dev, 2.13.x-dev].
- Root composer.json requires drupal/ckeditor_config ^3.0 -> satisfiable by drupal/ckeditor_config[3.0.0-beta1, 3.0.0, 3.1.0, 3.x-dev].

```

My composer.json file looks like this:

```
    {
    "name": "drupal/recommended-project",
    "description": "Project template for Drupal 8 projects with a relocated document root",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "homepage": "https://www.drupal.org/project/drupal",
    "support": {
        "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
        "chat": "https://www.drupal.org/node/314178"
    },
    "repositories": [
        {
            "type": "path",
            "url": "web/modules/custom/*"
        },
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.7",
        "drupal/acl": "^1.0@beta",
        "drupal/admin_toolbar": "^3.1",
        "drupal/ckeditor_config": "^3.0",
        "drupal/config_inspector": "^1.3",
        "drupal/console": "^1.9",
        "drupal/content_access": "^1.0@alpha",
        "drupal/content_browser": "^1.0",
        "drupal/core-composer-scaffold": "^9.4",
        "drupal/core-project-message": "^9.4",
        "drupal/core-recommended": "^9.4",
        "drupal/csp": "^1.15",
        "drupal/d8w3css": "^2.0",
        "drupal/devel": "^5.0.0-beta1",
        "drupal/devel_entity_updates": "^4.0",
        "drupal/domain": "^1.0@beta",
        "drupal/domain_group": "^2.0",
        "drupal/domain_site_settings": "^1.3",
        "drupal/dropzonejs": "^2.4",
        "drupal/dynamic_entity_reference": "^1.12",
        "drupal/editor_advanced_link": "^1.8",
        "drupal/entity_browser": "^2.5",
        "drupal/entity_embed": "^1.1",
        "drupal/fancy_file_delete": "^2.0",
        "drupal/file_delete": "^1.0",
        "drupal/filefield_paths": "^1.0@beta",
        "drupal/formblock": "^2.0@beta",
        "drupal/gdoc_field": "^1.1",
        "drupal/group": "^1.5",
        "drupal/groupmedia": "^2.0@alpha",
        "drupal/ief_table_view_mode": "^2.2",
        "drupal/inline_entity_form": "^1.0@RC",
        "drupal/item_bucket": "*",
        "drupal/jsonapi_extras": "^3.19",
        "drupal/jsonapi_include": "^1.4",
        "drupal/libraries": "^3.0@beta",
        "drupal/media_bulk_upload": "^3.0",
        "drupal/media_directories": "^2.0",
        "drupal/media_entity_instagram": "^3.0",
        "drupal/multiple_fields_remove_button": "^1.0@alpha",
        "drupal/pathauto": "^1.8",
        "drupal/pdf": "^1.1",
        "drupal/profile": "^1.2",
        "drupal/rabbit_hole": "^1.0@beta",
        "drupal/responsive_menus": "^1.x-dev",
        "drupal/restui": "^1.20",
        "drupal/rules": "^3.0@alpha",
        "drupal/showcase_lite": "^1.3",
        "drupal/taxonomy_manager": "^2.0",
        "drupal/textarea_widget_for_text": "^1.2",
        "drupal/video_embed_spotify": "^1.5",
        "drupal/weight": "^3.3",
        "drush/drush": "^11",
        "kint-php/kint": "^4.2"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true,
        "allow-plugins": {
            "composer/installers": true,
            "drupal/console-extend-plugin": true,
            "cweagans/composer-patches": true,
            "drupal/core-composer-scaffold": true,
            "drupal/core-project-message": true
        }
    },
    "extra": {
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
            }
        },
        "installer-paths": {
            "web/core": [
                "type:drupal-core"
            ],
            "web/libraries/{$name}": [
                "type:drupal-library"
            ],
            "web/modules/contrib/{$name}": [
                "type:drupal-module"
            ],
            "web/profiles/contrib/{$name}": [
                "type:drupal-profile"
            ],
            "web/themes/contrib/{$name}": [
                "type:drupal-theme"
            ],
            "drush/Commands/contrib/{$name}": [
                "type:drupal-drush"
            ],
            "web/modules/custom/{$name}": [
                "type:drupal-custom-module"
            ],
            "web/themes/custom/{$name}": [
                "type:drupal-custom-theme"
            ]
        },
        "drupal-core-project-message": {
            "include-keys": [
                "homepage",
                "support"
            ],
            "post-create-project-cmd-message": [
                "<bg=blue;fg=white>                                                         </>",
                "<bg=blue;fg=white>  Congratulations, you’ve installed the Drupal codebase  </>",
                "<bg=blue;fg=white>  from the drupal/recommended-project template!          </>",
                "<bg=blue;fg=white>                                                         </>",
                "",
                "<bg=yellow;fg=black>Next steps</>:",
                "  * Install the site: https://www.drupal.org/docs/8/install",
                "  * Read the user guide: https://www.drupal.org/docs/user_guide/en/index.html",
                "  * Get support: https://www.drupal.org/support",
                "  * Get involved with the Drupal community:",
                "      https://www.drupal.org/getting-involved",
                "  * Remove the plugin that prints this message:",
                "      composer remove drupal/core-project-message"
            ]
        }
    }
}

```

I've tried individually updating each listed dependency, (ie composer update zendframework/zend-feed -W), etc, and they seem to run, but no updates are found and nothing is changing. How can I correct these dependency issues?

# Answer
> 1 votes
The problem package is `drupal/ckeditor_config`. This is a packaging bug that is being discussed in these issues:

---
Tags: composer
---


title: Preprocessing twig templates

text:
# Question
Title: Preprocessing twig templates
I currently have two templates, one of which is *page.html.twig*, which is the main page and I can preprocess with `MYTHEME_preprocess_page()`. `MYTHEME_preprocess_page()` affects all the other pages in different modules.

The other template is *\_carousel.html.twig* (theme/templates/includes/\_carousel), which I include into *page.html.twig*, but I cannot hook into it with `MYTHEME_preprocess__carousel()`.

Is this the default behavior, or am I missing something?

# Answer
> 0 votes
`hook_preprocess_page()` is invoked for every page Drupal renders. That's why it needs to check for which page is invoked, if it really needs to preprocess specific pages.
A preprocess hook isn't invoked for template files that are included from other template files.

For both the cases, the answer is yes, that is default, expected behavior.

---
Tags: theming, 9
---


# Question
Title: How can I catch a login event in a subscriber?
I've got an event that is triggered on hook\_user\_login in a module.

```
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch('mymodule_user_login', $event);

```

I also have a subscriber that I think should be catching this event.

```
public function mymodule_user_login(GetResponseEvent $event) {...

static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['mymodule_user_login', 1];
    return $events;
}

```

The event seems to fire when I log in, however the subscriber runs on every page load afterwards.

Do I need to somehow clear the event in the subscriber?

# Answer
Your code is subscribing to a kernel event KernelEvents::REQUEST dispatched on every request.

But you want to subscribe to the custom event `'mymodule_user_login'`. The array value is the callback method, not the event name

```
static function getSubscribedEvents() {
    $events['mymodule_user_login'][] = ['onUserLoginCallback', 1];
    return $events;
}

```

which receives the custom event object, not a core event:

```
public function onUserLoginCallback(MyEvent $event) {
  ...
}

```

BTW the dispatching code is deprecated. In Drupal 9 or higher swap both arguments:

```
$event_dispatcher->dispatch($event, 'mymodule_user_login');

```

See https://symfony.com/blog/new-in-symfony-4-3-simpler-event-dispatching
> 1 votes

---
Tags: event-subscribers
---