Score:0

Controlling dropdown field visibility using #states API for dependent dropdown

cn flag

I have the following setup.

dropdown_one

[
    '#type' => 'select',
    '#title' => $this->t('Dropdown one'),
    '#options' => $dropdownOneOptions,
    '#empty_option' => '---',
    '#weight' => 1,
    '#ajax' => [
      'event' => 'change',
      'callback' => [$this, 'getDropdownTwoOptions'],
      'wrapper' => 'dropdown-two',
      'progress' => [
        'type' => 'throbber',
      ],
    ],
    '#name' => 'dropdown_one',
]

dropdown_two

[
    '#type' => 'select',
    '#title' => $this->t('Dropdown two'),
    '#options' => [],
    '#empty_option' => '---',
    '#weight' => 2,
    '#ajax' => [
      'event' => 'change',
      'callback' => [$this, 'getDropdownThreeOptions'],
      'wrapper' => 'dropdown-three',
      'progress' => [
        'type' => 'throbber',
      ],
    ],
    '#name' => 'dropdown_two',
    '#prefix' => sprintf('<div id="%s">', 'dropdown-two'),
    '#suffix' => '</div>',
    '#states' => [
      'invisible' => [
        ':input[name="dropdown_one"]' => ['value' => ''],
      ],
    ],  
]

dropdown_three

[
    '#type' => 'select',
    '#title' => $this->t('Dropdown three'),
    '#options' => [],
    '#empty_option' => '---',
    '#weight' => 3,
    '#name' => 'dropdown_three',
    '#prefix' => sprintf('<div id="%s">', 'dropdown-three'),
    '#suffix' => '</div>',
    '#states' => [
      'invisible' => [
        ':input[name="dropdown_two"]' => ['value' => ''],
      ],
    ],  
]

The select fields options of dropdown two and dropdown three are updated/set via their respective AJAX callback, with HtmlCommand().

$response = new AjaxResponse();
$wrapper_id = $triggeringElement['#ajax']['wrapper']; // 'dropdown-two' or 'dropdown-three'
$response->addCommand(new HtmlCommand("#$wrapper_id select", $html)); // $html = "<option value='foo'>bar</option>...";

I'm trying to figure out why this case is not working:

Given in dropdown one an non-empty option is selected
And dropdown two is displayed
And an non-empty option is selected in dropdown two
And dropdown three is displayed
When I select the empty option in dropdown one
Then dropdown two and dropdown three should not be displayed

Unfortunately when I run this set of action, dropwdown three remains visible and I can't figure out why.

I would really appreciate if someone could help.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.