2

Hi I build Add more for radios when click button load ajax. This ajax only add more options for radios . But not working , how to build used ajax add more options for type radios form ? Thanks

This code example my demo:

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DemoForm extends FormBase{

    public function getFormId()
    {
        return 'DemoForm';
    }
    public function buildForm(array $form, FormStateInterface $form_state,$param = array())
    {
        $form['wrapper_data'] = array(
            '#type' => 'container',
            '#attributes' => array('id' => 'wrapper_data'),
        );  
        $form['wrapper_data']['data_media'] = array(
            '#type' => 'select',
            '#title' => 'List Media',
            '#options' => array('aaa','bbb','cccc'), 

        );
        $form['wrapper_data']['load_more_data'] = array(
            '#type' => 'button',
            '#value' => 'Load More',
            '#ajax' => array(
                'callback' => '::AjaxLoadMore',
                'wrapper' => 'wrapper_data',
            ),
        );

        return $form;
    }

    public function AjaxLoadMore(array &$form,FormStateInterface $formState){

        $form['data_media']['#options'] += array('bbbb'); // Want Add more options for radios

        return $form['wrapper_data'];
    }
}
2

Here is the complete code example:

<?php
/**
 * @file
 * File: src/Form/MyExampleForm.php
 * Contains \Drupal\mymodule\Form\MyExampleForm.
 */
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyExampleForm extends FormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'example_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['wrapper'] = array(
        '#type' => 'container',
        '#attributes' => array('id' => 'data-wrapper'),
        );

    /* // or:
    $form['wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => $this->t('Example title'),
      '#tree' => FALSE,
      '#prefix' => "<div id='data-wrapper'>",
      '#suffix' => '</div>',
    );
    */

    /* // or:
    $form['#prefix'] = '<div id="data-wrapper">';
    $form['#suffix'] = '</div>';
    */

    $form['wrapper']['data_media'] = array(
        '#type' => 'radios',
        //'#title' => 'Title',
        '#options' => array('aaa','bbb','cccc'), 
        );
    $form['wrapper']['more_data'] = array(
        '#type' => 'button',
        '#required' => TRUE,
        '#value' => 'Show more',
        // @see: https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.3.x
        '#ajax' => array(
          // The callback to invoke to handle the server side of the Ajax event.
          'callback' => [$form_state->getBuildInfo()['callback_object'], 'ajaxLoadMore'],
          // or: //'callback' => [$this, 'ajaxLoadMore'],
          // or: //'callback' => '::ajaxLoadMore',
          // @see: http://api.jquery.com/category/manipulation/
          //'method' => 'replace', // May be: 'replaceWith' (default), 'append', 'prepend', 'before', 'after', or 'html'.
          // The HTML 'id' attribute of the area where the content returned by the callback should be placed.
          'wrapper' => 'data-wrapper',
          ),
        );
    $form['wrapper']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Confirm'),
        );

    return $form;
  }

  /**
   * Ajax handler for loading more radio options.
   */
  public function ajaxLoadMore(array &$form, FormStateInterface $form_state){
    // Add more options for radios.
    $trigger = $form_state->getTriggeringElement();
    if ($trigger['#value'] == 'Show more') {
      $form['wrapper']['data_media']['#options'] += array_merge($form['wrapper']['data_media']['#options'], ['bbbb']);
    }
    return $form['wrapper'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $trigger = $form_state->getTriggeringElement();
    if ($trigger['#type'] === 'submit') {
      if (is_null($values['data_media'])) {
        $form_state->setErrorByName('data_media', t('Please select the option!'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your form has been submitted.'));
  }

}
2

Move the code to add more radios to form build:

  if ($form_state->getTriggeringElement()['#value'] == 'Load More') {
    $form['wrapper_data']['data_media']['#options'] += array('bbbb');
  }

You can use getTriggeringElemement() to identify the button by checking a property of the element, if you want this can be the ajax callback itself.

  • Hi I used getTriggeringElemement but not working for radios . Could you show detail about your solution ? Thanks – Henry Tran Aug 23 '16 at 6:59
  • getTriggeringElement() is to check if the button was clicked. The code in my answer is the complete solution. – 4k4 Aug 23 '16 at 7:05
  • I replace $form['wrapper_data']['data_media']['#options'] += array('bbbb') to $form['wrapper_data']['data_media']['#options'] = array_merge($form['wrapper_data']['data_media']['#options'],array('bbbb')) this working . Thank for your answer ! – Henry Tran Aug 23 '16 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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