I want to set some error message at one method and display it at another method [closed]
-
16-02-2021 - |
Вопрос
I have a method , here I set some message .
function doSomeAction(){
$messenger = \Drupal::Messenger();
$messenger->addMessage('error msg',$messenger::TYPE_ERROR,true);
$response = new RedirectResponse(\Drupal::url('action_error.content',[], ['query' => ['error' => '1'],'absolute' => TRUE,]));
$response->send();
return $response;
}
I want to display this error message at another method
function action_error(){
$messenger = \Drupal::Messenger();
$msg = $messenger->messagesByType($messenger::TYPE_ERROR);
print_r($msg); die();
}
As a result I got Blank array.. Method doSomeAction and action_error is in same class differentiated by routing.yml
I have checked error-log from back-end , displaying some error i.e
RuntimeException: Failed to start the session because headers have already been sent by "\vendor\symfony\http-foundation\Response.php" at line 1286.
In D7
In drupal 7 drupal_set_message() & drupal_get_messages() available..We can easily handle message
Решение
It's not about how you set and get the message, although you normally don't get a message but display it in the system message block.
The issue is that you can't send a response from inside a Drupal 8 function. This sends the response headers too early, so that the session handling for the message doesn't work anymore. If doSomeAction() is a controller, then only return the redirect response, do not send it:
function doSomeAction(){
$messenger = \Drupal::Messenger();
$messenger->addMessage('error msg',$messenger::TYPE_ERROR,true);
$response = new RedirectResponse(\Drupal::url('action_error.content',[], ['query' =>
['error' => '1'],'absolute' => TRUE,]));
// $response->send(); ... don't send responses from inside a D8 function
return $response;
}