n How to programmatically set a conditional field in Drupal 8 & 9 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

How to programmatically set a conditional field in Drupal 8 & 9

 

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.

 

Example how to use #states in custom form:

 

<?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'),
      ],
      '#attributes' => [
        //define static name and id so we can easier select it
        // 'id' => 'colour_select',
        'name' => '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. You'll always use
          //:input here, no matter whether your source is a select, radio or checkbox element.
          ':input[name="field_select_colour"]' => ['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 result.
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }
  }

}

 

Read this chapter for more Details.

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook