Drupal Modal: add click callback to the modal button

Posted by edsardachuk - August 19, 2025

The client wanted for a button in the modal to add the product to the cart. The button was rendered dynamically via a dialog options attribute.

We all know that Drupal automatically moved form buttons into the jQuery UI dialog buttons pane. We also know that we can supply custom buttons via the data-dialog-options attribute. But it's impossible to supply a click callback for a button via the data-dialog-options attribute.

Well, we have to alter Drupal's dialog script and there no elegant way.


  let originalOpenDialog = Drupal.AjaxCommands.prototype.openDialog;

  Drupal.AjaxCommands.prototype.openDialog = function (ajax, response, status) {
    if (!response.selector) {
      return false;
    }
    var $dialog = $(response.selector);
    if (!$dialog.length) {
      $dialog = $("<div id=\"".concat(response.selector.replace(/^#/, ''), "\" class=\"ui-front\"></div>")).appendTo('body');
    }

    let $ajaxElement = $(ajax.element);

	// Make sure that button callback is added to the correct dialog.
    if ($dialog.length && $ajaxElement.length && $ajaxElement.hasClass('my-custom-class')) {
      response.dialogOptions.buttons['custom_button']['click'] = function (event) {
        // custom callback
      };
    }

    // Call original behavior.
    originalOpenDialog.call(this, ajax, response, status);
  };