Share

Automatically hide messages in Magento 2 #codehacks

16 February, 2018

One of the things that I miss in Magento 2 is being able to automatically hide information messages on any page of the store. Modifying behavior is not excessively difficult, but you have to have clear a couple of things about how the messaging system works.

In Magento 2, Knockout is used to render messages through an observable, so messages can be displayed dynamically using ajax without reloading the page by adding them with the MessageFactory. In order to add a timeout to the block of messages, we need to modify the observable to handle the state of said block (hidden or not). The best option is to create a small module to manage these changes, using a mixin and modifying the template by layout. For or this post, however, we will do it in a more rough-and-ready way, so as not to get lost in the details of the module.

Overwriting the message block

As we are going to make an overwrite, we copy the file vendor/magento/module-theme/view/frontend/templates/messages.phtml en app/design/frontend/vendor/theme/Magento_Theme/templates/messages.phtml

The difference from the base file is the following line:

1
data-bind="visible: isVisible(), click: removeAll

With this, we can control if the message should be hidden and, if visible, hidden when the message is clicked. We will manage this behavior from the JS component.

Overwriting of the JS component

As with the phtml we copy the file: vendor/magento/module-theme/view/frontend/web/js/view/messages.js en app/design/frontend/vendor/theme/Magento_Theme/web/js/view/messages.js.

The resulting code is the following:

Notice that we have modified the attributes of the component (two added) and also the functions initObservable, isVisible, removeAll and onHiddenChange.

We’ve added an isHidden parameter is added, and a “listens”, which calls the  onHiddenChange function. This is the function that is responsible for launching the timeout and hiding the message using jQuery.

You can see this behavior in the checkout messages, which use a different message component than the entire store. With these changes, the behaviors are unified.

Category
Tags
Author
Senior Front-end Developer

Share

Subscribe to our newsletter

You may also like

We use third party cookies to improve our services and obtain statistical data of your browsing habits. If you continue browsing we consider that you accept its use. You can get more information at Privacy policy and cookies