0

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 Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;

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?

2 Answers 2

1

Move form building to buildForm(). You can't build form elements in an Ajax callback (I've also renamed the callback method to make this clear):

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;

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' => '::ajaxCallback',
        'wrapper' => 'edit-more-wrapper',
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Loading...'),
        ],
      ],
    ];
    $form['more'] = [
      '#type' => 'container',
      '#prefix' => '<div id="edit-more-wrapper">',
      '#suffix' => '</div>',
    ];

    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;
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    return $form['more'];
  }
}
1
  • Thanks a lot. It works! Apr 4, 2022 at 7:38
2

Actually it is significantly easier to use form element #states property to make an element visible , invisible , enabled , disabled , required or ... rather than using ajax

A code like this will do the job:

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;

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',
      ],
    ];


    $form['more']['name'] = [
      '#type' => 'textfield',
      '#title' => 'Name',
      '#states' => array(
        'visible' => array(
          ':input[name="show_more"]' => array('value' => 'Y'),
        ),
        'required' => array(
          ':input[name="show_more"]' => array('value' => 'Y'),
        )
      ),
    ];
    $form['more']['gender'] = [
      '#type' => 'radios',
      '#title' => 'Gender',
      '#options' => [
        'M' => 'Male',
        'F' => 'Female',
      ],
      '#states' => array(
        'visible' => array(
          ':input[name="show_more"]' => array('value' => 'Y'),
        ),
        'required' => array(
          ':input[name="show_more"]' => array('value' => 'Y'),
        )
      ),
    ];

    return $form;
  }

}

2
  • This does not work for my case because I'd want the appeared fields to be required fields. Apr 4, 2022 at 9:12
  • What does this not work exactly? The required state is also input-dependent in the answer?
    – Alex
    Apr 5, 2022 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.