Drupal - How do I redirect users and show a message?
Set the repeat parameter in drupal_set_message()
to TRUE and it will work:
$response = new RedirectResponse($url);
$response->send();
drupal_set_message(t('My message after redirect'), 'status', TRUE);
I had this same issue, but using an exit to end the script is not a good idea. Drupal has shutdown functions that it runs at the end of a page load which can be important. Instead I just had to return the redirect response directly:
public function buildForm(array $form, FormStateInterface $form_state) {
$wizard_data = $form_state->getTemporaryValue('wizard');
if (empty($wizard_data['csv_data'])) {
drupal_set_message($this->t('Please upload a file first.'), 'error');
return $this->redirect('my.route')->send();
}
Redirect:
// Drupal\Core\Url;
// Symfony\Component\HttpFoundation\RedirectResponse;
$url = Url::fromUri('internal:/');
$response = new RedirectResponse($url->toString());
$response->send();
Messeges using static service:
\Drupal::messenger()->addStatus($message);
Other equivalents:
addMessage()
, addError()
, addWarning()
.
References:
RedirectResponse
Url
Drupal::messenger
MessengerInterface