1

I have a multi-value entity reference field on a content entity that I am displaying using a custom form class that extends ContentEntityForm, which extends EntityForm, which extends FormBase.

I'd like to set the field to be required: when using this form, you must select at least one entity to reference. I don't want to make this an entity level constraint however, as it's not absolutely required in all circumstances.

In a form alter hook (as well as in my custom form class) I've tried setting things like

  $form['field_myfield']['widget']['#required'] = TRUE;
  $form['field_myfield']['widget']['#required'] = TRUE;
  $form['field_myfield']['widget']['0']['#required'] = TRUE;

Some of these show up when I kint the form after saving it, some are set back to FALSE, but none of these prevent the form from saving when there is no value in my field. But regardless of that, I don't see anything in FormBase, EntityForm or ContentEntityForm that will validate a required element anyway.

Do I really need to create my own validation handler? Or is it something else that I'm missing?

3

It is really annoying... I struggled with that several times as well. The important key is places deeper in the array. Take a look on

$form['field_ref_download']['widget'][0]['target_id']['#required']

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.