13

I want to show an error or success message in my magento 2 module. I have extended my front-end controller with the class name \Magento\Framework\App\Action\Action. Then I redirect client to home page using following code

$this->messageManager->addError($SomeMessage);
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($base_path);

Everything works fine but this line never prints the error

$this->messageManager->addError($SomeMessage);
2
  • Are you have to show messages on storefront or in admin panel?
    – KAndy
    Sep 13, 2015 at 20:22
  • I want to show messages on storefront Sep 14, 2015 at 4:49

6 Answers 6

7

I have faced issue related to display message in Magento2 Beta source. In some source by default display error and success message but in some case it do not display then follow below steps.

Step 1: I have created Message.php file in my custom module in Darsh\Crud\Block\Message.php



namespace Darsh\Crud\Block;

class Message extends \Magento\Framework\View\Element\Messages {

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Message\Factory $messageFactory,
        \Magento\Framework\Message\CollectionFactory $collectionFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,       
        array $data = []
    ) {
        parent::__construct(
            $context,
            $messageFactory,
            $collectionFactory,
            $messageManager,
            $data
        );       
    }

    protected function _prepareLayout()
    {
        $this->addMessages($this->messageManager->getMessages(true));       
        return parent::_prepareLayout();
    }

}

Step 2: Added message block in to handeler in Darsh\Crud\view\frontend\layout\crud_index_form.xml

   <referenceContainer name="page.messages">
        <block class="Darsh\Crud\Block\Message" name="darsh.crud.message" />
    </referenceContainer>

Please add opening and closing Tag <> for layout handle.

Now you can see your custom message added in Darsh\Crud\Controller\Index\Form.

If you face any issue please see Example module on https://github.com/Darshanmodi1427/Magento2_Crud_Operation.git

1
  • After some modifications i got the results :) Jan 15, 2016 at 10:45
7

In layout file i have used the below code. now i got the message in frontend.

<referenceContainer name="page.messages">            
    <block class="Magento\Framework\View\Element\Template" name="ajax.message.placeholder" template="Magento_Theme::html/messages.phtml"/>
    <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
</referenceContainer>
2
  • Thankyou Marius
    – Naveenbos
    Jul 27, 2016 at 11:50
  • 1
    Thanks @Naveen. Works fine in Magento 2 in my custom module
    – Jackson
    Sep 20, 2016 at 10:11
6

I have faced the same issue and I was able to fix it by adding the following in my layout file:

<body>
    <!-- your layout content -->
    <referenceContainer name="page.messages">
        <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages"/>
    </referenceContainer>
</body>

This should fix it ;)

2

Have you tried returning your last line of the code?

return $resultRedirect->setPath($base_path);

The actual addError function looks fine unless the $SomeMessage variable is empty, have you checked that as well?

If that fails maybe you can try redirecting using the _redirect function instead like:

$this->_redirect('*/*/');

Maybe the resultRedirect function clears the message session so your message never gets displayed.

2

Yes, I have added message using $resultRedirect object with

$resultRedirect->setUrl($this->_redirect('crud/index/form'));

Please see below controller code


namespace Darsh\Crud\Controller\Index;

use Magento\Framework\App\Filesystem\DirectoryList;

class Post extends \Magento\Contact\Controller\Index {
//class Post extends \Magento\Framework\App\Action\Action {


    public function execute() {
        $data = $this->getRequest()->getPostValue();

        if (!$data) {
            $this->_redirect('crud/index/form');
            return;
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        try {
            $model = $this->_objectManager->create('Darsh\Crud\Model\Crud');
            if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
                try {
                    $uploader = $this->_objectManager->create('\Magento\MediaStorage\Model\File\Uploader', array('fileId' => 'image'));
                    $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);
                    $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                            ->getDirectoryRead(DirectoryList::MEDIA);
                    $config = $this->_objectManager->get('Darsh\Crud\Model\Crud');
                    $result = $uploader->save($mediaDirectory->getAbsolutePath('bannerslider/images'));
                    unset($result['tmp_name']);
                    unset($result['path']);
                    $data['image'] = $result['file'];
                } catch (Exception $e) {
                    $data['image'] = $_FILES['image']['name'];
                }
            } else if (isset($data['image']['delete'])) {
                $data['image'] = '';
            } else if (isset($data['image']['value'])) {
                $data['image'] = $data['image']['value'];
            }

            $model->setData($data);
            $model->setStoreId($this->storeManager->getStore()->getId())
                        ->setStores([$this->storeManager->getStore()->getId()])
                        ->save();
            try {
                $model->save();
                $this->messageManager->addSuccess(
                        __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
                );
                //$this->_redirect('crud/index/form');
                //return;
            } catch (\Exception $e) {
                $this->messageManager->addError(
                        __('We can\'t process your request right now. Sorry, that\'s all we know.'));
                //$this->_redirect('crud/index/form');
                //return;
            }
        } catch (\Exception $e) {
            $this->messageManager->addError(
                    __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            //$this->_redirect('crud/index/form');
            //return;
        }

        $resultRedirect->setUrl($this->_redirect('crud/index/form'));

        return $resultRedirect;
    }

}

Thanks.

2

Try using XDEBUG, set break point at your controller action. Maybe it was duplicated redirect and making lost messages in manager.

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.