Is it possible to call response()->setStatusCode() within hook_theme_suggestions_page_alter?

drupal.stackexchange https://drupal.stackexchange.com/questions/295272

  •  26-02-2021
  •  | 
  •  

Question

We set up a custom error page theme by creating a block with the error text and then used the following code within a hook_theme_suggestions_page_alter implementation to determine when to override the template and show that "Page Not Found" block:

// error page template suggestions
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
  $status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
  $suggestions[] = 'page__error';
}

Now it turns out that due to some hosting constraints we need to be able to serve up a version of the "Page Not Found" page with an HTTP status code of 200. So, is it possible to use response()->setStatusCode() within hook_theme_suggestions_page_alter? I was hoping to just override the status code for a single arbitrary route, but so far my attempts to call it from there have been unsuccessful.

Admittedly, it would be a hack to call it there even if I can, but I wanted to check before reverting a bunch of theming code.

Was it helpful?

Solution

You don't need this code by the way, it is in core since D8.8.x, see https://www.drupal.org/node/2960810.

If you want to change the status code then do this in an event subscriber. If you want Drupal to build a normal 404 page and only change the status code of the already built error page then use a response event subscriber and set the status code:

$response->setStatusCode(200);

See this answer for the scaffolding https://drupal.stackexchange.com/a/201297/47547

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top