Posted by Crell on November 17, 2012 at 4:23am
Project:
Drupal core
Introduced in branch:
8.x Description:
The API for returning Ajax commands from Drupal has changed. In Drupal 7, you would define a nested anonymous array of Ajax commands that line up with Javascript functions on the client-side. In Drupal 8, you create an AjaxResponse object and populate it with command objects. The AjaxResponse object will compile down to the necessary Javascript for you.
Drupal 7:
<?php
function my_page_callback() {
$commands[] = ajax_command_alert(t('Hello World'));
$commands[] = ajax_command_insert('.foo', '<h2>Goodbye World</h2>');
return array('#type' => 'ajax', '#commands' => $commands);
}
?>Drupal 8:
<?php
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\InsertCommand;
// @todo Convert this example to a Controller
function my_page_callback() {
$response = new AjaxResponse();
$response->addCommand(new AlertCommand(t('Hello World')));
$response->addCommand(new InsertCommand('.foo', '<h2>Goodbye World</h2>'));
return $response;
}
?>Any object that conforms to Drupal\Core\Ajax\CommandInterface may be used as an Ajax command. See /core/lib/Drupal/Core/Ajax for a list of the command objects Drupal ships with by default.
Impacts:
Module developers