Created
January 8, 2018 00:53
-
-
Save jez500/3402ef2723e51fa78ac759918e0906bb to your computer and use it in GitHub Desktop.
Drupal 8 Ajax form example when select box changed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. | |
} | |
} |
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
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?