Drupal 8: Custom AJAX Commands

When changing the ajax responses with hook_ajax_render_alter(), you may sometimes want to add a custom ajax command. Drupal 8 actually supports a plugin-like functionality for it. This functionality needs to be served by a custom module and consists of 2 files - a src/Ajax class and a javascript file implementing the command.

1. The Ajax class file.

src/Ajax/MyCommand.php

<?php

namespace Drupal\mymodule\Ajax;

use
Drupal\Core\Ajax\CommandInterface;

/**
 * Set mymodule key.
 *
 * This command is implemented in Drupal.AjaxCommands.prototype.myCommand.
 */
class MyCommand implements CommandInterface {

 
/**
   * Assigned data.
   *
   * @var mixed
   */
 
protected $data;

 
/**
   * Constructs a \Drupal\mymodule\Ajax\MyCommand object.
   *
   * @param string $key
   *   Key name.
   * @param mixed $value
   *   Assigned value.
   */
 
public function __construct($data) {
   
$this->data = $data;
  }

 
/**
   * {@inheritdoc}
   */
 
public function render() {
    return [
     
'command' => 'myCommand',
     
'data' => $this->data,
    ];
  }

}
?>

2. The Javascript Implementation.

/**
* @file
* JavaScript behaviors for Ajax.
*/

(function ($, Drupal) {

  /**
   * Sample command.
   *
   * @see Drupal.AjaxCommands
   */
  Drupal.AjaxCommands.prototype.myCommand = function (ajax, response) {
    console.log(response.data);
  };

})(jQuery, Drupal);
Tags