I am trying to write a simple extension that utilises the \Magento\Framework\Message\ManagerInterface
to add a custom success message on all pages. I have built this observer:
<?php
namespace Revolution\MessageCentre\Observer;
use Magento\Framework\Event\ObserverInterface;
class ControllerActionPredispathObserver implements ObserverInterface
{
/**
* @var \Magento\Framework\App\RequestInterface
*/
protected $request;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* @param \Magento\Framework\App\RequestInterface $request
* @param \Magento\Framework\Message\ManagerInterface $messageManager
*/
public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Magento\Framework\Message\ManagerInterface $messageManager
) {
$this->request = $request;
$this->messageManager = $messageManager;
}
/**
* Pre-dispatch frontend controller action
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$requestParams = $this->request->getParams();
$this->messageManager->addSuccessMessage(__('This is a success message'));
}
}
The observer listens on frontend controller action predispatch. Here is the etc/frontend/events.xml
:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch">
<observer name="revolution_messagecentre_controller_action_predispatch" instance="MyNamespace\MessageCentre\Observer\ControllerActionPredispathObserver" shared="false" />
</event>
</config>
It works fine as it adds the success message on the /checkout/cart/
page, however it only appears on this page. I can see in the network panel of Chrome and in the source that the magento/module-theme/view/frontend/templates/messages.phtml
is appearing on pages like the product page, but it is empty, no messages are coming through here. Why? I have done a comprehensive nuke of all caches, tried again with browser cache disabled but still no messages. What triggers the actual rendering of the messages, and why is this missing from all pages except the cart? Thanks in advance!