2

How do I add messages using Magento 2 Ui messages to page via javascript from a custom module?

I have found a file in Magento/Ui/view/frontend/web/js/view/messages.js that appears to be responsible for adding messages to the page, in the same manner as the php message manager interface.

Am I mistaken? If not, how can it be used to add errors and success messages like the php version?

dotancohen
1,1306 silver badges21 bronze badges
asked Sep 26, 2016 at 13:52
2
  • 1
    please provide more detail to your question Commented Sep 26, 2016 at 13:52
  • Hi @LM_Fielding, did you manage to find a solution for this issue? I've stumbled upon 'Magento_Ui/js/model/messageList' myself but I can't seem to get it to work. This is what I did: define(['Magento_Ui/js/model/messageList'], function(messageList) { messageList.addErrorMessage({ message: 'Message to be shown.' }); }); But the message is never displayed. Commented Mar 28, 2018 at 10:28

1 Answer 1

8

Looks like you're on the right way. You just need to perform the following simple steps in order to get it working.

  1. Add the messages container as a child into your component. It can be done via js layout config.

    <item name="children" xsi:type="array">
     <item name="messages" xsi:type="array">
     <item name="component" xsi:type="string">Magento_Ui/js/view/messages</item>
     <item name="displayArea" xsi:type="string">messages</item>
     </item>
    </item>
    

    Example: Magento_Customer::view/frontend/layout/default.xml

  2. Then add the messages block into a place where you expect to see the messages within your custom KnockoutJS template:

    <!-- ko foreach: getRegion('messages') -->
    <!-- ko template: getTemplate() --><!-- /ko -->
    <!--/ko-->
    

    Example: Magento_Customer::view/frontend/web/template/authentication-popup.html

  3. Add the messages list dependency into your js file and call the corresponding function: addSuccessMessage or addErrorMessage.

    define([
     'Magento_Ui/js/model/messageList'
    ], function (messageList) {
     messageList.addSuccessMessage({ message: 'Message to be shown.' });
    });
    

    Example: Magento_Customer::view/frontend/web/js/action/login.js

answered Apr 23, 2018 at 14:24
1
  • shall I do the same thing for backend Commented Mar 8, 2019 at 3:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.