Skip to content

Instantly share code, notes, and snippets.

@slivorezka
Forked from jez500/TestAjaxFormSelect.php
Created September 21, 2018 07:32
Show Gist options
  • Save slivorezka/90250ffbe33e65d13a9d8dee1fc3a48e to your computer and use it in GitHub Desktop.
Save slivorezka/90250ffbe33e65d13a9d8dee1fc3a48e 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.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment