Magento 2 – Ensure Message Manager Messages Show After Redirect

magento2session

I have the following code in a Magento controller execute method

public function execute()
{
    //...
    /* var $messageManager \Magento\Framework\Message\ManagerInterface $messageManager */    

    $this->messageManager->addError('My Error');

    return $this->resultFactory->create(
        \Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT
        )->setUrl('/');    

    //...
}

My expectation is that this will

  1. Add my message to the session messenger
  2. Redirect the user to the home page
  3. Display the error message out of the session messenger

Numbers one and two appear to go off without a hitch. Number 3, however, does not. My error message does not display when I redirect to the home page.

Strangely, if I navigate to a category listing page and add a product, the error message does display (along with the cart success message).

Am I using the message manager properly? Or is it meant only for ajax requests? If the later, is there a system in Magento 2 that replicates the old Magento 1 "add notices to session, redirect, and have them display on the next page load" functionality?

This is specifically for a project on the merchant beta, but I'd also be interested in answers that cover any changes in the official 2.0 release.

This is also for the frontend theme(s), but I'd be interested in difference between the adminhtml and frontend areas.

Best Answer

I using this function below to return value and it's working fine(adminhtml and frontend):

/** @var \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory  **/

$resultRedirect = $this->resultRedirectFactory->create(); 
/** @return \Magento\Framework\Controller\Result\Redirect **/

return $resultRedirect->setPath('/');
Related Topic