Magento2 – How to Add JS Messages from Custom Module

javascriptmessagesmodulerequirejs

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?

Best Answer

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