2

vendor/magento/module-contact/Controller/Index/Post.php set in session messages like

$this->messageManager->addSuccess(
    __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
);
$this->_redirect('contact/index');

How do I access these messages in phtml?

1 Answer 1

4

You need to use dependency injection in order to load message manager in your block.

protected $messageManager;

public function __construct(
    Template\Context $context,
    \Magento\Framework\Message\ManagerInterface $messageManager,
    array $data = [])
{
    $this->messageManager = $messageManager;
    parent::__construct($context, $data);
}

Then you can implement new method getMessages in the same block which will retrieve recent messages from manager.

public function getMessages()
{
    $messages = array();
    $collection = $this->messageManager->getMessages(true);
    if ($collection && $collection->getItems()) {
        foreach ($collection->getItems() as $message) {
            $messages[] = $message->getText();
        }
    }
    return $messages;
}

And finally you can call method getMessages in block template.

<?php if ($messages = $block->getMessages()): ?>
    <?php foreach ($messages as $message): ?>
        <h1><?php echo $block->escapeHtml($message) ?></h1>
    <?php endforeach; ?>
<?php endif; ?>

Hope it helps.

1
  • It doesn't work for me. Magento 2.3.1 Mar 10, 2020 at 18:20

Your Answer

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

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