Created
June 1, 2020 14:48
-
-
Save lcube45/4b069ea7ef514523da97ba0c17952ca3 to your computer and use it in GitHub Desktop.
Drupal 8 - ajax callback
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 | |
class AjaxForm extends FormBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFormId() { | |
return 'ajax_form'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$form['#tree'] = TRUE; | |
$form_state->setCached(FALSE); | |
$form['container'] = [ | |
'#type' => 'container', | |
'#attributes' => ['id' => 'my-container'], // CHECK THIS ID | |
]; | |
$form['container']['selection'] = [ | |
'#type' => 'select', | |
'#title' => t('Selection'), | |
'#options' => [ | |
'selection1' => 'Selection 1', | |
'selection2' => 'Selection 2', | |
'selection3' => 'Selection 3', | |
], | |
'#empty_value' => '', | |
'#ajax' => [ | |
'callback' => [$this, 'myCallback'], | |
'event' => 'change', | |
'wrapper' => 'my-container', | |
], | |
]; | |
if ($form_state->getUserInput()) { | |
$val = 'changed'; | |
$status = FALSE; | |
} | |
else { | |
$val = 'original'; | |
$status = TRUE; | |
} | |
$form['container']['label'] = [ | |
'#type' => 'textfield', | |
'#title' => 'label', | |
'#attributes' => [ | |
'id' => ['edit-label'], | |
], | |
'#value' => $val, | |
]; | |
$form['container']['title'] = [ | |
'#type' => 'textfield', | |
'#title' => 'title', | |
'#attributes' => [ | |
'id' => ['edit-title'], | |
], | |
'#disabled' => $status, | |
]; | |
// Add a submit button that handles the submission of the form. | |
$form['actions'] = [ | |
'#type' => 'actions', | |
'submit' => [ | |
'#type' => 'submit', | |
'#value' => $this->t('Submit'), | |
], | |
]; | |
return $form; | |
} | |
function myCallback(array &$form, FormStateInterface $form_state) { | |
return $form['container']; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validateForm(array &$form, FormStateInterface $form_state) { | |
parent::validateForm($form, $form_state); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
// Display result. | |
foreach ($form_state->getValues() as $key => $value) { | |
drupal_set_message($key . ': ' . $value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment