0

How do we set required for new & optional for existing fields - when adding basic field to content type?

When using Drupal 8 following this how to article shows the steps to take to add a basic field to content types. https://www.drupal.org/docs/user_guide/en/structure-fields.html

What I want to learn how to accomplish is to make the new field "Required" for all newly created content types however for existing content I want the field to be optional.

In the admin I see the required checkbox however this will make all of them required. Below is an image of what I am viewing: enter image description here

Any & all feedback is greatly appreciated.

1

You can use hook_form_alter or hook_form_FORM_ID_alter to set require for that field.

 
function my_module_form_alter(&$form, $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  if ($entity->isNew()) {
    $form['my_field']['#required'] = TRUE;
  }
}

And, not set the field 'my_field' as required field. Not tested, but it is a way to go.

  • 1
    You’ll want to narrow this down by content type or you will get warnings/errors. – Kevin Aug 7 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.