How to add a button to Drupal 8/9 Modal

Components

Creating a modal with a title and some content in Ajax callback is easy:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;

public function ajaxCallback(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand($this->t('Title!'), $this->t('Some content.')));
  return $response;
}

If you also want to display a button in the modal, just provide the third parameter like this:

$options = [
  'buttons' => [
    'button1' => [
      'text' => $this->t('Close'),
      'id' => 'close-button',
      'onclick' => "jQuery('.ui-icon-closethick').click()",
    ],
  ],
];

...
$response->addCommand(new OpenModalDialogCommand($this->t('Title!'), $this->t('Some content.'), $options));
...

As you can see, by clicking on this button the modal will be closed.

About the Author

Goran Nikolovski is a creator, speaker, open-source contributor, web developer specializing in Drupal and DevOps enthusiast. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything related to Drupal? Get in touch.