Skip to content

Instantly share code, notes, and snippets.

@dmouse
Last active January 13, 2025 13:04
Drupal 8: how to create a sub-request
<?php
/**
* @file
* Contains Drupal\dmouse\Controller\SubRequestController.
* Generated by drupal/console.
*/
namespace Drupal\dmouse\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
class SubRequestController extends ControllerBase implements ContainerInjectionInterface {
/**
* Symfony\Component\HttpKernel\HttpKernelInterface definition.
*
* @var Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $httpKernel;
public function __construct(HttpKernelInterface $http_kernel) {
$this->httpKernel = $http_kernel;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('http_kernel.basic')
);
}
/**
* Index.
*
* @return string
* Return Hello string.
*/
public function index() {
$sub_request = Request::create('/search/node', 'GET');
$subResponse = $this->httpKernel->handle($sub_request, HttpKernelInterface::SUB_REQUEST);
$html = $subResponse->getContent();
return $subResponse;
}
}
@joegl
Copy link

joegl commented Feb 7, 2018

This is great, however, you need to update the protected property from $http_kernel to $httpKernel.

@ojacquet
Copy link

I lose all styling when I use this. Anyone knows why and how to fix that?

@WesWedding
Copy link

If anyone has arrived here with strange behavior (such as losing styling), it may be because you should be using $container->get('http_kernel.basic')

I was experiencing odd redirects whenever I was handling responses via $container->get('http_kernel')

@dmouse
Copy link
Author

dmouse commented Mar 13, 2020

thanks @WesWedding I updated the reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment