Tuesday, July 21, 2020


Form API conditional field required and visible in Drupal 8

A few months ago, I was working with a Drupal shop and was surprised that they didn’t know how to make a field conditional and required using the Form API. I have decided to publish my findings here:

I am going to give a code example on how to do it here:

   $form['fruit'] = [
      '#type' => 'select',
      '#title' => 'Fruit Types',
      '#options' => [                                                                                                              
           'citrus' => $this->t('Citrus'),                                                                                      
            'other' => $this->t('Other'),                                                                                     
         ],                                                                                                                   
      '#attributes' => [
        'name' => 'fruit',
      ],
    ];
    $form['citrus_fruits'] = [
      '#type' => 'textfield',                                                                                              
      '#title' => 'Type in your fruit',                                                                                    
      '#size' => '60',
      '#states' => [                                                                                                         
        'required' => [
          ':input[name="fruit"]' => ['value' => 'other'],
        ],                                                                                                                   
        'visible' => [
          ':input[name="fruit"]' => ['value' => 'other'],                                                                    
        ],
      ],
    ];

With this FormAPI code, you can see that it is possible to make a field required and visible based of a choice of another field. you can add other properties too, like disabled and such.