Skip to content

Instantly share code, notes, and snippets.

@lcube45
Created June 1, 2020 14:48
Show Gist options
  • Save lcube45/4b069ea7ef514523da97ba0c17952ca3 to your computer and use it in GitHub Desktop.
Save lcube45/4b069ea7ef514523da97ba0c17952ca3 to your computer and use it in GitHub Desktop.
Drupal 8 - ajax callback
<?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