# Question
Title: How do I take the value of a variable from the node template and insert it into the field value?
In the template of the material type node there is a variable that adds and multiplies integers according to the formula, which I take from the filled fields of the node. Everything is working properly.

An example in which the variable "result\_value" in the node template is assigned a value calculated by the formula:

```
{% set result_value = (5 + portfolio_result_value) * portfolio_event_status_value * portfolio_participant_value / portfolio_worker_value / program_form_value %}

```

At the output I get a number, for example 180. Next, at the moderation stage, I enter it manually in the "result" field of the "decimal number" type.

The question is, how do I pass the value of the variable "result\_value" to the result field automatically after creating a node or when launching crowns?

# Answer
The correct answer in my case is either to write your own module with your own logic, which will substitute the necessary values into the fields through hooks:

* hook\_entity\_presave() - will add when creating the material
* hook\_entity\_upadte() - will add it after updating the material

Or use a ready-made mathematical expressions module, I used this one: https://www.drupal.org/project/field\_expression

The module adds a special type of field in which, using tokens, you can substitute and calculate the values of the material fields according to the desired formula. The value is recalculated every time the material is updated and stored in the database, it can be output in a template or used to implement some other logic.

In my case, I use the taxonomy field in the material, the user selects a term from a certain dictionary. Each term has a numeric field where a certain score is stored, this field is easy to output via tokens, and the score can always be easily changed if necessary.

In the final value of the field looks like this:

```
(5+[node:field_portfolio_result:entity:field_competitive_events_score])*[node:field_portfolio_event_status:entity:field_competitive_events_score]*[node:field_portfolio_participant_sum:value]/[node:field_portfolio_worker]/[node:field_portfolio_participat_form:entity:field_competitive_events_score]

```

Also in one place I needed to substitute the number of elements that I refer to through the reference field. In tokens, it was not possible to output this as a number, so I used this module, which simply adds a field formatter that counts the number of elements and outputs a number: https://www.drupal.org/project/field\_count\_formatter. I installed it, turned on the "Token" viewing mode for my material, and there, in the field display settings, I chose the way to display the field I needed. As a result, everything works as I need it.

There is a similar module for Views, so that it is possible to perform mathematical calculations in the view: https://www.drupal.org/project/views\_simple\_math\_field

There is also a module that allows you to add the values of other Views fields: https://www.drupal.org/project/views\_cumulative\_field
> 0 votes

---
Tags: 9
---


# Question
Title: After installation, pages do not use any CSS style
I installed Drupal on Ubuntu 22.24. I'm able to get everything done, but after the installation, the next page is all messed up and I have no other permission besides looking at this page.

How can I fix this issue?

I ran `chown -R www-data: /var/www/html/` and `chmod -R 775 /var/www/html/`; if I messed something up with permissions that'll be great!

This is the error I'm getting from the f12 in the browser.

# Answer
> -1 votes
You probably need to set write access (recursively) for the following directories:

```
/sites/default/files

```

OR

```
/sites/default/files/js
/sites/default/files/css
/sites/default/files/php

```

---
Tags: installation
---


# Question
Title: Set a dynamic meta title on Node with MetaTag module installed
I've got one specific node where I need to dynamically set the meta title. The logic to determine the correct title is too involved to express in tokens; I need to do it in code.

It seems that I should be able to override the title using the `hook_preprocess_html`; I get the current title, and replace it with the proper title.

After I set the title here though, the Metatag module (8.x-1.26) waltzes in, and replaces my meticulously assembled title by its own fairly generic pattern generated title. I suppose I could try using the same hooks that Metatag uses to try to outsmart it, but that seems like a fragile approach.

Is there a better way, maybe through Metatag itself?

# Answer
> 0 votes
The best solution in my case turned out to be to simply override the value of the 'current-page:title' token. This is the token I used in my metatags pattern, and could be easily overriden in hook\_tokens\_alter.

Other solutions I tried which worked to some degree:

* Using hook\_metatags\_alter to override the metatags
* Hijacking the \_title\_callback on the entity.node.canonincal route

---
Tags: meta-tags, 10
---


title: How to unlink the site name?

text:
# Question
Title: How to unlink the site name?
Core with Olivero theme.

The site name is a link and I want to unlink it.

I want to do it because I already link to the homepage from the main menu and don't want two links to the homepage from the same place (`header`) and I also don't want to waste even one link-crawl of a given crawling budget.

How to unlink a site name?

# Answer
> 0 votes
Override the `block--system-branding-block.html.twig` theme file. Most core themes have something like this in it:

```
{% if site_name %}
    <a href="{{ path('<front>') }}" rel="home">{{ site_name }}</a>
{% endif %}

```

In your override template, remove the `<a>` tag.

---
Tags: blocks, 10
---


# Question
Title: Is it possible to make a theme hook suggestion for blocks according to content type?
I was hoping it was possible to do something similar to this for menus:

```
 * Implementation of hook_theme_suggestions_HOOK_alter() for menus.
 *  * Make menus themeable:
 * e.g. => menu--main--node-type--page.html.twig
 */
function MYTHEME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__%';
    $suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__'.$content_type;
  }
}

```

But for blocks, because the main navigation block suggestions look like this for me:

```
 * block--system-menu-block--main.html.twig
 * block--system-menu-block.html.twig
 * block--system.html.twig
 * block.html.twig

```

And I was hoping that I could have something like `block--system-menu-block--main--page.html.twig`?

# Answer
> 0 votes
After trying more solutions in different answers, modifying this one finally worked for me: How to make a theme hook suggestion for blocks according to region?

```
use Drupal\block\Entity\Block;

function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $content_type = $node->bundle();
      $suggestions[] = 'block__'.$variables['elements']['#id'].'__node_type__'.$content_type;
    }
  }
}

```

---
Tags: theming, blocks
---


# Question
Title: How do I fix a "Mismatched entity and/or field definitions" error on my configuration?
I'm getting the following error on my Drupal 8 configuration page.

> Entity/field definitions
> Mismatched entity and/or field definitions
> The following changes were detected in the entity type and field definitions.
>
> Content Update the node.rng\_capacity field. Update the node.rng\_registrants\_duplicate field. Update the node.rng\_registration\_groups field. Update the node.rng\_registration\_type field. Update the node.rng\_reply\_to field. Update the node.rng\_status field.

I'm not sure what caused these issues or how to go about resolving them. I think they may be leftover fragments/elements from when I deleted a registration or entity type.

# Answer
You can solve this issue by two ways.

If you installed Drush, you can run `drush entity-updates`. Otherwise, add the following lines in the index.php file located in the Drupal root folder, before `$response->send();` and reload the page.

```
try {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}
catch (EntityStorageException $e) {
  print_r($e);
}

```

Then remove the code from the *index.php* file.
> 11 votes

# Answer
**Solved!**

Method 1: Go to the admin/reports/status and find the field machine name.

For Example: "paragraph.field\_video\_upload". Edit the field storage settings and save the configuration again. That's it.

It works.

(or)

Method 2: If it's not working, please try the method below.

.install

```
<?php

/**
 * Implements hook_update_N().
 */
function HOOK_update_9001() {

  $entity_type_manager = \Drupal::entityTypeManager();
  $entity_type_manager->clearCachedDefinitions();

  $entity_type_ids = [];
  $change_summary = \Drupal::service('entity.definition_update_manager')->getChangeSummary();
  foreach ($change_summary as $entity_type_id => $change_list) {
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    \Drupal::entityDefinitionUpdateManager()->installEntityType($entity_type);
    $entity_type_ids[] = $entity_type_id;
  }

  return t("Installed/Updated the entity type(s): @entity_type_ids", [
    '@entity_type_ids' => implode(', ', $entity_type_ids),
  ]);
}

```

RUN drush cim & drush cr
> 24 votes

# Answer
`drush entity-updates` (aka `drush entup`) has been deprecated as of Drupal 8.7.0. You either need to write an update script using hook\_update\_N(), or you can use the Devel Entity Updates module, which does the same thing as `drush entup` did previous to 8.7.0.
> 18 votes

# Answer
Find the field in /admin/reports/fields. For each entity that uses the field, edit the field and save the parameters again.

This should be updating the database and make the entity and the field match again.
> 11 votes

# Answer
For Drupal 9, use devel\_entity\_updates module

```
composer require 'drupal/devel_entity_updates'
drush en devel_entity_updates
drush entity-updates

```

should fix the issue.
> 6 votes

# Answer
It is clearly written in the Devel Entity Updates:

**Do not use this to fix the Mismatched entity and/or field definitions error: again, this is not meant to fix production sites.**

This will not help these issues.

Here some links that could fix the issues:

https://www.drupal.org/project/paragraphs/issues/3062300 https://www.drupal.org/project/commerce/issues/2656896
> 4 votes

# Answer
For Drupal 8 and Drupal 9, there is the Entity Update module, which allows to update an entity schema with Drush or without it.

> The main objective of this module is to allow module developers and site administrators to update entity types schema even when entities have data.
> The update can be executed via Drush (recommended), from the web browser, or programmatically.
> The module also allows to view the list of entity types, the entity types update status, and show the content of an entity type.
> 1 votes

# Answer
For Drupal 10 or Migrated from Drupal 9 to Drupal 10, or migrated Contrib modules like `Paragraph`

You need to add `devel_entity_updates`

```
$ drush composer require 'drupal/devel_entity_updates:^4.1'

```

Then Enable

And Run the Drush command

```
$ drush devel_entity_updates

The following updates are pending:

paragraph entity type :
The paragraph.field_reusable_paragraph field needs to be updated.

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

 [success] Finished performing updates.

```

This resolved the above issue
> 0 votes

# Answer
You can Add **hook\_update\_N()** hook (in module\_name.install file): to fix Mismatched entity and/or field definitions error for Configuration

```
/**
 * Update the Paragraph field definitions for mismatched fields.
 */
function hook_update_N() {
  try {

    $entityTypeManager = \Drupal::entityTypeManager();

    // Get the media entity type.
    $paragraphEntityType = $entityTypeManager->getDefinition('paragraph');

    // Install the media entity type to ensure field updates.
    \Drupal::entityDefinitionUpdateManager()->installEntityType($paragraphEntityType);

  }
  catch (\Exception $e) {
    watchdog_exception('logger_name', $e, 'hook_update_N failed');
  }
}

```

**Note:** I used nkf\_update\_8901() for hook\_update\_N(), where module\_name : nkf, N denotes 8901

Follow this document to read more about hook\_update\_N() hook

**I have used this approach** to fix a "Mismatched entity and/or field definitions" error for Configuration **due to couple of reasons**:

**In some projects :**

* Lower(dev) env can use "devel entity updates" but on higher(stg/prod) it is not recommended to use "devel entity updates" module. so in this particular scenario this approach hook\_update\_N() can be used
* It also helps to keep track of recent changes related to particular entity updates of db at code level
> 0 votes

# Answer
You can use the below code(on module\_name.install file) to fix this mismatched entity issue. I tried this on Drupal 10 version. Please post your comment if you need any clarification on this.

```
/**
 *
 * Mismatched entity and/or field definitions Fix.
 */
function hook_update_N() {

  $entity_type_manager = \Drupal::entityTypeManager();
  $entity_type_manager->clearCachedDefinitions();
  $entity_type_ids = [];
  $change_summary = \Drupal::service('entity.definition_update_manager')->getChangeSummary();
  foreach ($change_summary as $entity_type_id => $change_list) {
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    \Drupal::entityDefinitionUpdateManager()->installEntityType($entity_type);
    $entity_type_ids[] = $entity_type_id;
  }
  drupal_flush_all_caches();
  return t("Installed/Updated the entity type(s): @entity_type_ids", [
    '@entity_type_ids' => implode(', ', $entity_type_ids),
  ]);
}

```
> 0 votes

---
Tags: 8, entities, configuration
---


title: Adding a default text

text:
# Question
Title: Adding a default text
Option 1: Is there any way to write a conditional in Twig that if field1 in Drupal is empty, I can set a default text to say "Bye"

Option 2: I was also trying to use the conditional fields module, to where field2(with the default text "Bye") will only display if field1 is empty. It doesn't seem to work though.

Any help is appreciated thank you

# Answer
Solution for option-1 :

```
{% if node.field_example.value is empty %}
   <span>Bye</span>
{% endif %}

```
> 1 votes

# Answer
Never tried with that dependency but option 2 should work, how are you setting the conditional field?

Anyway there's empty fields module that should solve your issue.
> 0 votes

---
Tags: 9
---


title: I can't upload images

text:
# Question
Title: I can't upload images
I can't upload images with CkEditor 5 in my Drupal 10.1.6 website (which runs on PHP 8.2); all the other features work fine.

>

In my recent upgrade of Drupal, I switched directly from Drupal 9.4 to Drupal 10.1.6. I followed Upgrading to CKEditor 5.

I've seen ckeditor5 upload image MethodNotAllowedException where they talk about this problem. Spokje's comment says that issue is a duplicate of AccessAwareRouter does not respect HTTP method which has been already fixed on September 18, 2023. So normally the issue should not re-appear, shouldn't it?

I also already seen Why is MethodNotAllowedException thrown when an image is uploaded with CKEditor 5? but I can't find the user settings where I could change the language to default. In my website, we don't use this field on user. We just have *first name*, *last name*, *email*, *password*, and *state*.

I've enabled *Account administration pages* on /admin/config/regional/language/detection (*Detection and selection*).

In my admin profile, I can just update my mail or the password.

I can't find where the problem is. I have the Editor Advanced Link module installed, but that is compatible with Drupal 10 and CkEditor 5. (I've tested it.)

Can you help me please? I do not see errors in the Drupal log.

# Answer
I found the error, I had **restricted access for the admin** on the website with a function "isAllowedPath" on a AdminEventSuscriber. So we were redirected automatically to home admin (people list) page.

```
   * Restrict the access to some paths for the admin.
   *
   * @param string $path
   *
   * @return bool
   */
  protected static function isAllowedPath(string $path): bool {
    return str_starts_with($path, '/admin') ||
      str_starts_with($path, '/editor') ||
      str_starts_with($path, '/entity_reference_autocomplete') ||
      str_starts_with($path, '/ckeditor5') || // Fix here --> Adding Ckeditor5 path
      $path === '/user/{user}/masquerade' ||
      $path === '/unmasquerade' ||
      $path === '/dqe/check' ||
      $path === '/views/ajax' ||
      $path === '/navigate/as/{user}' ||
      $path === '/user/logout' ||
      $path === '/system/files/{scheme}' ||
      preg_match('#^/sites/[a-z]{3}/files/styles/{image_style}/{scheme}#i', $path) === 1 ||
      preg_match('#^/editor/dialog/image/{editor}#i', $path) === 1 ||
      preg_match('#^/profiler#i', $path) === 1 ||
      preg_match('#^/cron#i', $path) === 1 ||
      preg_match('#^/views-bulk-operations#i', $path) === 1 ||
      preg_match('#^/batch#i', $path) === 1;
  }

```
> 0 votes

---
Tags: media, updating, 10
---


# Question
Title: Preprocess variables only for certain blocks
Is it possible preprocess variables only for certain blocks? I created `mytheme_preprocess_block__aggregator(&$vars)`, but it doesn't work.

# Answer
Unfortunately, there is no way to do it like that (similar to hook\_form\_alter()).

The best way to do this would be to use $variables\['block'\]-\>bid to apply modifications only to the blocks you want:

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['block']->bid === 'target_block_id') {
    // do something for this block
  } else if ($variables['block']->bid === 'other_target_block_id') {
    // do something else for this other block
  }
}

```
> 20 votes

# Answer
Just to confirm, in Drupal 8 you can write preprocess functions for specific blocks. For example:

**Drupal 8**

```
mytheme_preprocess_block__system_branding_block(&$vars) {
  // Make changes to the the system branding block
}

```

But you could also use hook\_preprocess\_block, and the plugin ID:

```
function mytheme_preprocess_block(&$vars) {
  if ($vars['plugin_id'] == 'system_branding_block') {
    // Make changes to the the system branding block
  }
}

```

As mentioned by Alex, in Drupal 7 you'll have to stick with HOOK\_preprocess\_block, and an id check:

**Drupal 7**

```
mytheme_preprocess_block(&$vars) {
  if ($vars['block']->bid === 'target_block_id') {
    // make changes to this block
  }
}

```
> 12 votes

# Answer
In Drupal 10 (presumably 8 & beyond), you can dig into the `$vars` array to isolate a particular block type/bundle:

```
function mytheme_preprocess_block(&$vars){
  $block_content = $vars['elements']['content']['#block_content'];
  if($block_content instanceof \Drupal\block_content\Entity\BlockContent) {
    $block_type = $block_content->bundle();
    // Logic here based on a (custom) block type/bundle.
  }
  else{
    /* A variety of system-generated blocks (logo, menu, etc.)
       will have other kinds of info in $vars['elements']['content']
       you may be able to key off of.
       Views-generated blocks will also provide details
       about the View and display in $vars['elements']['content'].
    */
  }
}

```
> 0 votes

---
Tags: blocks
---


# Question
Title: Event listener for button intermittently fails to be added on home page
# Background

I have a filtered view for the content type "Change Requests" that I built as a page, and as a block. The block is added to the user's home page and only shows that user's change requests. The filters div was always visible, but I wanted it to be collapsed and to have a button which expands the filters when the user wants to change it.

I added a button, some custom styling to show/hide the filters block, and a jQuery file that finds the button ID and adds an event listener to it. This worked successfully at first, but then I noticed that when you refresh the home page, sometimes the event listeners are not added to the block and it does not function at all. The view page on the other hand works seemingly every time.

This seems to work sometimes but not other times. For example, sometimes the home page loads and the functionality works, but other times it does not. If I refresh the page a few times, it will load at least once without the event listener added. This also happens when I click the home page link or on first time load, and not just when I am refreshing the page.

# Setup

All three steps were used to alter or create files within my custom theme folder.

1. Altered `views-exposed-form.html.twig` and added a button after the filters div:

```
<div class="form--inline clearfix filters">
  {{ form }}
</div>
<button id="expand-filters" type="button" class="button" aria-pressed="false">filters</button>

```
2. Added some styling in the CSS to hide/show filters:

```
.filters {
  display: none;
}
.filters.visible {
  display: block;
}

```
3. Created a jQuery file that adds event listener to button to show/hide the filters div:

```
jQuery(document).ready(function($) {
    // Expand Filter Button
    $('#expand-filters').on('click', function() {
        $(this).toggleClass('active');
        $(this).attr('aria-pressed', $(this).attr('aria-pressed') === 'true' ? 'false' : 'true');
        $('.filters').toggleClass('visible');
    });
});

```

It seems to me that sometimes the files either don't execute after the document loads, or they execute before elements are loaded and thus fail to add the event listeners. That is my guess, as I don't fully understand why this isn't working in the block but is working in the view.

# Question

What is the right way to add this functionality so that it works every time, and not intermittently? I am open to solutions which add modules, but my preferred method is to add this functionality within the theme so that it works only by loading my custom theme into pages.

# Additional Info

This site is using Drupal 10 so I am trying to use any and all conventions that apply to Drupal 10.

# Answer
> 0 votes
After some research and help from the comments under my question, I found a solution that seems to work.

1. Use Drupal Javascript best practices

However, when I tried these instructions alone, I got the error:

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

```

I believe this is due to `jQuery.once()` being removed as of D10 and replaced with core/once

2. After further research, I found a very helpful post about how to Replace jQuery.once() with Javascript once().

Just to use a better example than in my above question, consider this jQuery:

```
jQuery(document).ready(function($) {
    // Expand Filter Button
    $('#expand-filters').on('click', function() {
        $(this).toggleClass('active');
        $(this).attr('aria-pressed', $(this).attr('aria-pressed') === 'true' ? 'false' : 'true');
        $('.filters').toggleClass('visible');
    });
});

```

Changing it to Drupal Behaviors looks like this:

```
(function ($, Drupal) {
  Drupal.behaviors.filterBehavior = {
    attach: function (context, settings) {
      $(once('filterBehavior', '#expand-filters', context)).each(function () {
        $(this).on('click', function(e) {
          $(this).toggleClass('active');
          $(this).attr('aria-pressed', $(this).attr('aria-pressed') === 'true' ? 'false' : 'true');
          $('.filters').toggleClass('visible');
        })
      })
    }
  };
})(jQuery, Drupal);

```

And in my `theme.libraries.yml` file, I added `core/once` to the dependencies:

```
dependencies:
    - core/drupal
    - core/jquery
    - core/once

```

Following these changes, I just cleared the caches and the issue seems to now be fixed.

---
Tags: theming
---


title: How to add a reset button to forms?

text:
# Question
Title: How to add a reset button to forms?
How do I add a reset button to a form? I have a form with a CKEditor and other fields, plus hidden fields. How do I reset the form so all fields are empty?

# Answer
> 0 votes
I was able to get this to work.

Within the buildForm() method, part of the form array contains this for the reset button:

```
$form['rmdrs_form_reset_button'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#limit_validation_errors' => TRUE,
    '#submit' => ['::reminderFormReset'],
  );

```

Also in that Form class I have method for handling the reset:

```
public function reminderFormReset($form, &$form_state) {
  $form_state->setRebuild(FALSE);
}

```

The downside is that it is, IMHO, a glorified page reload. The button acts like a submit button, but instead calls the reminderFormReset() method in the same class.

---
Tags: forms, 10
---


# Question
Title: Is there a module/way to send an email quarterly to a list of people about all the new content that has been published since the last email?
I need to be able to take all the users who sign up for updates on a webform and on an editable frequency email them the new content (that I choose to send them) that has been published since the last email. Do any of y'all know if there is a module/way currently that I can do that? And if not what the best way to do that would be?

As an example, how would I send all the people from this webform results list a quarterly email informing them of all the blog posts that have been published since the last quarter?

# Answer
> 1 votes
This is a really broad question so this will be a broad answer.

> how would I send all the people from this webform results list a quarterly email informing them of all the blog posts that have been published since the last quarter?

First, how to get a list of all blog posts that have been published since the last quarter? This can be done with the Views module; it's quite easy to generate a filtered list of content.

How to send the email? Well, I wouldn't use Webform for this; I would use Simplenews instead. This is by far the most popular Drupal module for mailing lists, and offers the great advantage of being open source, so you don't have to pay Mailchimp or another company for your newsletter. The disadvantage is that it is not super easy to set up.

---
Tags: emails
---


title: Set timestamp field default value empty

text:
# Question
Title: Set timestamp field default value empty
I have created field type "Timestamp" in my Drupal 8 node. Field is not required. In field settings default value, there is HTML 5 datetime picker, in which you can select default date/time or leave values as on picture:

But the Drupal behavior seem to be little bit strange - when you select default date, this value is set on node save (this is correct). When you leave field blank (values as on picture) it saves field with time of form submission (it is stated in field comment, so it is not a bug)... But how to disable default value, when you just want to leave field blank as it is possible with all other fields (e.g. text, number, ...)? I do not see any settings for this in this field configuration. Also this is not logical, beucase when you leave other fields blank, they are really blank. When you leave this field type blank, it still saves value (some additional checkbox will be more logical)?

Thanks

# Answer
There is backstory to this that is a little complicated.

The **Timestamp** field type was added back into Drupal 8.2.0 core as a "UI Field". The field type had always been there, just as a behind-the-scenes field, and used as the base field for `CreatedItem` and `ChangedItem` for entity timestamps (which are both non-UI field types).

If this field is rendered out on with the proper widget on the edit page (see bug), then you end up using `TimestampDatetimeWidget`. This widget has a `::massageFormValues()` method, which enforces the current time being used (at save) as the field value if the element is empty.

So, the behavior you are seeing is by-design. The widget was initially intended for entity edit pages, where created and changed timestamps never have empty values after the entity is saved. When this field was added as a UI field, it inherited the widget and its behavior.

If you really want a timestamp and don't want this behavior, you need to make a custom module and make your own widget. You should just be able to copy `TimestampDatetimeWidget` into the module, rename it, update the annotation, and update the `::massageFormValues()` method:

* remove the `else` branch containing `$date = new DrupalDateTime();` \- this won't set the default datetime
* handle unset `$date` variable, example: `$item['value'] = !empty($date) ? $date->getTimestamp() : NULL;`

That should allow you to have empty timestamps.

Personally, I would not use **Timestamp** fields, though. I would use **Date** fields, which can have empty values or default values, and better widgets and formatters in general.
> 12 votes

# Answer
Here is the quick solution: instead of timestamp use date field with datetime widget and convert the datetime to timestamp with strtotime() function.

Example:

```
$datetime = $node->get('field_date')->getValue()[0]['value'];
$timestamp = strtotime($datetime);

```
> 0 votes

# Answer
The below solution that worked for me as of drupal 10.

use case: I needed it for event time addition and I also needed both date & time fields.

//logic

Checked the last node updated time vs actual user time added. If the user time is same as last node updated time , then the field must be empty.(ignored some extreme cases where , both of them will be same since in my case most events will be some time in future not immediate)

//code

```
function __get_validated_timestamp_value($timestamp_field_name, $entity) {
    if($entity->get($timestamp_field_name)->getValue()) {
        $actual_value = $entity->$timestamp_field_name->getValue()[0]['value'];
        $node_submitted_time = $entity->getChangedTime();

        $field_item = $entity->get($timestamp_field_name);
        if ($field_item->isEmpty()) {
            return null;
        }
        if($actual_value == $form_submiited_time) {
            return null;
        }
        return $actual_value;
    }
    return null;
}

```

invoked and used like below

```
if($node->get('field_event_start_time')) {
 $start_timestamp = __get_validated_timestamp_value('field_event_start_time', $node);
}

```
> 0 votes

---
Tags: 8, entities, datetime
---


title: How to get paragraph field values?

text:
# Question
Title: How to get paragraph field values?
I'd like to create a product list in drupal and send it in a webservice. For this I created an entity type with paragraphs for each product. How can I load the paragraph and access its fields? Until now I see only the target\_id and target\_revision\_id of the product. Thanks!

```
$nodestorage = \Drupal::entityManager()->getStorage('node');
$productslist = $nodestorage->loadUnchanged(9)->toArray();
foreach($productslist['field_products'] as $prod) {
  debug($prod);
}

```

Result:

```
Array
(
  [target_id] => 1
  [target_revision_id] => 3
)

```

# Answer
You should be able to include the Paragraph entity class, and use `Paragraph::load($entity_id)` to load it.

Example:

```
use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($target_id);
$foo = $paragraph->field_name->value;

```
> 17 votes

# Answer
```
$paragraph = Paragraph::load($target_id);
// Paragraph type could be also useful.
$prgTypeId = $paragraph->getType();
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $prgMediaField */
$prgMediaField = $paragraph->get('field_media');
$prgMediaFieldValue = $prgMediaField->getValue();

```
> 11 votes

# Answer
I know this is old, but might be helpful for the future. To load entities referenced by a Node entity you can use the `entity` property. For example, consider the following code:

```
$nodestorage = \Drupal::entityManager()->getStorage('node');
$node = $nodestorage->loadUnchanged(9);

foreach ($node->field_products as $product) {

  /** @var Entity (i.e. Node, Paragraph, Term) $referenced_product **/
  $referenced_product = $product->entity;

  // Use now the entity to get the values you need.
  $field_value = $referenced_product->field_name->value;
}

```

So no need to load an entity by the entity id, you just simply user `->entity` property over a referenced list of entities.
> 10 votes

# Answer
The quickest way is to use `referencedEntities()`:

```
$nodestorage = \Drupal::entityManager()->getStorage('node');
$node = $nodestorage->loadUnchanged(9);
$products_list = $node->{'field_products'}->referencedEntities();

```
> 1 votes

---
Tags: entities, paragraphs
---


title: Allow certain user role to add tags

text:
# Question
Title: Allow certain user role to add tags
I have added a taxonomy entity reference on a node. I want users of certain roles to only select from the list and not allow them to create a new one.

A user role A to select from the list or add a new one.

I have checked the box in the reference field setting 'Create referenced entities if they don't already exist' and only administrator and user role A has permission to create/edit term. But still the form allows other users to add new term, how can I stop this?

# Answer
1. If you want specific roles to access denied on taxonomy term create/edit then you can set permission on taxonomy term.
2. If you want specific roles to access denied on node taxonomy field then you can use this module :"https://www.drupal.org/project/field\_permissions" and set permission.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How can I compare date time values in a content form?
I want to use `getString()` instead of `[0]['value']`. How do I do that, if it possible? Is there any other way?

This is the array I get when I run this code.

```
dump($form_state->getValue('field_start_time'));
dump($form_state->getValue('field_end_time'));
dump($form_state->getValue('field_duration'));
die();

```

