Skip to main content
Category:

in this tuto, I'll show you how to show/hide form element based on AJAX-enabled radiobox click in drupal 8.

Step1: add Ajax triggers to a form element

$form['cms'] = [
  '#type' => 'radios',
  '#title' => $this->t('Select a cms'),
  '#options' => [
    'drupal' => $this->t('Drupal'),
    'wordpress' => $this->t('Wordpress'),
    'joomla' => $this->t('Joomla'),
    'other' => $this->t('Other'),
  ],
  '#ajax' => [
    'callback' => '::radioCallback',
    'wrapper' => 'cms_container',
  ],
];
  • callback: The callback to invoke to handle the server side of the Ajax event. More information on callbacks is below in "Setting up a callback to process Ajax".
  • wrapper: The HTML 'id' attribute of the area where the content returned by the callback should be placed. Note that callbacks have a choice of returning content or JavaScript commands; 'wrapper' is used for content returns.

Add radioCallback():

/**
 * @param $form
 * @param FormStateInterface $form_state
 * @return mixed
 */
public function radioCallback($form, FormStateInterface $form_state)
{
  return $form['cms_container'];
}

Step2: show textfield element when 'other' option is clicked

Wrap textfields in a container. This container will be replaced through ajax.

$form['cms_container'] = [
  '#type' => 'container',
  '#attributes' => [
    'id' => 'cms_container'
  ],
];


if ($form_state->getValue('cms', NULL) === "other") {
  $form['cms_container']['other_cms'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Other CMS'),
  ];
}

This form is rebuilt on all requests, so whether or not the request comes from AJAX.

by default 'Other CMS' is hidden, it will be visible when I checked 'other' option.

 

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook