A form like the following is expected to show additional fields when user selected "Yes" in the "Show more" radio button. When shown, the more section has a "Name" text field, and a "Gender" radios set.
But it never works as expected. The "Gender" label will be there, but the radio buttons are never rendered. I know changing "Gender" into radios would work, but for some reason, I need to use multiple radio buttons. Is there any way I can make this work?
<?php namespace DrupalmymoduleForm; use DrupalCoreFormFormBase; class DonationPrepareForm extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'my_form'; } /** * {@inheritdoc} */ public function buildForm( array $form, FormStateInterface $form_state ) { $form['show_more'] = [ '#type' => 'radios', '#title' => 'Show more', '#options' => [ 'Y' => 'Yes', 'N' => 'No', ], '#ajax' => [ 'callback' => '::ajaxBuildForm', 'wrapper' => 'edit-more-wrapper', 'progress' => [ 'type' => 'throbber', 'message' => $this->t('Loading...'), ], ], ]; $form['more'] = [ '#type' => 'container', '#prefix' => '<div id="edit-more-wrapper">', '#suffix' => '</div>', ]; return $form; } public function ajaxBuildForm(array &$form, FormStateInterface $form_state) { if ($form_state->getValue('show_more') === 'Y') { $form['more']['name'] = [ '#type' => 'textfield', '#title' => 'Name', '#required' => TRUE, ]; $form['more']['gender'] = [ '#type' => 'radios', '#title' => 'Gender', '#options' => [ 'M' => 'Male', 'F' => 'Female', ], '#required' => TRUE, ]; } return $form['more']; } }
Same question extends to other composite form elements (e.g. Checkboxes). Is there any way to make AJAX work for them?