Blog IT

Drupal's Form API #states property allows to easily show or hide, enable or disable, require or collapse form fields based on values selected or entered in other fields on that form or anywhere else on the page.

<?php

namespace Drupal\ajaxfilters\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;


class DefaultForm extends FormBase
{
  public function getFormId() {
    return 'default_form';
  }


  public function buildForm(array $form, FormStateInterface $form_state)
  {
    // Create a list of radio boxes that will toggle the  textbox
    // below if 'other' is selected.
    $form['colour_select'] = [
      '#type' => 'radios',
      '#title' => $this->t('Pick a colour'),
      '#options' => [
        'blue' => $this->t('Blue'),
        'white' => $this->t('White'),
        'black' => $this->t('Black'),
        'other' => $this->t('Other'),
      ],
      // We cannot give id attribute to radio buttons as it will break their functionality, making them inaccessible.
      /* '#attributes' => [
        // Define a static id so we can easier select it.
        'id' => 'field_colour_select',
      ],*/ 
    ];

    // This textfield will only be shown when the option 'Other'
    // is selected from the radios above.
    $form['custom_colour'] = [
      '#type' => 'textfield',
      '#size' => '60',
      '#placeholder' => 'Enter favourite colour',
      '#attributes' => [
        'id' => 'custom-colour',
      ],
      '#states' => [
        // Show this textfield only if the radio 'other' is selected above.
        'visible' => [
          // Don't mistake :input for the type of field or for a css selector --
          // it's a jQuery selector. 
          // You can always use :input or any other jQuery selector here, no matter 
          // whether your source is a select, radio or checkbox element.
          // in case of radio buttons we can select them by thier name instead of id.
          ':input[name="colour_select"]' => ['value' => 'other'],
        ],
      ],
    ];

    // Create the submit button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Sorry, I\'m colour-blind'),
    ];

    return $form;
  }


  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    parent::validateForm($form, $form_state);
  }


  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    // Display the result.
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }
  }

}

 

conditional form fields programmatically