```
array:1 [▼
  0 => array:1 [▼
    "value" => Drupal\Core\Datetime\DrupalDateTime {#2248 ▼
      #inputTimeRaw: ""
      #inputTimeAdjusted: ""
      #inputTimeZoneRaw: ""
      #inputTimeZoneAdjusted: ""
      #inputFormatRaw: ""
      #inputFormatAdjusted: ""
      #langcode: "en"
      #errors: []
      #dateTimeObject: DateTime @1700800785 {#2247 ▼
        date: 2023-11-24 04:39:45.0 UTC (+00:00)
      }
      #formatTranslationCache: null
      #stringTranslation: null
    }
  ]
]
 array:1 [▼
  0 => array:1 [▼
    "value" => Drupal\Core\Datetime\DrupalDateTime {#2222 ▼
      #inputTimeRaw: ""
      #inputTimeAdjusted: ""
      #inputTimeZoneRaw: ""
      #inputTimeZoneAdjusted: ""
      #inputFormatRaw: ""
      #inputFormatAdjusted: ""
      #langcode: "en"
      #errors: []
      #dateTimeObject: DateTime @1700807985 {#2211 ▼
        date: 2023-11-24 06:39:45.0 UTC (+00:00)
      }
      #formatTranslationCache: null
      #stringTranslation: null
    }
  ]
]
 array:1 [▼
  0 => array:2 [▼
    "duration" => DateInterval {#2340 ▼
      interval: + 02:00:00.0
      +"y": 0
      +"m": 0
      +"d": 0
      +"h": 2
      +"i": 0
      +"s": 0
      +"f": 0.0
      +"weekday": 0
      +"weekday_behavior": 0
      +"first_last_day_of": 0
      +"invert": 0
      +"days": false
      +"special_type": 0
      +"special_amount": 0
      +"have_weekday_relative": 0
      +"have_special_relative": 0
    }
    "seconds" => 7200
  ]
]

```

The code I am using in my module is the following one.

```
/**
 * Implements hook_form_alter().
 */
function ir_hiring_validation_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_exam_form' || $form_id == 'node_exam_edit_form') {
    $form['#validate'][] = 'ir_hiring_validation_validate';
  }
}

/**
 * Custom validation callback to check start time, end time, and duration.
 */
function ir_hiring_validation_validate($form, $form_state) {
  $start_time = $form_state->getValue('field_start_time')[0]['value'];
  $end_time = $form_state->getValue('field_end_time')[0]['value'];
  $duration_seconds = $form_state->getValue('field_duration')[0]['seconds'];
  if (strtotime($end_time) < strtotime($start_time)) {
    $form_state->setErrorByName('field_end_time', t('End time cannot be less than start time.'));
  }
  elseif (!empty($duration_seconds)) {
    $expected_end_timestamp = strtotime($start_time) + $duration_seconds;
    if (strtotime($end_time) != $expected_end_timestamp) {
      $form_state->setErrorByName('field_end_time', t('End time need to same as total time more than exam.'));
    }
  }
}

```

# Answer
> 2 votes
Instead of a string and strtotime() you could get the timestamp directly via the method getTimeStamp():

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

...

  if ($start_time instanceof DrupalDateTime && $end_time instanceof DrupalDateTime) {
    if ($end_time->getTimestamp() < $start_time->getTimestamp()) {
      $form_state->setErrorByName('field_end_time', t('End time cannot be less than start time.'));
    }
  }

```

# Answer
> 0 votes
`\DateTime` objects are directly comparable without having to resolve them to scalar values.

---
Tags: forms, 10
---


# Question
Title: Show menu links for anonymous users only
I need to show the user register link as a menu item in the `account` menu. I am able to add the link in the menu via `links.menu.yml`.

The menu links shows up for anonymous users as well as authenticated users but not for admin user role.

How can I hide the menu item for logged in users irrespective of user role?

# Answer
> 2 votes
Tried all the options to hide the menu item from authenticated users irrespective of the role, but admin always sees it. Did that using CSS and Menu Link Attributed module. Using the module I added a class to the menu link and then using the body class `user-logged-in` hid the menu item for logged in user.

I am still open to any other alternative and a better solution.

# Answer
> 2 votes
In case someone bumps here again, I found two ways it can be achieved within a theme without using any using module.

1) Using custom CSS:

```
.user-logged-in .menu.menu--account a[href="/user/register"] { display: none; }

```

2) Using custom JS:

```
$('.user-logged-in').find('.menu.menu--account a[href="/user/register"]').hide();

```

This is applicable only if you are customizing your theme in any way.

# Answer
> 0 votes
You can do this: group references in several menus: for registered - one for guests - another, etc. Then configure the units display, in which the menus are displayed on the page. The unit registered only show the registered menu.

# Answer
> 0 votes
Try the Menu Per Role Module. The new maintainer is trying to take over the drupal.org project but he has his code up on Github.

# Answer
> 0 votes
I can recommend the module Menu Item Role Access for this. It allows you to limit the access to a menu link by role. This can be configured for each menu link individually in its edit form. There you can also select it to be visible for Authenticated Users, which applies to all logged in users irrespective of other roles they may have.

---
Tags: users, 8, navigation
---


# Question
Title: How can the Webform element Form display defaults be set?
Every webform element has a little section like this:

Where can one set these defaults, for Title display location, Description display location, and Help display location?

It does not appear to be in any of the webform overall settings or webform specific settings.

If it's the default *for the element type*, is there a programmatic way to override the default (but not if set for an individual element)?

Doesn't matter much whether setting or overriding this default on a sitewide or webform-specific level, just want the ability to switch Title display from "Inline" to "Before" for all the elements on a form, as design requests change, without having to edit all individually.

# Answer
It looks default title display is set in Drupal core:

https://git.drupalcode.org/project/drupal/-/blob/9.5.x/core/lib/Drupal/Core/Form/FormBuilder.php#L923-930
> 1 votes

# Answer
Per Webform maintainer Jacob Rockowitz:

> In your theme or module you can create a `hook_preprocess_form_element()` which overrides the default #title\_display set via `template_preprocess_form_element()`.
>
> @see template\_preprocess\_form\_element().

Or:

> Maybe you can use hook\_webform\_element\_alter() to set the #title\_display before template\_preprocess\_form\_element() sets it.
>
> I specifically avoided implementing a customizable default #title\_display and #description\_display because some themes have different default #title\_display.

From How to set the default Title position for an element? (Issue #3003067 on Drupal.org)

So as ognockocaten suggests, 'default' means 'the default of Drupal' (or the theme if it alters this), not a default set in Webform.

Also, in my experience, Webform has minimal CSS to get this to work and is likely to fail depending on your theme's CSS, you may need to add styles in your theme for the classes `webform-element--title-inline > .label` and `webform-element--title-inline > .control` to ensure that the Inline option does indeed put the label and the input inline, for example.
> 0 votes

---
Tags: webforms
---


# Question
Title: How to convert context_definitions to PHP attribute syntax?
Drupal 10.2 enables PHP attributes to be used instead of annotations.

So I tried to create some PHP attributes for one of my blocks:

```
/**
 * Provides an 'Ebook Navigation' Block.
 *
 * @Block(
 *   id = "ebooknavigation_block",
 *   admin_label = @Translation("eBook navigation block"),
 *   category = @Translation("MyModule"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
 *   }
 * )
 */

```

This is what I came up witH:

```
use Drupal\Core\StringTranslation\TranslatableMarkup;

#[Block(
  id: 'ebooknavigation_block',
  admin_label: new TranslatableMarkup('eBook navigation block'),
  category: new TranslatableMarkup('MyModule'),
)]

```

However, I don't understand how to convert the `context_definitions` part.

# Answer
At the moment, only two annotation classes have been converted to attribute classes. Blocks defined by Drupal core modules still use annotations, like the `AnnounceBlock` class.

```
/**
 * Provides an 'Announcements Feed' block.
 *
 * @Block(
 *   id = "announce_block",
 *   admin_label = @Translation("Announcements Feed"),
 * )
 *
 * @internal
 */

```

Since attributes cannot be nested in attributes, once Drupal 10.2 gets its stable release, the annotation to use should be similar to the following one.

```
#[Block(
  id: 'ebooknavigation_block',
  admin_label: new TranslatableMarkup('eBook navigation block'),
  category: new TranslatableMarkup('MyModule'),
  context_definitions: array(new ContextDefinition("entity:node", new TranslatableMarkup("Node")))
)]

```
> 2 votes

---
Tags: blocks, 10
---


# Question
Title: How can I programmatically trigger a 403 error with a hook implementation?
In a module within a drupal hook I'd like to conditionally trigger a 403 for the user.

I could archieve this e. g. by throwing an exception

```
throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

```

But is this the right way to do it? I know that a redirect in general should not be done directly from a hook, in order to not break the chain of hooks to be executed, instead I should use a middleware like described e.g. in this answer

Is this relevant here, too? Do I have to write a middleware or stuff instead of throwing the exception within a hook, or does the exception not exit Symfony/Drupal within the hook, but "end" the process in a correct way?

I've seen the solution in combination with exit(), too

```
throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
exit();

```

but I think this would do exactly what I try to not do regarding the hook chain?

Thank you in advance!

# Answer
> 2 votes
Throwing the exception is the correct way for your code to stop building a 200 response and instead return a 403 response. Don't use exit(). The AccessDeniedHttpException is a specific exception class handled by a kernel exception subscriber returning the themed 403 page, which can be configured in admin UI.

If it's possible to determine the 403 situation in advance, then add an access callback to the route. Then you don't need to throw the exception later, because it is already checked in the routing process and this makes it possible to hide the link if the current user has no access to it.

---
Tags: hooks, redirection, 10
---


title: CKEditor returns a value as array

text:
# Question
Title: CKEditor returns a value as array
In my Form I have this entry that presents a CKEditor instance

```
$form['notes'] = array(
    '#input_format' => '1',
    '#rows' => '5',
    '#type' => 'text_format',
    '#base_type' => 'textarea',
    '#title' => t('Reminder Notes'),
  );

```

In the "values" array within my submit method I have this:

```
$form_state->getValue('notes'),

