Select's #empty_option gets removed on ajax callback

Created on 31 October 2020, almost 4 years ago
Updated 17 July 2023, about 1 year ago

Problem/Motivation

It was discovered in #2577219: Single item configuration export form config_name does not have "- Select -" as it's first option that select element adds #empty_option in Select::processSelect. However, if a select element is updated (re-rendered?) on an ajax callback, the #empty_option gets removed.

Steps to reproduce

Create a form with the following in buildForm

  $form['ajax_parent_select'] = [
      '#title' => $this->t('Parent select with Ajax callback'),
      '#type' => 'select',
      '#options' => ['one' => 'One', 'two' => 'Two'],
      '#default_value' => 'one',
      '#ajax' => [
        'callback' => '::ajaxCallback',
        'wrapper' => 'child-wrapper',
      ],
    ];
    $form['ajax_child_select'] = [
      '#title' => $this->t('Child select'),
      '#type' => 'select',
      '#options' => ['three' => 'Three'],
      '#empty_option' => $this->t('- Select -'),
      '#prefix' => '<div id="child-wrapper">',
      '#suffix' => '</div>',
    ];

Where ajaxCallback looks something like this

  public function ajaxCallback($form, FormStateInterface $form_state) {
    $options = [
      'one' => ['three' => 'Three'],
      'two' => ['four' => 'Four'],
    ];
    $form['ajax_child_select']['#options'] = $options[$form_state->getValue('ajax_parent_select')];
    return $form['ajax_child_select'];
  }

When ajaxCallback fires, it removes #empty_option during re-rendering of ajax_child_select

This has been demonstrated here

Proposed resolution

Add #empty_option in a #pre_render callback

Remaining tasks

Code review and validate the used approach.

User interface changes

None

API changes

None

Data model changes

None

Release notes snippet

None

🐛 Bug report
Status

Needs work

Version

11.0 🔥

Component
Render 

Last updated 1 day ago

Created by

🇮🇳India raman.b Delhi

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024