Создание ajax команд Drupal 8-9
15 декабря 2020
Пример создания ajax команды для вывода сообщений в консоль браузера.
// src/Ajax/ConsoleLogCommand.php namespace Drupal\modulename\Ajax; use Drupal\Core\Ajax\CommandInterface; class ConsoleLogCommand implements CommandInterface { protected $message; /** * Command constructor. */ public function __construct($message) { $this->message = $message; } /** * {@inheritDoc} */ public function render() { return [ 'command' => 'consoleLog', 'message' => $this->message, ]; } }
// modulename.ajax.js (function ($, Drupal) { /** * Command "consoleLog". */ Drupal.AjaxCommands.prototype.consoleLog = function (ajax, response, status) { console.log(response.message); }; })(jQuery, Drupal);
Использование:
$response = new AjaxResponse(); $response->addCommand(new ConsoleLogCommand('Hello World!')); return $response;