Add Complex Messages

Would you like to add a message that contains more information than just text? For example a message with a link to the customer account? Let's see how you can achieve that in Magento 2.

Is well known that if you want to add a message in your page after an action, you can simply do that by using the following functions depending on the type of the message.

  • addSuccessMessage()
  • addErrorMessage()
  • addNoticeMessage()
  • addWarningMessage()

All the above functions are provided by the Magento\Framework\Message\ManagerInterface interface. When you add a message using one of these function the output is automatically escaped. That means that if you want to add a link to the message the result will be the following.

The solution for that is to add the message using the following functions, which are also provided by the ManagerInterface.

  • addComplexSuccessMessage($identifier, array $data = [], $group = null)
  • addComplexErrorMessage($identifier, array $data = [], $group = null)
  • addComplexNoticeMessage($identifier, array $data = [], $group = null)
  • addComplexWarningMessage($identifier, array $data = [], $group = null)

Furthermore, you will need also to add and define a template that will be used for the identifier. Defined a template for the identifier in the di.xml like below.

Add a template

Add a complex success message in your action.

So now the message with the link will be show correctly like below.

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!