Skip to content

Instantly share code, notes, and snippets.

@jez500
Created January 8, 2018 00:53
Show Gist options
  • Save jez500/3402ef2723e51fa78ac759918e0906bb to your computer and use it in GitHub Desktop.
Save jez500/3402ef2723e51fa78ac759918e0906bb to your computer and use it in GitHub Desktop.
Drupal 8 Ajax form example when select box changed
<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class TestAjaxFormSelect.
*/
class TestAjaxFormSelect extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'test_ajax_form_select';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Get the form values and raw input (unvalidated values).
$values = $form_state->getValues();
// Define a wrapper id to populate new content into.
$ajax_wrapper = 'my-ajax-wrapper';
// Sector.
$form['my_select'] = [
'#type' => 'select',
'#empty_value' => '',
'#empty_option' => '- Select a value -',
'#default_value' => (isset($values['my_select']) ? $values['my_select'] : ''),
'#options' => [
1 => 'One',
2 => 'Two',
3 => 'Three'
],
'#ajax' => [
'callback' => [$this, 'mySelectChange'],
'event' => 'change',
'wrapper' => $ajax_wrapper,
],
];
// Build a wrapper for the ajax response.
$form['my_ajax_container'] = [
'#type' => 'container',
'#attributes' => [
'id' => $ajax_wrapper,
]
];
// ONLY LOADED IN AJAX RESPONSE OR IF FORM STATE VALUES POPULATED.
if (!empty($values) && !empty($values['my_select'])) {
$form['my_ajax_container']['my_response'] = [
'#markup' => 'The current select value is ' . $values['my_select'],
];
}
return $form;
}
/**
* The callback function for when the `my_select` element is changed.
*
* What this returns will be replace the wrapper provided.
*/
public function mySelectChange(array $form, FormStateInterface $form_state) {
// Return the element that will replace the wrapper (we return itself).
return $form['my_ajax_container'];
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Required by FormInterface.
}
}
@abelperezlindo
Copy link

Thanks!! I find it very useful.

@Immortal1900
Copy link

Hi, I used the same code in my form but in the callback $form['my_ajax_container'] is null and response is causing an error, then i checked out for other fields and all are null, does anyone have any idea?

@abelperezlindo
Copy link

Maybe if you share a portion of the code you are using we can help you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment