Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By Crell on
Change record status:
Published (View all published change records)
Project:
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:
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:
namespace Drupal\my_module\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\InsertCommand;
class MyModuleController {
public function myModuleControllerMethod() {
$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