setAttachments example

if (!$response instanceof HtmlResponse) {
      return;
    }

    $attachments = $response->getAttachments();
    if (empty($attachments['placeholders'])) {
      return;
    }

    $attachments['placeholders'] = $this->placeholderStrategy->processPlaceholders($attachments['placeholders']);

    $response->setAttachments($attachments);
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    // Run shortly before HtmlResponseSubscriber.     $events[KernelEvents::RESPONSE][] = ['onRespond', 5];
    return $events;
  }

}

  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    // First render the main content, because it might provide a title.     $content = $this->renderer->renderRoot($main_content);

    // Attach the library necessary for using the OpenModalDialogCommand and set     // the attachments for this Ajax response.     $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $response->setAttachments($main_content['#attached']);

    // If the main content doesn't provide a title, use the title resolver.     $title = $main_content['#title'] ?? $this->titleResolver->getTitle($request$route_match->getRouteObject());

    // Determine the title: use the title provided by the main content if any,     // otherwise get it from the routing information.     $options = $request->request->all('dialogOptions');

    $response->addCommand(new OpenModalDialogCommand($title$content$options));
    return $response;
  }

}
return [
      // Second operand is a BubbleableMetadata object.       // All empty.       [(new BubbleableMetadata())(new BubbleableMetadata())(new BubbleableMetadata())],
      // Cache contexts.       [(new BubbleableMetadata())->setCacheContexts(['foo'])(new BubbleableMetadata())->setCacheContexts(['bar'])(new BubbleableMetadata())->setCacheContexts(['bar', 'foo'])],
      // Cache tags.       [(new BubbleableMetadata())->setCacheTags(['foo'])(new BubbleableMetadata())->setCacheTags(['bar'])(new BubbleableMetadata())->setCacheTags(['foo', 'bar'])],
      // Cache max-ages.       [(new BubbleableMetadata())->setCacheMaxAge(60)(new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT)(new BubbleableMetadata())->setCacheMaxAge(60)],
      // Assets.       [(new BubbleableMetadata())->setAttachments(['library' => ['core/foo']])(new BubbleableMetadata())->setAttachments(['library' => ['core/bar']])(new BubbleableMetadata())->setAttachments(['library' => ['core/foo', 'core/bar']])],
      // Placeholders.       [(new BubbleableMetadata())->setAttachments(['placeholders' => ['<my-placeholder>' => ['callback', ['A']]]])(new BubbleableMetadata())->setAttachments(['placeholders' => ['<my-placeholder>' => ['callback', ['A']]]])(new BubbleableMetadata())->setAttachments(['placeholders' => ['<my-placeholder>' => ['callback', ['A']]]])],

      // Second operand is a CacheableMetadata object.       // All empty.       [(new BubbleableMetadata())(new CacheableMetadata())(new BubbleableMetadata())],
      // Cache contexts.       [(new BubbleableMetadata())->setCacheContexts(['foo'])(new CacheableMetadata())->setCacheContexts(['bar'])(new BubbleableMetadata())->setCacheContexts(['bar', 'foo'])],
      // Cache tags.       [(new BubbleableMetadata())->setCacheTags(['foo'])(new CacheableMetadata())->setCacheTags(['bar'])(new BubbleableMetadata())->setCacheTags(['foo', 'bar'])],
      // Cache max-ages.
'node',
    'ajax_test',
    'ajax_forms_test',
  ];

  /** * Regression test: Settings command exists regardless of JS aggregation. */
  public function testAttachedSettings() {
    $assert = function D$message) {
      $response = new AjaxResponse();
      $response->setAttachments([
        'library' => ['core/drupalSettings'],
        'drupalSettings' => ['foo' => 'bar'],
      ]);

      $ajax_response_attachments_processor = \Drupal::service('ajax_response.attachments_processor');
      $subscriber = new AjaxResponseSubscriber($ajax_response_attachments_processor);
      $event = new ResponseEvent(
        \Drupal::service('http_kernel'),
        new Request(),
        HttpKernelInterface::MAIN_REQUEST,
        $response
      );
$error = $main_content['#error'];
      if (!empty($error)) {
        // Fall back to some default message otherwise use the specific one.         if (!is_string($error)) {
          $error = 'An error occurred while handling the request: The server received invalid input.';
        }
        $response->addCommand(new AlertCommand($error));
      }
    }

    $html = $this->renderer->renderRoot($main_content);
    $response->setAttachments($main_content['#attached']);

    // The selector for the insert command is NULL as the new content will     // replace the element making the Ajax call. The default 'replaceWith'     // behavior can be changed with #ajax['method'].     $response->addCommand(new InsertCommand(NULL, $html));
    $status_messages = ['#type' => 'status_messages'];
    $output = $this->renderer->renderRoot($status_messages);
    if (!empty($output)) {
      $response->addCommand(new PrependCommand(NULL, $output));
    }
    return $response;
  }
    // cacheability metadata of the same type is working (two links with cache     // tags).     $test_cases = [
      // \Drupal\Core\RouteProcessor\RouteProcessorCurrent: 'route' cache context.       [
        'uri' => 'route:<current>',
        'cacheability' => (new BubbleableMetadata())->setCacheContexts(['route']),
      ],
      // \Drupal\Core\Access\RouteProcessorCsrf: placeholder.       [
        'uri' => 'route:outbound_processing_test.route.csrf',
        'cacheability' => (new BubbleableMetadata())->setCacheContexts(['session'])->setAttachments(['placeholders' => []]),
      ],
      // \Drupal\Core\PathProcessor\PathProcessorFront: permanently cacheable.       [
        'uri' => 'internal:/',
        'cacheability' => (new BubbleableMetadata()),
      ],
      // \Drupal\url_alter_test\PathProcessorTest: user entity's cache tags.       [
        'uri' => 'internal:/user/1',
        'cacheability' => (new BubbleableMetadata())->setCacheTags(User::load(1)->getCacheTags()),
      ],
      [
public function setContent($content)static {
    // A render array can automatically be converted to a string and set the     // necessary metadata.     if (is_array($content) && (isset($content['#markup']))) {
      $content += [
        '#attached' => [
          'html_response_attachment_placeholders' => [],
          'placeholders' => [],
        ],
      ];
      $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));
      $this->setAttachments($content['#attached']);
      $content = $content['#markup'];
    }

    return parent::setContent($content);
  }

}
$this->processor->processOutbound('test', $route$parameters$bubbleable_metadata);
    // 'token' should be added to the parameters array.     $this->assertArrayHasKey('token', $parameters);
    // Bubbleable metadata of routes with a _csrf_token route requirement is a     // placeholder.     $path = 'test-path';
    $placeholder = Crypt::hashBase64($path);
    $placeholder_render_array = [
      '#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
    ];
    $this->assertSame($parameters['token']$placeholder);
    $this->assertEquals((new BubbleableMetadata())->setAttachments(['placeholders' => [$placeholder => $placeholder_render_array]])$bubbleable_metadata);
  }

  /** * Tests the processOutbound() method with a dynamic path and one replacement. */
  public function testProcessOutboundDynamicOne() {
    $route = new Route('/test-path/{slug}', []['_csrf_token' => 'TRUE']);
    $parameters = ['slug' => 100];

    $bubbleable_metadata = new BubbleableMetadata();
    $this->processor->processOutbound('test', $route$parameters$bubbleable_metadata);
    
$response = new BigPipeResponse(new HtmlResponse());

    // Add many placeholders.     $many_placeholders = [];
    for ($i = 0; $i < 400; $i++) {
      $many_placeholders[$this->randomMachineName(80)] = $this->randomMachineName(80);
    }
    $attachments = [
      'library' => [],
      'big_pipe_nojs_placeholders' => $many_placeholders,
    ];
    $response->setAttachments($attachments);

    // Construct minimal HTML response.     $content = '<html><body>content<drupal-big-pipe-scripts-bottom-marker>script-bottom<drupal-big-pipe-scripts-bottom-marker></body></html>';
    $response->setContent($content);

    // Capture the result to avoid PHPUnit complaining.     ob_start();
    $bigpipe->sendContent($response);
    $result = ob_get_clean();

    $this->assertNotEmpty($result);
  }
