Magento 2 Beta – Show Session Messages at Front End

global-messagesmagento2magento2-dev-betasession

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

Best Answer

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