In Magento Message Collection /vendor/magento/framework/Message/Collection.php.

There are two method to get and delete message by Identifier, getMessageByIdentifier and deleteMessageByIdentifier. But I didn't get any way to set message with identifier, Does anyone knows how to set identifier?

1 Answer 1


In this particular class /vendor/magento/framework/Message/Collection.php there is a addMessage method that looks like

     * Adding new message to collection
     * @param MessageInterface $message
     * @return $this
    public function addMessage(MessageInterface $message)
        if (!isset($this->messages[$message->getType()])) {
            $this->messages[$message->getType()] = [];
        // Prevent adding duplicate messages.
        $foundIndex = array_search($message, $this->messages[$message->getType()], false);
        if (false === $foundIndex) {
            $this->messages[$message->getType()][] = $message;
            $this->lastAddedMessage = $message;
        } else {
            $this->lastAddedMessage = $this->messages[$message->getType()]    [$foundIndex];
        return $this;

You see, this method accepts @param MessageInterface $message.

If you open /vendor/magento/framework/Message/MessageInterface.php you will notice that there is setIdentifier mandated

     * Setter message identifier
     * @param string $identifier
     * @return $this
    public function setIdentifier($identifier);

So, the way to set an identifier is to do it on an object of type Magento\Framework\Message\MessageInterface, or to be even more accurate, of type Magento\Framework\Message\AbstractMessage because this abstract class actually implements MessageInterface.

Anyway, suppose you have injected a MenagerInterface in your class like

     * @param \Magento\Framework\Message\ManagerInterface $messageManager
    public function __construct(
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->messageManager = $messageManager;

you should be able to write something like this in a method of yours in the same class

   $messages = $this->messageManager->getMessages();
   $message = $messages->getLastAddedMessage();
   if ($message) {       


Please notice that $this->messageManager->getMessages() returns s Collection of messages, the one that you have mentioned Magento\Framework\Message\Collection, so if you need any other than the last message, you can just simply filter this collection, or loop through it to get the message you need and then you simply call setIdentifier on that message.

I hope this helps.

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.