```

But when it saves the data it comes in with only the word "Array"

The install file schema is like this:

```
  'notes' => [
    'type' => 'text',
    'size' => 'medium',
    'not null' => FALSE,
    'description' => 'Notes to aid in managing the reminder',
  ],

```

How can I get this to save the data correctly rather than just giving the word "Array"?

# Answer
You have to define `#default_value` or `#value` as below

```
$form['notes'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Reminder Notes'),
  '#default_value' => '',
  '#format' => 'filtered_html',
  '#rows' => 5,
];

```

Then in your install file schema

```
function mymodule_schema() {
  $schema = array();

  // Define your custom table.
  $schema['mytable'] = array(
    'description' => 'Table for storing reminders',
    'fields' => array(
      'id' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Reminder notes',
      ),
      'notes' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'description' => 'notes to aid in managing the reminder',
      ),
      // Add other fields as needed.
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

```
> -1 votes

---
Tags: forms, 10
---


# Question
Title: How can I get the record of the last insert?
Is there a method to be called that will get the ID of the record just inserted?

In my module the first thing done is the insert of some data into a table.

After that I have other things to do in the same submit method of my module that needs the ID of the record that was created, so I can place it into tables that are related.

I've tried

\`$reminder\_query-\>execute();

$reminder\_id = $reminder\_query-\>id();\`

But keep getting an error.

> Error: Call to undefined method Drupal\mysql\Driver\Database\mysql\Insert::id() in Drupal\rmdrs\Form\ReminderForm-\>submitForm()

# Answer
> 0 votes
```
$db = \Drupal::database();

$reminder_query = $db->insert('rmdrs_reminders');
$reminder_query->fields ([
  .......
]);

$reminder_query->values([
  .......
]);
$reminder_query->execute();
$reminder_id = $db->lastInsertId(); // Must refer to the connection to get ID immediately after it is inserted

```

# Answer
> 0 votes
```
// Assuming $reminder_query is a database query object.
$reminder_query = \Drupal::database()->select('your_table_name', 't')
  ->fields('t')
  ->condition('your_condition_field', $your_condition_value);

// Add the range to limit the result set to one row.
$reminder_query->range(0, 1);

// Execute the query and fetch the result.
$result = $reminder_query->execute()->fetch();

// Check if a result was found.
if ($result) {
  // Access the 'id' field from the result.
  $reminder_id = $result->id;
  // Use $reminder_id as needed.
} else {
  // Handle the case where no result was found.
}

```

---
Tags: database, 10
---


title: Get the value of a custom entity field

text:
# Question
Title: Get the value of a custom entity field
How can I get the value of a custom field added to user profiles?

I read and tested everything I found on Google, including the following code.

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$custom_field_value = $user->field_custom_field->value;
// $custom_field_value = $user->get('field_custom_field')->value;

```

It does not work, though.

How can I get the value of a custom field in user profiles?

# Answer
> 0 votes
If you've added a new field through `admin/config/people/accounts/fields` and wish to retrieve its value, try the below code:

```
use Drupal\Core\Session\AccountInterface;

// Get the current user.
$current_user = \Drupal::currentUser();

// Load the user entity.
$user = \Drupal::entityTypeManager()->getStorage('user')->load($current_user->id());

// Check if the user entity exists and has the specified field.
if ($user && $user->hasField('field_custom_field')) {
  // Access the value of the 'field_custom_field' field.
  $custom_field_value = $user->get('field_custom_field')->value;

  // Now $custom_field_value contains the value of the field.
  // You can use it as needed.

}
else {
  // The user entity or the specified field doesn't exist.
}

```

---
Tags: entities, 10
---


# Question
Title: How to dispatch a ResponseEvent so that a cookie is added after login?
I want to add a session cookie when a user logs in.

The previous implementation I had, was setting the cookie in `hook_user_login` with this snippet:

```
$response = new Response();
$response->headers->setCookie($plain_cookie);
$response->send();

```

But this was causing randomly the following exception:

> RuntimeException: Failed to start the session because headers have already been sent

After some research, I found out that a way to handle it is via an EventSubscriber. https://www.drupal.org/docs/develop/creating-modules/subscribe-to-and-dispatch-events

However, I have not managed to dispatch a ResponseEvent in order to add the cookie to the response header, aka. the cookie is not being added after login. I have tried event low priorities in order for the event to be exeuted at the end, but again it does not work.

```
function custom_user_login($account) {
  $response = new Response();
  $event = new MyResponseEvent($response);

  $event_dispatcher = \Drupal::service('event_dispatcher');
  $event_dispatcher->dispatch($event, MyResponseEvent::EVENT_NAME);
}

```

And in my EventSubscriber:

```
public function onUserLogin(MyResponseEvent $event) {
  $response = $event->getResponse();
  $response->headers->setCookie($plain_cookie);
  $event->setResponse($response);
}

```

How could I do it?

# Answer
> 0 votes
Finally, since I could not find a way to create an EventSubscriber for the login event, I returned to my initial implementation and tried to fix the problem with the `$response->send()` command.

It seems that if we just want to modify the response headers (e.g. add some cookies) in the context of a hook where a response is already in place, the proper function to use, instead of `$response->send()` is:

```
 $response->sendHeaders();

```

This works fine, setting the cookies properly to the response and does not trigger the fatal error:

> Headers already sent.

---
Tags: 9, cookies, event-subscribers
---


# Question
Title: How to customize webform item formats, for the preview page?
I'm trying to disable all links targeting entities (taxonomy terms for instance) when previewing a webform, just before submitting it.

When building webforms, I know it's possible to customize how items get displayed on the view page (when viewing a webform submission). This can be achieved by configuring the "Advanced \> Submission display" section of an item, like so:

But I can't find how to configure the same thing for the "preview" page that recaps all filled-in fields, just before submitting a webform. Is that configurable? Or do I have to override webforms' templates?

Cheers :)

# Answer
Turns out I crossed my wires with Drupal's configuration. It seems the preview page does apply the configuration we set for submissions' display in "Advanced \> Submission display".

I guess we could argue configuration could be different for the preview page and the view page, but it suits my needs in my case, so... all good :)
> 0 votes

---
Tags: webforms
---


title: Twig debugging comments stuck on

text:
# Question
Title: Twig debugging comments stuck on
I'm working on a Drupal 10 upgrade and have run into a strange problem ... the contextual edit buttons on my site will not hide. They should be hidden until you mouse over a region/block/whatever, but mine are currently all on all the time.

I THINK this might be due to the fact that, for some reason, the Twig debugging comments around them seems to be stuck on (for lack of a better term).

```
<div data-contextual-id="block:block=nla_owners_theme_page_title:langcode=en" data-contextual-token="BkKyejE0rLQX-QEe31ftM_FGznoaAMuM_XXvgr1tlrE" data-drupal-ajax-container="" data-once="contextual-render" class="contextual">
  <button class="trigger focusable" type="button" aria-pressed="false">Open  configuration options</button>
  <!-- THEME DEBUG -->
  <!-- THEME HOOK: 'links__contextual' -->
  <!-- FILE NAME SUGGESTIONS:
     * links--contextual.html.twig
     x links.html.twig
  -->
  <!-- BEGIN OUTPUT from 'themes/contrib/classy/templates/navigation/links.html.twig' -->
  <ul class="contextual-links" hidden="">
    <li class="block-configure"><a href="/admin/structure/block/manage/nla_owners_theme_page_title?destination=/node/763%3Fcheck_logged_in%3D1">Configure block</a></li>
    <li class="block-remove"><a href="/admin/structure/block/manage/nla_owners_theme_page_title/delete?destination=/node/763%3Fcheck_logged_in%3D1">Remove block</a></li>
  </ul>
  <!-- END OUTPUT from 'themes/contrib/classy/templates/navigation/links.html.twig' -->
</div>

```

Also, if I open that links.html.twig template and just completely empty it, nothing changes.

I know to normally disable and enable the twig debugging in services.yml and that works for the rest of the page code in terms of showing/hiding the debug info, but no matter what I do, this one template will not change.

Here is my services.yml file...

```
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 100
    gc_maxlifetime: 200000
    cookie_lifetime: 0
  twig.config:
    debug: false
    auto_reload: null
  cache: true:
  renderer.config:
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []
  http.response.debug_cacheability_headers: false
  factory.keyvalue:
    {}
  factory.keyvalue.expirable:
    {}
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp
  cors.config:
    enabled: false
    allowedHeaders: []
    allowedMethods: []
    allowedOrigins: ['*']
    exposedHeaders: false
    maxAge: false
    supportsCredentials: false

```

How can I fix this? I'm almost at a loss for how to even ask this question. Thanks!

# Answer
> 0 votes
Disable Twig debugging in the admin UI.

# Answer
> 0 votes
So, it turns out this was something with Chrome. I still can't explain it ... I set debug on and off multiple times, rebooted the server and computer, etc. and it still happens on my Chrome. But I tried it in a different browser and in Chrome incognito mode and the problem wasn't there. I even tried a hard reload in Chrome.

So, thanks for everyone's input, but at this point I'm moving on and writing this off as some glitch in Chrome. Hopefully, it goes away soon.

---
Tags: 10
---


# Question
Title: Why the form does not save data from the entity reference field?
I have a custom entity (with the name **Entity Quote**), from the add form of this entity I make a multistep form.

In the custom entity **Entity Quote**, I added another custom entity (with the name **Quote Design**) as a reference field(with the name **Design**) to add the form of the second custom entity **Quote Design** to the second form step of the first custom entity **Entity Quote**. And I implemented adding the form of the second custom entity using the module Inline Entity Form:
https://www.drupal.org/project/inline\_entity\_form

Where for the reference field I chose in the Manage Form Display the widget: **Inline entity form - Complex**

But the problem is that only the fields on the first step of the form are saved where the fields of the first custom entity (**Entity Quote**), on the second step where the two fields of the second custom entity (**Quote Design**) the data is not saved. The data is not in the tables and, accordingly, is not in the UI either.

The `save()` method is executed after pressing the **Save** button, which appears on the second step of the form.

Implementation of multistep form (**Entity Quote** add form) in sandbox:
https://phpsandbox.io/n/divine-grass-1doo-ylab7

# Answer
> 0 votes
As you've discovered Inline Entity From saves all the referenced entities on the final save, so you'd need to add fairly complex handling to carry its form state to page two.

If I was doing this, I would consider using a pure JS solution for your two pages, where you show and hide fields as desired. The IEF processing is pretty fancy and I wouldn't want to mess with the setup it has.

---
Tags: entities, forms, 9
---


# Question
Title: How to make #description appear on a field widget?
I have a custom field widget that extends WidgetBase. My formElement method looks like this:

```
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => $items[$delta]->value ?? NULL,
      '#size' => $this->getSetting('size'),
      '#placeholder' => $this->getSetting('placeholder'),
      '#maxlength' => $this->getFieldSetting('max_length'),
      '#attributes' => ['class' => ['js-text-full', 'text-full']],
      '#description' => $this->t('test description'),
      '#description_display' => 'after',
    ];

    return $element;
  }

```

The description does not display. Adding the xdebug output for the widget when the node form loads:

```
Array
(
    [#title] => field test
    [#title_display] => before
    [#description] =>
    [#field_parents] => Array
        (
        )

    [#required] =>
    [#delta] => 0
    [#weight] => 0
    [#type] => textfield
    [#default_value] =>
    [#size] => 60
    [#placeholder] =>
    [#maxlength] => 255
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => js-text-full
                    [1] => text-full
                )

        )

)

```

# Answer
> 1 votes
So, oddly enough, it turns out there was either a flaw in the example I had borrowed or there was some subtle difference in the context.

I became suspicious of the very first line of the function:

```
$element['value'] = $element + [

```

and, indeed, when I changed it to:

```
$element['value'] = [

```

the description text appeared. Very odd.

---
Tags: forms
---


# Question
Title: Add custom field template for front page only?
Is it possible to use twig template naming conventions to target a field on the front page only? For example, if I want a different version of the header field on my front page I could use `field--node--field-header-page-front.html.twig`

# Answer
Add this code to your **mytheme.theme** file

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for field templates.
 */
function mytheme_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  // Check if it's the front page.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $field_name = $variables['element']['#field_name'];
    // Add a template suggestion for the all node fields on the front page.
    $suggestions[] = 'field__node__' . $field_name . '__front_page';
  }
}

```

Results in:
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to make CSS changes without the need to flush all caches after each CSS change?
Core version 10.1.6 with an Olivero based sub-theme with a `style.css` file.

My problem is that CSS changes I make in `style.css` won't take effect until I flush all caches and this causes me to lose much time.

How to prevent this situation so to make CSS changes without having to flash all caches each time?

# Answer
> 0 votes
Once you have CSS-aggregation disabled there is a direct connection between your browser and the CSS files. You have to configure the browser not to cache the files or the webserver to add headers to tell the browser not to cache. This is common to CSS development in general and not specific to Drupal.

However, there is one thing Drupal-specific. Drupal adds a cache buster query string to CSS files that changes when clearing the cache. The main use case is for deploying CSS files. This system was not implemented for developers to clear the cache every time they change a CSS file.

---
Tags: theming, 10
---


# Question
Title: Why can't I log in when there is no flood table?
In the database there isn't any *flood* table, but I get this error message.

> There have been more than 5 failed login attempts for this account. It is temporarily blocked.

What could not allow me to log in?

# Answer
Drupal 8 still exited table flood. You can see here. Table **flood** created when use login failed. You can use the way in drupal 7. Simple

```
drush php-eval 'db_query("DELETE FROM `flood`");'

```

Full document.
> 13 votes

# Answer
You can use Flood Control Module.

> Flood Control provides an interface for hidden flood control variables (e.g. login attempt limiters) and makes it possible for site administrators to remove IP addresses and user ID's from the flood table.
> 0 votes

# Answer
If you don't have a flood table, then you are not using Drupal's default flood control mechanism.

So the first step is to identify what mechanism you are on using. On Drupal SaaS like PlatformSH and Pantheon, it is common to use Redis. Redis can be configured to handle flood control instead of Drupal.

In such a case, you need to clear the Redis keystore. One way to do this is to use the redis-cli to connect to Redis and then delete all the keys with `flushall`. This assumes you are using Redis in an ephemeral configuration and do not need to keep the keys.
> 0 votes

---
Tags: 8
---


# Question
Title: Unable to resolve "User ID field needs to be updated" error on status page
I'm on Drupal 10.1.6, and the above-mentioned error is appearing on my status page under "Mismatched entity and/or field definitions." I had similar errors for fields on different entities (File, Content, and Paragraph) that I was able to resolve with one of the following two methods:

1. Running `drush entity-updates`.
2. Navigating to the settings page for the specific fields that needed updating and re-saving.

Method 1 does not work for the User entity, and method 2 is not available, as there is no field settings page available for the User ID field in the Drupal UI. Is there a method for re-saving the User ID field, either programmatically for via drush? Or has anyone else found a different way to resolve this error?

# Answer
I posted a solution to this on this thread over on Drupal.org, repeating it here just in case anyone has the same issue. This problem is the result of core update 9301 from D9 being skipped (for some reason), so I grabbed the original update, created a custom module, and tweaked the update function so that I could run it from the module. Here is the rewritten function:

```
function _user_update_9301() {
   $connection = \Drupal::database();

   if ($connection->databaseType() === 'mysql') {
      $sql_mode = $connection->query("SELECT @@sql_mode;")->fetchField();
      $connection->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
      $new_keys = [];
   }
   else {
      $new_keys = ['primary key' => ['uid']];
      $connection->schema()->dropPrimaryKey('users');
   }
   $connection->schema()->changeField('users', 'uid', 'uid', ['type' => 'serial', 'not null' => TRUE], $new_keys);
   if (isset($sql_mode)) {
      $connection->query("SET sql_mode = '$sql_mode'");
   }

   // Update the last installed schema to reflect the change of field type.
   $installed_storage_schema = \Drupal::keyValue('entity.storage_schema.sql');
   $field_schema_data = $installed_storage_schema->get('user.field_schema_data.uid');
   $field_schema_data['users']['fields']['uid']['type'] = 'serial';
   $installed_storage_schema->set('user.field_schema_data.uid', $field_schema_data);

   // The new PostgreSQL sequence for the uid field needs to start with the last
   // used user ID + 1 and the sequence must be owned by uid field.
   // @todo https://drupal.org/i/3028706 implement a generic fix.
   if ($connection->driver() == 'pgsql') {
      $maximum_uid = $connection->query('SELECT MAX([uid]) FROM {users}')->fetchField();
      $seq = $connection->makeSequenceName('users', 'uid');
      $connection->query("ALTER SEQUENCE " . $seq . " RESTART WITH " . ($maximum_uid + 1) . " OWNED BY {users}.uid");
   }
}

```

Add this function to the `.module` file of your custom module, and then you can run it via Drush:

`drush php-eval '_user_update_9301();'`

This will update the user ID field, and the error message will no longer appear on the Drupal status page.
> 1 votes

---
Tags: entities, users
---


title: Upgrade fails: "Could not delete core"

text:
# Question
Title: Upgrade fails: "Could not delete core"
The upgrade from 9.5.11 to 10.1.7 fails with the error: *Upgrade of drupal/core failed; Could not delete core* I followed the steps in https://www.drupal.org/docs/upgrading-drupal/upgrading-from-drupal-8-or-later/how-to-upgrade-from-drupal-9-to-drupal-10 The step *composer update --dry-run* gives no errors. What should I do? (btw: a few days ago I tested the proces with a demo-version of the site and everything worked fine; although the upgrade then was to 10.1.6)

```
[u134858p129517@web0137 public_html]$ ls -la
totaal 30480
dr-xr-xr-x 11 u134858p129517 u134858p129517     4096 27 apr  2022 .
drwx--x--x  7 u134858p129517 u134858p129517     4096 19 feb  2022 ..
-rw-r--r--  1 u134858p129517 u134858p129517      312 12 dec 10:06 autoload.php
-rw-r--r--  1 u134858p129517 u134858p129517     4085 12 dec 10:17 composer.json
-rw-r--r--  1 u134858p129517 u134858p129517   219854 12 dec 10:26 composer.lock
drwxrwxrwx  2 u134858p129517 u134858p129517     4096 12 dec 10:27 core
-rw-r--r--  1 u134858p129517 u134858p129517     1025 20 sep 13:42 .csslintrc

```

. . . .

```
[u134858p129517@web0137 public_html]$ ls -la core
totaal 8
drwxrwxrwx  2 u134858p129517 u134858p129517 4096 12 dec 10:27 .
dr-xr-xr-x 11 u134858p129517 u134858p129517 4096 27 apr  2022 ..
[u134858p129517@web0137 public_html]$

```

# Answer
This happens because the `core` directory or its parent directory is unwritable by the shell user. Make the directory and its parent directory writable by the shell user to proceed.
> 2 votes

---
Tags: composer, upgrading, 10
---


title: Create a custom element in Webform?

text:
# Question
Title: Create a custom element in Webform?
I am trying to create a custom Webform element that can be added to any webform. It is a select list, but I am providing the options from a remote API call (they cannot be static or hardcoded).

I can get the element to appear in the admin UI with:

```
use Drupal\webform\Plugin\WebformElement\Select;

/**
 * Provides a 'tour type' element.
 *
 * @WebformElement(
 *   id = "tour_type",
 *   label = @Translation("Tour Type"),
 *   description = @Translation("Provides a form element to list tour types from Funnel."),
 *   category = @Translation("Options elements"),
 * )
 */
class TourType extends Select {

}

```

I can add it to a form, and give it options like a regular Select in Webform, but nothing renders on the form.

I was trying to follow this here, but don't quite understand what needs to be done: Why do my custom elements not get rendered?

Do I need a WebformElement plugin, or a new Element class? I don't see how the two are correlated.

# Answer
You need to create a 'Form Element' to process, validate, and render an input and corresponding 'WebformElement' to integrate the input with the Webform module.

You can use the Webform Example Element module as a starting point.
> 5 votes

# Answer
For the record, if you just want to display static or computed data, here's the most basic webform element:

```
<?php
namespace Drupal\your_module\Plugin\WebformElement;

use Drupal\webform\Plugin\WebformElement\WebformMarkup;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Provides a static webform element.
 *
 * @WebformElement(
 *   id = "webform_your_module",
 *   label = @Translation("Human element name"),
 *   description = @Translation("Element description"),
 *   category = @Translation("Choose an existing category or use a new one"),
 *   states_wrapper = TRUE,
 * )
 */
class YourModuleWebformElement extends WebformMarkup {

  /**
   * Optional: only needed if you want to set a human title in the UI
   * {@inheritdoc}
   */
  protected function defineDefaultProperties() {
    return parent::defineDefaultProperties() + [
        'title' => '',
      ];
  }

  public function isInput(array $element) {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function isContainer(array $element) {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
    $element['#title'] = '';
    $element[] = [
      '#markup' => 'My text',
    ];
    parent::prepare($element, $webform_submission);
  }

}

```

As said above, you need matching element

```
<?php

namespace Drupal\your_module\Element;

use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides an fake element for 'YourModuleWebformElement'.
 *
 * @FormElement("webform_recapitulatif_rac")
 *
 * @see \Drupal\Core\Render\Element\FormElement
 * @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21FormElement.php/class/FormElement
 * @see \Drupal\Core\Render\Element\RenderElement
 * @see https://api.drupal.org/api/drupal/namespace/Drupal%21Core%21Render%21Element
 * @see \Drupal\your_module\Element\YourModuleWebformElement
 */
class YourModuleWebformElement extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      '#input' => FALSE
    ];
  }

}

```
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Default values for route parameters in REST resources
The title says it all: is it possible to set a deafult value for a parameter configured in the `uri_paths` of a RestResource? I had a look at the code of `RestResource` and I have a feeling that it is not supported, since `uri_paths` is simply a map; but still, I thought it was worth asking the question :)

# Answer
Yes, the `ResourceBase` generates a `RoutingCollection` in `ResourceBase::routes()`, which you can then loop through and play around with (see https://api.drupal.org/api/drupal/core%21modules%21rest%21src%21Plugin%21ResourceInterface.php/function/ResourceInterface%3A%3Aroutes/8.2.x).

Let say your `uri_paths` looks like this:

```
uri_paths = {
  "canonical" = "/api/fetch/{some_id}"
}

```

Simply override the method in your own Resource, fetch the `RoutingCollection` from the parent - e.g. `ResourceBase` \- and give your parameters a default.

Like so:

```
  public function routes(): RouteCollection {
    $collection = parent::routes();

    // Add a default of NULL for the 'some_id' optional parameter.
    foreach ($collection->all() as $route) {
      $route->addDefaults(['some_id' => NULL]);
    }

    return $collection;
  }

```

The parameter should then get that default value, when it's not provided in the call.

So if your `get()` looks like this:

```
public function get($some_id = NULL): ResourceResponse { .. }

```

The GET-call to `/api/fetch/2` would set `$some_id` to 2, while a GET-call to `/api/fetch` would set `$some_id` to `NULL`.
> 2 votes

# Answer
If you only need to add something to the route, it might be better to override the `getBaseRoute` function of `ResourceBase`, because then you don't have to loop through every route if you only want to add an option to one of them.

```
  /**
   * {@inheritdoc}
   */
  protected function getBaseRoute($canonical_path, $method): Route {
    $route = parent::getBaseRoute($canonical_path, $method);
    if ($method === 'GET') {
      $route->addDefaults(['some_id' => NULL]);
    }
    return $route;
  }

```
> 0 votes

---
Tags: 8
---


# Question
Title: How to use the Tableselect element for an order-able list of items?
It's been a minute since I have used tableselect. I want to present a user with a list of sortable options that have checkboxes to indicate they are on or off. See this screenshot:

While the table does allow to drag options around, when the widget form is submitted the form values have already floated the selected options to the top with the unselected options to the bottom.

What I want to do is preserve the entire list, so I can set the correct order of the form the next time it is displayed in a form. How do I do this?

# Answer
> 1 votes
I wound up following some examples set in this module to implement it in my code:

https://www.drupal.org/project/options\_table

It seems like reading around that people do not advise using tableselect element to do this.

The result:

Users can store field level instance data, retaining order and other settings.

---
Tags: forms, 9
---


# Question
Title: How do I alter the behavior of the form fields contained within the paragraph field?
Using the Paragraphs module in Drupal 8, I am attempting to alter the behavior of the form fields contained within the paragraph field. This is so I can add behavior like AJAX callbacks, hide show other fields using states etc.

I can access the paragraph parent field using this function:

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

```

But how do I access the fields inside the paragraph?

I have tried `hook_field_widget_form_alter` but to no avail.

How do I do this?

Note: I am still quite new to Drupal development.

# Answer
> 31 votes
Since paragraphs^1.3 you can use hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() (I linked the 8.2 version because there is a good comment about using the hook).

You can see the following example in `modules/contrib/paragraphs/tests/modules/paragraphs_test/paragraphs_test.module`

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function paragraphs_test_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'altered_paragraph') {
    $element['subform']['field_text']['widget'][0]['#title'] = 'Altered title';
  }
}

```

# Answer
> 13 votes
If you are using Paragraphs Browser Field Widgets, then the `WIDGET_TYPE` ids for hook `hook_field_widget_WIDGET_TYPE_form_alter()` are different:

| Field Widget Label | Field Widget ID | Provider |
| --- | --- | --- |
| Paragraphs Classic | `entity_reference_paragraphs` | Paragraphs |
| Paragraphs EXPERIMENTAL | `paragraphs` | Paragraphs |
| Paragraphs Browser Classic | `entity_reference_paragraphs_browser` | Paragraphs Browser |
| Paragraphs Browser EXPERIMENTAL | `paragraphs_browser` | Paragraphs Browser |

# Answer
> 3 votes
**Solved!** It works for me. hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() Soution 1 is working for me.

Dependee Field: "field\_align"

Dependent Field: "field\_tab\_sticky" & "field\_tab\_content"

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_paragraphs_form_alter(&$element, &$form_state, $context) {
  if (!empty($element['subform']['field_dependee'])) {
    $parents_array = $element['subform']['#parents'];
    $parents = array_shift($parents_array) . '[' . implode('][', $parents_array) . ']';
    if (!empty($element['subform']['field_dependent'])) {
      $element['subform']['field_dependent']['#states'] = [
        'visible' => [
          ':input[name="' . $parents . '[field_dependee]"]' => [
            'value' => (string) 'some value',
          ],
        ],
      ];
    }
  }
}

```

**Solution 1**:

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function HOOK_field_widget_paragraphs_form_alter(&$element, &$form_state, $context) {
  if (!empty($element['subform']['field_align'])) {
    $parents_array = $element['subform']['#parents'];
    $parents = array_shift($parents_array) . '[' . implode('][', $parents_array) . ']';
    if (!empty($element['subform']['field_tab_sticky'])) {
      $element['subform']['field_tab_sticky']['#states'] = [
        'visible' => [
          ':input[name="' . $parents . '[field_align]"]' => [
            'value' => (string) 'sticky',
          ],
        ],
      ];
    }
    if (!empty($element['subform']['field_tab_content'])) {
      $key = ':input[name="' . $parents . '[field_align]"]';
      $element['subform']['field_tab_content']['#states'] = [
        'visible' => [
          [$key => ['value' => (string) 'top']],
          'or',
          [$key => ['value' => (string) 'left']],
          'or',
          [$key => ['value' => (string) 'accordion']],
        ],
      ];
    }
  }
}

```

**Solution 2**: Refer

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function HOOK_field_widget_paragraphs_form_alter(&$element, &$form_state, $context ) {
  if($context['items']){

    $field_definition = $context['items']->getFieldDefinition();
    $paragraph_entity_reference_field_name = $field_definition->getName();

    if ($paragraph_entity_reference_field_name == 'field_content' && $element['#paragraph_type'] == 'tabs') {

      $key = (isset($element['#type']) && $element['#type'] == 'container') ? $element['#field_parents'] : '';

      $widget_state = \Drupal\Core\Field\WidgetBase::getWidgetState($key, $paragraph_entity_reference_field_name, $form_state);

      $paragraph_instance = $widget_state['paragraphs'][$element['#delta']]['entity'];
      $paragraph_type = $paragraph_instance->bundle();

      if ($paragraph_type == 'tabs') {
        $dependee_field_name = 'field_align';
        $selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);

        // Dependent fields.
        $element['subform']['field_tab_sticky']['#states'] = [
          'visible' => [
            $selector => ['value' => 'sticky'],
        ],
        ];

        // Dependent fields.
        $element['subform']['field_tab_content']['#states'] = [
          'visible' => [
            [$selector => ['value' => 'top']],
            'or',
            [$selector => ['value' => 'left']],
            'or',
            [$selector => ['value' => 'accordion']]
          ],
        ];
      }
    }
  }
}

```

Also, I agree with @baikho for hook references

# Answer
> 1 votes
Using `hook_form_alter` you could alter anything in the form, even stuff coming from widgets. It can easily get a bit messy and it tend to break easily when you mess around with widgets.

If you want to alter widgets what you can do it make your own widget. Widgets are plugins (PHP class) so you can make your own subclass the one you have and alter either by completely overwriting functions or by extending functions.

Widgets use annotation system, so you need to define name, id etc as comments above the class. Easiest way is simply to copy the original widget and alter give it a new name and id, rest should be like it needs to be.

Remember to clear cache to make Drupal find the new plugin.

# Answer
> 1 votes
If you are using Paragraphs Browser as field widget, things have one more twist for you. The hook that fits is named `hook_field_widget_paragraphs_browser_form_alter()` Took my quite some time to figure out...

# Answer
> 1 votes
In my case ( Drupal 8/9 - multi paragraphs entity reference field) hook mymodule\_field\_widget\_entity\_reference\_paragraphs\_form\_alter doesn't work, I used mymodule\_field\_widget\_paragraphs\_form\_alter like this :

```
<?php
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
*/
function mymodule_field_widget_paragraphs_form_alter(&$element, &$form_state, $context) {
 if ( $element['#paragraph_type'] == 'content_selection') {
   //my specifid need
   $element["subform"]["field_contents_related"]["widget"][0]["target_type"]["#options"]["taxonomy_term"] = t('Another text');
 }
}

```

Tips : to find quickly which field widget form alter is available in your form :

In core core/lib/Drupal/Core/Field/WidgetBase.php Just before :

```
\Drupal::moduleHandler()->alter(['field_widget_form', 'field_widget_' . $this->getPluginId() . '_form'], $element, $form_state, $context);

```

(in my case line 353 in protected function formSingleElement )

```
\Drupal::messenger()->addMessage('field_widget_' . $this->getPluginId() . '_form');

```

You will see all the form field widget alter in my case :

field\_widget\_datetime\_timestamp\_form field\_widget\_entity\_browser\_entity\_reference\_form field\_widget\_multiple\_options\_select\_form field\_widget\_comment\_default\_form field\_widget\_dynamic\_entity\_reference\_default\_form field\_widget\_string\_textfield\_form field\_widget\_paragraphs\_form field\_widget\_boolean\_checkbox\_form field\_widget\_options\_buttons\_form field\_widget\_text\_textarea\_form field\_widget\_metatag\_firehose\_form field\_widget\_entity\_reference\_autocomplete\_form field\_widget\_language\_select\_form field\_widget\_path\_form field\_widget\_datetime\_timestamp\_no\_default\_form field\_widget\_string\_textarea\_form

# Answer
> 1 votes
For Drupal 9.3 the `hook_field_widget_WIDGET_TYPE_form_alter()` is deprecated https://api.drupal.org/api/drupal/core%21modules%21field%21field.api.php/function/hook\_field\_widget\_WIDGET\_TYPE\_form\_alter/9.3.x

We should use `hook_field_widget_single_element_WIDGET_TYPE_form_alter()`

# Answer
> 1 votes
We shouldn't use `hook_field_widget_WIDGET_TYPE_form_alter` because this hook has been deprecated in drupal:9.2.0 and will be removed in 10.0.0.

Instead you should use hook\_field\_widget\_single\_element\_WIDGET\_TYPE\_form\_alter.

# Answer
> 1 votes
In Drupal 10 the old method of altering the form (that most other answers on this page mention) has been removed.

The other answers on this page mention `hook_field_widget_WIDGET_TYPE_form_alter()` but that's tricky to figure out the machine name of your widget. And if you want to experiment with another widget, your form alters will disappear.

So instead try `hook_field_widget_single_element_form_alter()`. Here's the simplest example:

```
/**
 * Implements hook_field_widget_single_element_form_alter().
 */
function MY_MODULE_field_widget_single_element_form_alter(&$element, FormStateInterface $form_state, $context) {
  if (isset($element['#paragraph_type']) && $element['#paragraph_type'] === 'my_paragraph_bundle') {
    $element['subform']['field_my_thing']['widget']['0']['#title'] = t('My new title');
  }

}

```

But you possibly want to alter forms for dozens of paragraphs and you don't want all that code in a single function. And wouldn't it also be nice to have the Paragraph object (which is really hard to get in D10). So try this technique of creating a pseudo hook (Search/replace "MY\_MODULE" with the name of your module. Then create as many implementations of the second function as you need them):

```

/**
 * Implements hook_field_widget_single_element_form_alter().
 *
 * @link [https://drupal.stackexchange.com/a/317870/3813] Description and discussion
 */
function MY_MODULE_field_widget_single_element_form_alter(&$element, FormStateInterface $form_state, $context) {
  if (!isset($element['#paragraph_type'])) {
    return;
  }
  $delta = $context['delta'];
  $paragraphBundle = $element['#paragraph_type'];

  /** @var \Drupal\field\Entity\FieldConfig $fieldDefinition */
  $fieldDefinition = $context['items']->getFieldDefinition();
  $contentFieldName = $fieldDefinition->getName();

  // @see \Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget::formElement()
  $widgetState = \Drupal\Core\Field\WidgetBase::getWidgetState($element['#field_parents'], $contentFieldName, $form_state);

  // If this is an empty paragraph, do nothing.
  if (!isset($widgetState['paragraphs'][$delta])) {
    return;
  }

  // Don't act on Paragraph previews.
  if (!\Drupal\Core\Render\Element::children($element['subform'])) {
    return;
  }

  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $widgetState['paragraphs'][$delta]['entity'];

  $functionName = 'MY_MODULE_paragraph__' . $paragraphBundle . '__form_alter';
  if (function_exists($functionName)) {
    $functionName($element['subform'], $element, $form_state, $context, $delta, $paragraph);
  }
}

/**
 * Implements pseudo hook hook_paragraph__BUNDLE__form_alter().
 */
function MY_MODULE_paragraph__my_bundle__form_alter(array &$subform, array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context, int $delta, \Drupal\paragraphs\Entity\Paragraph $paragraph):void {
  $subform['field_some_thing']['widget']['0']['#title'] = 'My new title';
}

```

# Answer
> 0 votes
There's a patch for this in the Paragraphs issue queue.

It adds new hooks:

```
hook_form_paragraphs_subform_alter()
hook_form_paragraphs_subform_TYPE_alter()
hook_form_paragraphs_subform_WIDGET_alter()
hook_form_paragraphs_subform_WIDGET_TYPE_alter()

```

---
Tags: 8, paragraphs
---


# Question
Title: Filling in default value for datetime field in custom entity
I am trying to set the default value for the date field in a custom Entity. The code does not produce any errors. The date field does just not populate with any value. How can I set the default value?

```
   $fields['date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date'))
      ->setDescription(t('The date of the entity.'))
      ->setDefaultValue('2021-09-09')

      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -6,
      ])
      ->setDisplayOptions('form', [
        'weight' => -6,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

```

# Answer
> 1 votes
To fill default value for the date field, you have two options:

1. create a DrupalDateTime and set it as default value like the following:

```

  use Drupal\Core\Datetime\DrupalDateTime;
  use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

  $default_date = DrupalDateTime::createFromTimestamp(strtotime("2021-09-09"));
  $default_date = $default_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
 // set default value.
  ->setDefaultValue($default_date)

```
2. or this way

```

  ->setDefaultValue([
    'default_date_type' => 'custom',
    'default_date'      => '2021-09-09',
  ])

```

*Note :* if you want the default value to be dynamic take a look at this answer it's more complete Default value for datetime field definition in content entity?

# Answer
> 0 votes
This can be achieved by editing the form class if we want to have some dynamic defaults for the DateTime:

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

final class FooForm extends ContentEntityForm {

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

    // Set the date seven days from now.
    $form['foo_date']['widget'][0]['value']['#default_value'] = DrupalDateTime::createFromTimestamp(time() + 3600 * 24 * 7);

    return $form;
  }

// ...
}

```

---
Tags: datetime
---


title: Commerce Number Pattern

text:
# Question
Title: Commerce Number Pattern
My system environment:

1. OS - Windows 10 64-bit
2. Local Server Stack - WampServer
3. Drupal 8.9.8
4. Theme Droopler
5. Module Commerce - installed using Composer and enabled by Drush

The Status Report (screen capture as below):

The setting for Commerce Number Pattern:

Despite clearing the cache after updating the default number setting, Drupal still reports an error as shown above.

Any assistance is greatly valued.

Thank you.

# Answer
> 0 votes
Please install Devel module. Link to Devel module

2. enable devel module.
3. click on reinstall module.
4. check module "Commerce Number Pattern".
5. click on reinstall.

Hope this helps you.

---
Tags: commerce
---


# Question
Title: Is it possible to favorite/bookmark Search API results using Flags or similar?
We are using the Flag module to create favorites of Nodes and this works great for allowing users to bookmark specific Nodes.

The client also wants to bookmark search results from the Search API Views page.

Ideally, this would be with a Flag also but I don't see how this would be possible as the search result is simply a URL and not en entity.

How could we allow users to bookmark a URL/search-result? It doesn't have to be a Flag, if there is another way.

EDIT:

Found this module that works perfectly for our needs:

https://www.drupal.org/project/bookmarks

# Answer
Found a module that works perfectly for our needs:

https://www.drupal.org/project/bookmarks
> 1 votes

---
Tags: flags
---


# Question
Title: Change View webform link edit to edit/all
I am currently using drupal 10 and I created a page using View (acquiring webform with pages). In View I add link edit webform.

When I click edit, it can open the submission as expected. However since the webform using pages, when I edit it opens page by page. There is a tab to see all pages, which is easier.

The different is edit and edit/all

Can I change the default to edit/all to open edit all pages.

Regards, waluyo

# Answer
Finally I can find the solution.
a. Hide edit link and output as URL

b. Then I add custom text, and simply add the replacement token with /all. This link replaces the original edit link. I can use a nice edit icon as well.
> 0 votes

---
Tags: views, webforms
---