3 namespace Drupal\Core\Render\MainContent;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Ajax\AjaxResponse;
7 use Drupal\Core\Ajax\OpenDialogCommand;
8 use Drupal\Core\Controller\TitleResolverInterface;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Symfony\Component\HttpFoundation\Request;
13 * Default main content renderer for dialog requests.
15 class DialogRenderer implements MainContentRendererInterface {
20 * @var \Drupal\Core\Controller\TitleResolverInterface
22 protected $titleResolver;
25 * Constructs a new DialogRenderer.
27 * @param \Drupal\Core\Controller\TitleResolverInterface $title_resolver
30 public function __construct(TitleResolverInterface $title_resolver) {
31 $this->titleResolver = $title_resolver;
37 public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
38 $response = new AjaxResponse();
40 // First render the main content, because it might provide a title.
41 $content = drupal_render_root($main_content);
43 // Attach the library necessary for using the OpenDialogCommand and set the
44 // attachments for this Ajax response.
45 $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
46 $response->setAttachments($main_content['#attached']);
48 // Determine the title: use the title provided by the main content if any,
49 // otherwise get it from the routing information.
50 $title = isset($main_content['#title']) ? $main_content['#title'] : $this->titleResolver->getTitle($request, $route_match->getRouteObject());
52 // Determine the dialog options and the target for the OpenDialogCommand.
53 $options = $request->request->get('dialogOptions', []);
54 $target = $this->determineTargetSelector($options, $route_match);
56 $response->addCommand(new OpenDialogCommand($target, $title, $content, $options));
61 * Determine the target selector for the OpenDialogCommand.
63 * @param array &$options
64 * The 'target' option, if set, is used, and then removed from $options.
65 * @param RouteMatchInterface $route_match
66 * When no 'target' option is set in $options, $route_match is used instead
67 * to determine the target.
70 * The target selector.
72 protected function determineTargetSelector(array &$options, RouteMatchInterface $route_match) {
73 // Generate the target wrapper for the dialog.
74 if (isset($options['target'])) {
75 // If the target was nominated in the incoming options, use that.
76 $target = $options['target'];
77 // Ensure the target includes the #.
78 if (substr($target, 0, 1) != '#') {
79 $target = '#' . $target;
81 // This shouldn't be passed on to jQuery.ui.dialog.
82 unset($options['target']);
85 // Generate a target based on the route id.
86 $route_name = $route_match->getRouteName();
87 $target = '#' . Html::getUniqueId("drupal-dialog-$route_name");