Skip to content

Instantly share code, notes, and snippets.

@mattschaff
Created April 3, 2019 14:10
Show Gist options
  • Save mattschaff/bf4d812a8ada9754810e603c361d3956 to your computer and use it in GitHub Desktop.
Save mattschaff/bf4d812a8ada9754810e603c361d3956 to your computer and use it in GitHub Desktop.
Drupal 8: Redirect with a warning message
<?php
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Redirects with warning message
*
* When you need to redirect user upon a page load in procedural code.
* Otherwise, use the Controller response or ...
* ... $form_state->setRedirect('routing_machine_name'); return;
*
* @param string $url
* @param string $message
*/
function _redirect_with_warning($url, $message = NULL) {
$response = new RedirectResponse($url, 302);
$response->send();
if ($message) {
\Drupal::messenger()->addWarning($message);
}
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment