Score:0

How do I dynamically (AJAX) show radios in form API?

au flag

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?

Score:2
cn flag

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

}

au flag
This does not work for my case because I'd want the appeared fields to be required fields.
in flag
What does this not work exactly? The required state is also input-dependent in the answer?
Score:1
cn flag

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'];
  }
}
au flag
Thanks a lot. It works!
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.