How to use messageManager to show an error after redirect
You need to use object injection method on ur module action class to inject the message manager object into it, i provided an example of what u can do. Hope it helps
class Example
{
protected $_messageManager;
public function __construct(
\Magento\Framework\Message\ManagerInterface $messageManager
) {
$this->_messageManager = $messageManager;
}
public function method( ) {
..
$message = '...';
$this->_messageManager->addError($message);
..
}
}
Not sure if this is what you are looking for, but I'm giving it a shot.
You can retrieve the messages like this:
$messages = $this->messageManager->getMessages(true);
where messageManager
is an instance of \Magento\Framework\Message\ManagerInterface
.
In the core, this is used for ajax calls in order to return the error messages in the json response like this (\Magento\Catalog\Controller\Adminhtml\Category\Move
):
$block = $this->layoutFactory->create()->getMessagesBlock();
...
$block->setMessages($this->messageManager->getMessages(true));
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'messages' => $block->getGroupedHtml(),
'error' => $error
]);
For actions with output you shouldn't do anything (I think). The default.xml
layout file from the Magento_Theme
module already contains this block <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
that should handle the messages.
[Side note]:
Don't use $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
. Inject in your constructor an instance of Magento\Framework\Escaper
and use that.
you can also find the message manager accessible through $context
that is injected into actions constructors:
class yourAction extends \Magento\Framework\App\Action\Action
{
/** var ... */
protected $_messageManager;
public function __construct(Context $context)
{
$this->_messageManager = $context->getMessageManager();
parent::__construct($context);
}
Next just use as mentioned in answers above
$this->_messageManager->addError($message);
Hope it helps