3 namespace Drupal\Core\Ajax;
5 use Drupal\Core\Render\BubbleableMetadata;
6 use Drupal\Core\Render\AttachmentsInterface;
7 use Drupal\Core\Render\AttachmentsTrait;
8 use Symfony\Component\HttpFoundation\JsonResponse;
11 * JSON response object for AJAX requests.
15 class AjaxResponse extends JsonResponse implements AttachmentsInterface {
20 * The array of ajax commands.
24 protected $commands = [];
27 * Add an AJAX command to the response.
29 * @param \Drupal\Core\Ajax\CommandInterface $command
30 * An AJAX command object implementing CommandInterface.
31 * @param bool $prepend
32 * A boolean which determines whether the new command should be executed
33 * before previously added commands. Defaults to FALSE.
35 * @return AjaxResponse
36 * The current AjaxResponse.
38 public function addCommand(CommandInterface $command, $prepend = FALSE) {
40 array_unshift($this->commands, $command->render());
43 $this->commands[] = $command->render();
45 if ($command instanceof CommandWithAttachedAssetsInterface) {
46 $assets = $command->getAttachedAssets();
48 'library' => $assets->getLibraries(),
49 'drupalSettings' => $assets->getSettings(),
51 $attachments = BubbleableMetadata::mergeAttachments($this->getAttachments(), $attachments);
52 $this->setAttachments($attachments);
59 * Gets all AJAX commands.
61 * @return \Drupal\Core\Ajax\CommandInterface[]
62 * Returns all previously added AJAX commands.
64 public function &getCommands() {
65 return $this->commands;