drupal-8

How to close a modal window?


I've found a few tutorials on how to open a modal window using Drupal 8, not so hard:

// Add an AJAX command to open a modal dialog with the form as the content.
    $response->addCommand(new OpenModalDialogCommand('Load Window', $modal_form, ['width' => '800']));

But now how do I programmatically close this window? Or more simply, I would like a "Cancel" button available at the bottom of the modal?


Solution

  • Not sure if this is the best way to do it, but if you make an ajax call to a method that calls the CloseModalDialogCommand() the modal will close.

    The route:

    #Close the modal form
    product.closeProductModal:
      path: '/close-modal-form'
      defaults:
        _controller: '\Drupal\product\Controller\ModalController::closeModalForm'
        _title: 'Close modal'
      requirements:
        _permission: 'access content'
        _role: 'administrator'
    

    And then the controller:

    Use Drupal\Core\Ajax\CloseModalDialogCommand;
    class ModalController extends ControllerBase {
    public function closeModalForm(){
            $command = new CloseModalDialogCommand();
            $response = new AjaxResponse();
            $response->addCommand($command);
            return $response;
        }
    }