$npx -y skills add edutrul/drupal-ai --skill drupal-form-ajaxDrupal AJAX form callbacks, #ajax properties, AjaxResponse commands, and dynamic form rebuilding.
| 1 | # Drupal AJAX Forms |
| 2 | |
| 3 | ## AJAX Callback Pattern |
| 4 | |
| 5 | ```php |
| 6 | public function buildForm(array $form, FormStateInterface $form_state): array { |
| 7 | $form['type'] = [ |
| 8 | '#type' => 'select', |
| 9 | '#title' => $this->t('Type'), |
| 10 | '#options' => ['a' => 'Type A', 'b' => 'Type B'], |
| 11 | '#ajax' => [ |
| 12 | 'callback' => '::updateOptions', |
| 13 | 'wrapper' => 'options-wrapper', |
| 14 | 'event' => 'change', |
| 15 | ], |
| 16 | ]; |
| 17 | |
| 18 | $form['options_wrapper'] = [ |
| 19 | '#type' => 'container', |
| 20 | '#attributes' => ['id' => 'options-wrapper'], |
| 21 | ]; |
| 22 | |
| 23 | $type = $form_state->getValue('type', 'a'); |
| 24 | $form['options_wrapper']['value'] = [ |
| 25 | '#type' => 'textfield', |
| 26 | '#title' => $this->t('Value for @type', ['@type' => $type]), |
| 27 | ]; |
| 28 | |
| 29 | return $form; |
| 30 | } |
| 31 | |
| 32 | public function updateOptions(array &$form, FormStateInterface $form_state): array { |
| 33 | return $form['options_wrapper']; |
| 34 | } |
| 35 | ``` |
| 36 | |
| 37 | ## AjaxResponse with Commands |
| 38 | |
| 39 | ```php |
| 40 | use Drupal\Core\Ajax\AjaxResponse; |
| 41 | use Drupal\Core\Ajax\ReplaceCommand; |
| 42 | use Drupal\Core\Ajax\HtmlCommand; |
| 43 | use Drupal\Core\Ajax\InvokeCommand; |
| 44 | use Drupal\Core\Ajax\MessageCommand; |
| 45 | |
| 46 | public function ajaxCallback(array &$form, FormStateInterface $form_state): AjaxResponse { |
| 47 | $response = new AjaxResponse(); |
| 48 | $response->addCommand(new ReplaceCommand('#my-wrapper', $form['my_element'])); |
| 49 | $response->addCommand(new HtmlCommand('#message', $this->t('Updated!'))); |
| 50 | $response->addCommand(new InvokeCommand('#my-input', 'val', ['new value'])); |
| 51 | $response->addCommand(new MessageCommand($this->t('Success!'), NULL, ['type' => 'status'])); |
| 52 | return $response; |
| 53 | } |
| 54 | ``` |
| 55 | |
| 56 | ## #ajax Properties |
| 57 | |
| 58 | ```php |
| 59 | '#ajax' => [ |
| 60 | 'callback' => '::myCallback', // Method or [ClassName, 'method'] |
| 61 | 'wrapper' => 'wrapper-id', // DOM ID to replace/update |
| 62 | 'event' => 'change', // JS event (change, click, blur, etc.) |
| 63 | 'method' => 'replaceWith', // replaceWith, append, prepend, etc. |
| 64 | 'effect' => 'fade', // none, slide, fade |
| 65 | 'progress' => [ |
| 66 | 'type' => 'throbber', // throbber or bar |
| 67 | 'message' => NULL, |
| 68 | ], |
| 69 | 'url' => NULL, // Custom URL (leave NULL for default) |
| 70 | 'options' => [], // Additional jQuery.ajax options |
| 71 | ], |
| 72 | ``` |
| 73 | |
| 74 | ## Trigger Form Rebuild |
| 75 | |
| 76 | ```php |
| 77 | public function submitForm(array &$form, FormStateInterface $form_state): void { |
| 78 | $form_state->setRebuild(TRUE); |
| 79 | } |
| 80 | ``` |