Make field optional via hook_field_widget_form_alter doesn't work

Created on 25 April 2017, over 7 years ago
Updated 6 September 2024, 4 months ago

When trying to make a field optional via hook_field_widget_form_alter, Drupal still require the field when submiting.

How to reproduce:
1. Make body field required for article;
2. Try to save the article without body and Drupal shows the message: Body field is required., witch is the expected behavior.
3. Create a new module called mymodule;
4. On mymodule.module add the following function:

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $items = $context['items'];
  $element_name = $items->getName();
  if ($element_name == 'body') {
    $element['#required'] = FALSE;
  }
}

5. Enable mymodule
6. Reload the article add/edit page
7. Try to save the article again, and Drupal shows the message: This value should not be null. and this is not the expected behavior. In this case, Drupal should allow saving the article without fill the body field.

The body field is just an example. It happens to all fields that are configured as required on Structure / Content Types / Manage Fields.

💬 Support request
Status

Closed: works as designed

Version

11.0 🔥

Component
Field 

Last updated 1 day ago

Created by

🇧🇷Brazil yseki

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇳🇿New Zealand quietone

    #13 has providing working code for this.

    As this is a support request and the Drupal Core issue queue is not the ideal place for support requests. The 'support request' option is there for filing support issues for contributed modules and themes. There are several support options listed on our support page (Community > Support at the top of Drupal.org) and there is Drupal Slack . You may get better replies in one of those places.

Production build 0.71.5 2024