3 namespace Drupal\ajax_test\Form;
5 use Drupal\ajax_test\Controller\AjaxTestController;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Ajax\AjaxResponse;
8 use Drupal\Core\Ajax\OpenModalDialogCommand;
9 use Drupal\Core\Ajax\OpenDialogCommand;
10 use Drupal\Core\Form\FormStateInterface;
13 * Dummy form for testing DialogRenderer with _form routes.
17 class AjaxTestDialogForm extends FormBase {
22 public function getFormId() {
23 return 'ajax_test_dialog_form';
29 public function buildForm(array $form, FormStateInterface $form_state) {
30 // In order to use WebTestBase::drupalPostAjaxForm() to POST from a link, we need
31 // to have a dummy field we can set in WebTestBase::drupalPostForm() else it won't
33 $form['textfield'] = [
39 '#value' => 'Button 1 (modal)',
41 'callback' => '::modal',
47 '#value' => 'Button 2 (non-modal)',
49 'callback' => '::nonModal',
59 public function validateForm(array &$form, FormStateInterface $form_state) {
66 public function submitForm(array &$form, FormStateInterface $form_state) {
67 $form_state->setRedirect('ajax_test.dialog_contents');
71 * AJAX callback handler for AjaxTestDialogForm.
73 public function modal(&$form, FormStateInterface $form_state) {
74 return $this->dialog(TRUE);
78 * AJAX callback handler for AjaxTestDialogForm.
80 public function nonModal(&$form, FormStateInterface $form_state) {
81 return $this->dialog(FALSE);
85 * Util to render dialog in ajax callback.
87 * @param bool $is_modal
88 * (optional) TRUE if modal, FALSE if plain dialog. Defaults to FALSE.
90 * @return \Drupal\Core\Ajax\AjaxResponse
91 * An ajax response object.
93 protected function dialog($is_modal = FALSE) {
94 $content = AjaxTestController::dialogContents();
95 $response = new AjaxResponse();
96 $title = $this->t('AJAX Dialog & contents');
98 // Attach the library necessary for using the Open(Modal)DialogCommand and
99 // set the attachments for this Ajax response.
100 $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
103 $response->addCommand(new OpenModalDialogCommand($title, $content));
106 $selector = '#ajax-test-dialog-wrapper-1';
107 $response->addCommand(new OpenDialogCommand($selector, $title, $content));