3 namespace Drupal\Core\Render\MainContent;
5 use Drupal\Core\Ajax\AjaxResponse;
6 use Drupal\Core\Ajax\AlertCommand;
7 use Drupal\Core\Ajax\InsertCommand;
8 use Drupal\Core\Ajax\PrependCommand;
9 use Drupal\Core\Render\ElementInfoManagerInterface;
10 use Drupal\Core\Routing\RouteMatchInterface;
11 use Symfony\Component\HttpFoundation\Request;
14 * Default main content renderer for Ajax requests.
16 class AjaxRenderer implements MainContentRendererInterface {
19 * The controller resolver.
21 * @var \Drupal\Core\Controller\ControllerResolverInterface
23 protected $controllerResolver;
26 * The element info manager.
28 * @var \Drupal\Core\Render\ElementInfoManagerInterface
30 protected $elementInfoManager;
33 * Constructs a new AjaxRenderer instance.
35 * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info_manager
36 * The element info manager.
38 public function __construct(ElementInfoManagerInterface $element_info_manager) {
39 $this->elementInfoManager = $element_info_manager;
45 public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
46 $response = new AjaxResponse();
48 if (isset($main_content['#type']) && ($main_content['#type'] == 'ajax')) {
49 // Complex Ajax callbacks can return a result that contains an error
50 // message or a specific set of commands to send to the browser.
51 $main_content += $this->elementInfoManager->getInfo('ajax');
52 $error = $main_content['#error'];
54 // Fall back to some default message otherwise use the specific one.
55 if (!is_string($error)) {
56 $error = 'An error occurred while handling the request: The server received invalid input.';
58 $response->addCommand(new AlertCommand($error));
62 $html = $this->drupalRenderRoot($main_content);
63 $response->setAttachments($main_content['#attached']);
65 // The selector for the insert command is NULL as the new content will
66 // replace the element making the Ajax call. The default 'replaceWith'
67 // behavior can be changed with #ajax['method'].
68 $response->addCommand(new InsertCommand(NULL, $html));
69 $status_messages = ['#type' => 'status_messages'];
70 $output = $this->drupalRenderRoot($status_messages);
71 if (!empty($output)) {
72 $response->addCommand(new PrependCommand(NULL, $output));
78 * Wraps drupal_render_root().
80 * @todo Remove as part of https://www.drupal.org/node/2182149.
82 protected function drupalRenderRoot(&$elements) {
83 return drupal_render_root($elements);