Created
October 27, 2025 15:49
-
-
Save drubb/8433405b5d7e4fb2ed0d64726783af45 to your computer and use it in GitHub Desktop.
Simple Drupal Ajax Form
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 | |
| declare(strict_types=1); | |
| namespace Drupal\my_module\Form; | |
| use Drupal\Core\Form\FormBase; | |
| use Drupal\Core\Form\FormStateInterface; | |
| /** | |
| * Provides a simple ajax form. | |
| */ | |
| final class AjaxExampleForm extends FormBase { | |
| /** | |
| * {@inheritdoc} | |
| */ | |
| public function getFormId(): string { | |
| return 'my_module_ajax_example'; | |
| } | |
| /** | |
| * {@inheritdoc} | |
| */ | |
| public function buildForm(array $form, FormStateInterface $form_state): array { | |
| $form['choice'] = [ | |
| '#type' => 'select', | |
| '#title' => 'First field', | |
| '#options' => [ | |
| '1' => 'Mandatory', | |
| '2' => 'Optional', | |
| ], | |
| '#description' => 'Determines whether the second field is mandatory or optional.', | |
| '#required' => TRUE, | |
| '#ajax' => [ | |
| 'callback' => '::changeRequired', | |
| 'wrapper' => 'second-field', | |
| ], | |
| ]; | |
| $isOptional = ($form_state->getValue('choice') === '2'); | |
| $form['second'] = [ | |
| '#type' => 'textfield', | |
| '#title' => 'Second field', | |
| '#description' => $isOptional ? 'This field is optional.' : 'This field is mandatory.', | |
| '#required' => !$isOptional, | |
| '#prefix' => '<div id="second-field">', | |
| '#suffix' => '</div>', | |
| ]; | |
| return $form; | |
| } | |
| // Ajax Callback. | |
| public function changeRequired(array &$form, FormStateInterface $form_state) { | |
| return $form['second']; | |
| } | |
| public function submitForm(array &$form, FormStateInterface $form_state) {} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment