0

When a field is required, Drupal removes the default "-None-" value. However, also for a required field, "-None-" is very valuable as it requires the user to make a deliberate selection (put the first value on the select list as default doesn't force a sloppy user to make a selection).

I need to:

  • Have "-None-" as default value in the select list of a required field
  • Not accept "-None-" as field value when the form is submitted

How can I achieve this with hook_form_alter()?

2

By default, the label for the first default option is automatically set to "- Select -" for a required field and "- None -" for an optional field. To force the #empty_option to also show "- None -" for a required field, assign it with something like:

"#empty_option" => t('- None -'),

This will keep everything else intact and will do exactly what you want. See class Select.

  • Hello @leymannx. This is indeed the general rule. However, this does not apply to all select fields. In some cases, I don't see the "-Select a value-" as default option for a select list : an entity reference, the country field of the address module. Any idea on how to tackle these (perhaps I should update my question accordingly? Sorry, I'm new to stack exchange...) – Dendreten Oct 4 '18 at 17:53

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.