Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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.

 

 

 

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon