2

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.

2 Answers 2

4

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('/');
5
  • Thanks! Is that the latest release, or are you using one of the systems that launched with the Merchant Beta? Dec 10, 2015 at 5:54
  • I using version 2.0.0 latest release.
    – LinoPham
    Dec 10, 2015 at 5:59
  • Hello, could you please say if this is really resolved? I'm using 2.0.4 and I still have this problem. Thank you! Apr 12, 2016 at 15:49
  • why we need to $resultRedirect = $this->resultRedirectFactory->create(); /** @return \Magento\Framework\Controller\Result\Redirect **/ return $resultRedirect->setPath('/');
    – Amit Bera
    Mar 28, 2017 at 8:59
  • why messages donot show when we this->_redirect(''); @AlanStorm Do have any idea for this case
    – Amit Bera
    Mar 28, 2017 at 9:00
1

I have struggled for hours with this exact issue and finally cracked as best I could. An example is worth a thousand words. Check out: https://github.com/zengoma/Magento2_MessageManagerExample. Any improvements, criticisms or compliments welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.