Following on from a previous question.

I have a slideshow field, an image field and a video field, but I only want editors to choose one of these.

Using Form API states I have created a form_alter in a custom module which reveals one input field at a time based based on a choice from a select list. This is working fine. Code below.


     * Implements hook_form_alter().
    function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
      $form['field_slideshow_image']['#states'] = [
        'visible' => [
          'select[name="field_selection_display"]' => ['value' => 'slideshow']
      $form['field_image']['#states'] = [
        'visible' => [
          'select[name="field_selection_display"]' => ['value' => 'image']
      $form['field_video_embed']['#states'] = [
        'visible' => [
          'select[name="field_selection_display"]' => ['value' => 'videoembed']

This method makes for a good UI, but it does not prevent more than one field being populated. Therefore I need to extend the module to;

1). Prevent an editor populating more than one field, perhaps by displaying an inline error message. OR 2). Limit the display on the front end, to the field which has a visible state (based on the selection list choice).

My feeling is that number 2 would make for the best UX, but it would be good to try both.

How would I go about this?


1 Answer 1


For option #1 you would have to create a custom validation.

For option #2 which is the better solution you would have to load the fields via AJAX.

  • Thank you for the pointers. Finding lots to read about custom validation, but much less about loading fields via ajax. Any other terms I should searching for? Commented Jun 25, 2018 at 21:06
  • I guess you could search for this
    – No Sssweat
    Commented Jun 25, 2018 at 23:01
  • I may take you up on that ;-) Commented Jun 26, 2018 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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