I created a module to alter the cart message.


<?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_postdispatch_checkout_cart_add">
    <observer name="updatemessage" instance="Eight25media\Changemsg\Observer\UpdateCartSuccessMessage" />



namespace Eight25media\Changemsg\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class UpdateCartSuccessMessage implements ObserverInterface
/** @var \Magento\Framework\Message\ManagerInterface */
protected $messageManager;

/** @var \Magento\Framework\UrlInterface */
protected $url;

public function __construct(
    \Magento\Framework\Message\ManagerInterface $managerInterface,
    \Magento\Framework\UrlInterface $url
) {
    $this->messageManager = $managerInterface;
    $this->url = $url;

public function execute(\Magento\Framework\Event\Observer $observer) {
    $messageCollection = $this->messageManager->getMessages();
    $message = $messageCollection->getLastAddedMessage()->getText();

    $message = str_replace(' shopping', '', $message);
     $st = strpos($message, "don");
    $st1 = strpos($message, "have");
    if ($st !== false && $st1 !== false) {
        $cartLink = 'You can request a quote, continue shopping, or view your cart <a href="'. $this->url->getUrl('checkout/cart') .'">here</a>';
        $cartLink = 'You can continue shopping or view your cart <a href="'. $this->url->getUrl('checkout/cart') .'">here</a>';

    $this->messageManager->addSuccess($message . '  ' . $cartLink);

If i remove true in this line $messageCollection = $this->messageManager->getMessages(true); i am getting 3 messages like this image.where success message added in 2 different section. if i add true in this line $messageCollection = $this->messageManager->getMessages(true); i am getting the last latest last message only.

Before come to my last message i want to add the previous message also to the final message.How can i concatenate this message in this observer file. enter image description here

1 Answer 1


Not sure I understand what you need here, but in case you want to modify the last message you can try this.

$messageCollection = $this->messageManager->getMessages();
$lastMessage = $messageCollection->getLastAddedMessage();
if ($lastMessage) {
    $messageText = $lastMessage->getText();
    $messageText = modify here your message as you want.

Calling $this->messageManager->addSuccess will always add a new message to the session.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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