// These forms have the title built in, so set the title here:     $title = $form_state->get('title') ?: '';

    if ($ajax && (!$form_state->isExecuted() || $form_state->get('rerender'))) {
      // If the form didn't execute and we're using ajax, build up an       // Ajax command list to execute.       $response = new AjaxResponse();

      // Attach the library necessary for using the OpenModalDialogCommand and       // set the attachments for this Ajax response.       $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
      $response->setAttachments($form['#attached']);

      $display = '';
      $status_messages = ['#type' => 'status_messages'];
      if ($messages = $renderer->renderRoot($status_messages)) {
        $display = '<div class="views-messages">' . $messages . '</div>';
      }
      $display .= $output;

      $options = [
        'dialogClass' => 'views-ui-dialog js-views-ui-dialog',
        'width' => '75%',
      ];


  /** * Populates this BigPipeResponse object based on the original HTML response. */
  protected function populateBasedOnOriginalHtmlResponse() {
    // Clone the HtmlResponse's data into the new BigPipeResponse.     $this->headers = clone $this->originalHtmlResponse->headers;
    $this
      ->setStatusCode($this->originalHtmlResponse->getStatusCode())
      ->setContent($this->originalHtmlResponse->getContent())
      ->setAttachments($this->originalHtmlResponse->getAttachments())
      ->addCacheableDependency($this->originalHtmlResponse->getCacheableMetadata());

    // A BigPipe response can never be cached, because it is intended for a     // single user.     // @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1     $this->setPrivate();

    // Inform surrogates how they should handle BigPipe responses:     // - "no-store" specifies that the response should not be stored in cache;     // it is only to be used for the original request     // - "content" identifies what processing surrogates should perform on the

  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    // First render the main content, because it might provide a title.     $content = $this->renderer->renderRoot($main_content);

    // Attach the library necessary for using the OpenDialogCommand and set the     // attachments for this Ajax response.     $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $response->setAttachments($main_content['#attached']);

    // Determine the title: use the title provided by the main content if any,     // otherwise get it from the routing information.     $title = $main_content['#title'] ?? $this->titleResolver->getTitle($request$route_match->getRouteObject());

    // Determine the dialog options and the target for the OpenDialogCommand.     $options = $request->request->all('dialogOptions');
    $target = $this->determineTargetSelector($options$route_match);

    $response->addCommand(new OpenDialogCommand($target$title$content$options));
    return $response;
  }
// Now replace the attachment placeholders.       $this->renderHtmlResponseAttachmentPlaceholders($response$attachment_placeholders$variables);
    }

    // Set the HTTP headers and status code on the response if any bubbled.     if (!empty($attached['http_header'])) {
      $this->setHeaders($response$attached['http_header']);
    }

    // AttachmentsResponseProcessorInterface mandates that the response it     // processes contains the final attachment values.     $response->setAttachments($attached);

    return $response;
  }

  /** * Formats an attribute string for an HTTP header. * * @param array $attributes * An associative array of attributes such as 'rel'. * * @return string * A ; separated string ready for insertion in a HTTP header. No escaping is * performed for HTML entities, so this string is not safe to be printed. * * @internal * * @see https://www.drupal.org/node/3000051 */

    else {
      $this->commands[] = $command->render();
    }
    if ($command instanceof CommandWithAttachedAssetsInterface) {
      $assets = $command->getAttachedAssets();
      $attachments = [
        'library' => $assets->getLibraries(),
        'drupalSettings' => $assets->getSettings(),
      ];
      $attachments = BubbleableMetadata::mergeAttachments($this->getAttachments()$attachments);
      $this->setAttachments($attachments);
    }

    return $this;
  }

  /** * Gets all AJAX commands. * * @return array * Returns render arrays for all previously added commands. */
  

  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    // First render the main content, because it might provide a title.     $content = $this->renderer->renderRoot($main_content);

    // Attach the library necessary for using the OpenModalDialogCommand and set     // the attachments for this Ajax response.     $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $response->setAttachments($main_content['#attached']);

    // If the main content doesn't provide a title, use the title resolver.     $title = $main_content['#title'] ?? $this->titleResolver->getTitle($request$route_match->getRouteObject());

    // Determine the title: use the title provided by the main content if any,     // otherwise get it from the routing information.     $options = $request->request->all('dialogOptions');
    // Override width option.     switch ($this->mode) {
      case 'wide':
        $options['width'] = 700;
        
Home | Imprint | This part of the site doesn't use cookies.