How to show success message in session Magento2

In Magento 2, we can do achieve this in two steps:

First, we need to assign the message to 'messageManager' from your module as below:

$this->messageManager->addSuccess(__('This is a success message.'));

Secondly, we need to assign a placeholder for the message through frontend layout xml used in the module as given below inside the <body> tag:

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

The above layout update will make use of the magento's message template to display the messages.


Magento2 is using MessageInterface to add all message, please use below code to show Messages

Magento Message Framework class

\Magento\Framework\Message\ManagerInterface

use below code in your file to add messages,

protected _messageManager;

public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Message\ManagerInterface $messageManager) {
        parent::__construct($context);
        $this->_messageManager = $messageManager;
    }

and then add below functions in your methods to show messages:

$this->_messageManager->addError(__("Error Message"));
$this->_messageManager->addWarning(__("Warning"));
$this->_messageManager->addNotice(__("Notice"));
$this->_messageManager->addSuccess(__("Success Message"));

I hope this will help you fixing your issue.


You can try below code to add success or error Messages.

$this->messageManager was in parent class calling from

\Magento\Framework\App\Action\Action

$this->messageManager = $context->getMessageManager();

class Post extends \Magento\Framework\App\Action\Action
{

    public function __construct(
        \Magento\Framework\App\Action\Context $context
    ) {
        parent::__construct($context);
    }
    public function execute()
    {

$data = $this->getRequest()->getPostValue();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();       
$question = $objectManager->create('Myvendor\Mymodule\Model\Feedback');

/****** set your data *********/
$question->setData($data);
$question->save();

$this->messageManager->addSuccess( __('Thanks for your valuable feedback.') );

/* ***** OR

$this->messageManager->addError('There is something went wrong');
$this->_redirect('*/');
return;
    }

You can assign messages to messageManager

$this->_messageManager->addError(__("Error"));
$this->_messageManager->addWarning(__("Warning"));
$this->_messageManager->addNotice(__("Notice"));
$this->_messageManager->addSuccess(__("Success"));

You can find some more information on how to Display notification messages

Hope this helps.