How to show session messages at front end in magento 2 beta

The question:

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 MagentoFrameworkAppActionAction. 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);

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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 DarshCrudBlockMessage.php

namespace DarshCrudBlock;

class Message extends MagentoFrameworkViewElementMessages {

    public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoFrameworkMessageFactory $messageFactory,
        MagentoFrameworkMessageCollectionFactory $collectionFactory,
        MagentoFrameworkMessageManagerInterface $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 DarshCrudviewfrontendlayoutcrud_index_form.xml

   <referenceContainer name="page.messages">
        <block class="DarshCrudBlockMessage" name="darsh.crud.message" />
    </referenceContainer>

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

Now you can see your custom message added in DarshCrudControllerIndexForm.

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

Method 2

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

<referenceContainer name="page.messages">            
    <block class="MagentoFrameworkViewElementTemplate" name="ajax.message.placeholder" template="Magento_Theme::html/messages.phtml"/>
    <block class="MagentoFrameworkViewElementMessages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
</referenceContainer>

Method 3

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="MagentoFrameworkViewElementMessages" name="messages" as="messages"/>
    </referenceContainer>
</body>

This should fix it 😉

Method 4

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.

Method 5

Yes, I have added message using $resultRedirect object with

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

Please see below controller code

namespace DarshCrudControllerIndex;

use MagentoFrameworkAppFilesystemDirectoryList;

class Post extends MagentoContactControllerIndex {
//class Post extends MagentoFrameworkAppActionAction {


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

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

        $resultRedirect = $this->resultRedirectFactory->create();
        try {
            $model = $this->_objectManager->create('DarshCrudModelCrud');
            if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
                try {
                    $uploader = $this->_objectManager->create('MagentoMediaStorageModelFileUploader', array('fileId' => 'image'));
                    $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);
                    $mediaDirectory = $this->_objectManager->get('MagentoFrameworkFilesystem')
                            ->getDirectoryRead(DirectoryList::MEDIA);
                    $config = $this->_objectManager->get('DarshCrudModelCrud');
                    $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.

Method 6

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment