#! code: Drupal 9: The Correct Way To Redirect A Page

Drupal CMS

I was recently working with a Drupal 9 site and found some strange behaviour when saving certain types of content. The page would appear to save, but much of the content appeared to be missing. It had even failed to generate the paths for the page based on the path auto rules.

Digging deeper I found the root cause of the problem was an improperly created redirect in an insert hook within custom code written on the site. This code looked for the creation of a particular content type and then forced the redirect to happen.

This was more or less the code in question. 

use DrupalCoreEntityEntityInterface;
use SymfonyComponentHttpFoundationRedirectResponse;

function mymodule_entity_insert(EntityInterface $entity) {
if ($entity->getType() == ‘article’) {
(new RedirectResponse(‘/node/’ . ($entity->id())))->send();
exit();
}
}

This isn’t great code in itself, but the worst part is the call to the exit() function. This stops any code execution straight away, which is what caused out content type to be half created. By stopping code execution like this we are preventing any other hooks or services from acting upon the content type being inserted.

The secondary effect of this is that it also bypasses Drupal’s shutdown functions. When Drupal starts a page request is registers a few methods that are to be called as the page response is closed down. This includes session management methods, but can also include a cron handler (if cron has been configured like that).

There is probably a reason why the exit() function was added. by default Drupal will perform a redirect after creating a page and I think the original developer was probably trying to prevent the upstream redirect from taking place. Unfortunately, they ended up creating more problems than just a redirect issue.

Read more.