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 web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.