Posts by Danijel Vrgoc

Moving the validation error message, this time globally

Moving the validation error message, this time globally

This blog post is a follow up to my previous blog post, which explained how to manage the display of error message on A2C section. By adding one mixin, you will be able to manage the position of error message on any form on any page. Let’s get the show on the road!

There is a proverb, “Life is full of surprises”. I would like to add, so is Magento 2. 😀

While trying some things out on the newsletter form, I noticed it would be great to change the position of the error message on the newsletter email field. I made another custom element #custom-newsletter-error in app/design/frontend/YOUR_VENDOR/YOUR_THEME/Magento_Newsletter/Templates/subscribe.phtml that should contain the error message…

<div class="block newsletter">
    ...
    <p id="custom-newsletter-error"><?= $block->escapeHtml('Newsletter error should appear here.') ?></p>
    ...
    <input name="email" type="email" id="newsletter"
           placeholder="<?= $block->escapeHtmlAttr(__('Enter your email address')) ?>"
           data-mage-init='{"mage/trim-input":{}}'
           data-validate="{required:true, 'validate-email':true}"
           data-errors-message-box="#custom-newsletter-error"
    />
    ...
</div>

However, the error message still appears in the default place, after the input field.

This means, there must be something specific on the product page, which makes it work in A2C section, but not elsewhere. In other words, it’s time to start digging through the code. After spending some finding what is where and putting all the pieces of the puzzle together, I was able to identify why it worked on product page only.

It is not nice to point fingers, but…. grouped product.

First thing that caught my attention was the custom data-errors-message-box attribute, which I thought had something to do with it. By searching the vendor/magento folder, the string was used in the following files:

  1. vendor/magento/module-catalog/view/frontend/web/product/view/validation.js
  2. vendor/magento/module-grouped-product/view/frontend/templates/product/view/type/grouped.phtml

Ok, so grouped product has the custom  <div id="validation-message-box"></div>, but I need to know where and how is the JavaScript file loaded on the page. After some additional search in the modules files, I found that it’s used as a RequireJS dependency in  vendor/magento/module-catalog/view/frontend/web/js/validate-product.js

define([
    'jquery',
    'mage/mage',
    'Magento_Catalog/product/view/validation',
    'catalogAddToCart'
], function ($) {
    ...
});

Which is loaded in vendor/magento/module-catalog/view/frontend/templates/product/view/addtocart.phtml

...
<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "Magento_Catalog/js/validate-product": {}
        }
    }
</script>

Improve the validation method!

With all the key information at hand, it is possible now to enhance the native validation process and provide this feature globally. First of all, create app/design/frontend/YOUR_VENDOR/YOUR_THEME/requirejs-config.js file and setup a mixin of main validation file:

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'mage/validation-mixin': true
            },
        }
    }
};

Next logical step is to create the app/design/frontend/YOUR_VENDOR/YOUR_THEME/web/mage/validation-mixin.js , which will override the native options errorPlacement keh  with the following content (actual modification is wrapped with comment, see snippet below):

define([
    'jquery',
    'jquery-ui-modules/widget'
], function ($) {
    'use strict';
 
    var enhancedMageValidation = {
        /**
         * @param {*} error
         * @param {*} element
         */
        options: {
            errorPlacement: function (error, element) {
                var errorPlacement = element,
                    fieldWrapper,
                    messageBox;
 
                /* added snippet - start */
                // use custom element to display error message
                if (element.attr('data-errors-message-box')) {
                    messageBox = $(element.attr('data-errors-message-box'));
                    messageBox.html(error);
 
                    return;
                }
                /* added snippet - end */
 
                // logic for date-picker error placement
                if (element.hasClass('_has-datepicker')) {
                    errorPlacement = element.siblings('button');
                }
                // logic for field wrapper
                fieldWrapper = element.closest('.addon');
 
                if (fieldWrapper.length) {
                    errorPlacement = fieldWrapper.after(error);
                }
                //logic for checkboxes/radio
                if (element.is(':checkbox') || element.is(':radio')) {
                    errorPlacement = element.parents('.control').children().last();
 
                    //fallback if group does not have .control parent
                    if (!errorPlacement.length) {
                        errorPlacement = element.siblings('label').last();
                    }
                }
                //logic for control with tooltip
                if (element.siblings('.tooltip').length) {
                    errorPlacement = element.siblings('.tooltip');
                }
                //logic for select with tooltip in after element
                if (element.next().find('.tooltip').length) {
                    errorPlacement = element.next();
                }
                errorPlacement.after(error);
            }
        }
    }
 
    return function (mageValidation) {
        $.widget('mage.validation', mageValidation, enhancedMageValidation);
 
        return $.mage.validation;
    }
});

Now, if you refresh the page, the validation of newsletter email field should be placed into the configured HTML element

And there you have it! 🙂 You should now be able to customize where the error message will be displayed on any page on any field.

To test this, I tried to make something very silly – to set the email error on H1 tag on Forgot Password page located in app/design/frontend/YOUR_VENDOR/YOUR_THEME/Magento_Customer/templates/form/forgotpassword.phtml file with the following change:

<form class="form password forget"
      action="<?= $block->escapeUrl($block->getUrl('*/*/forgotpasswordpost')) ?>"
      method="post"
      id="form-validate"
      data-mage-init='{"validation":{}}'>
    ...
    <input
        type="email"
        name="email"
        alt="email"
        id="email_address"
        class="input-text"
        value="<?= $block->escapeHtmlAttr($block->getEmailValue()) ?>"
        data-mage-init='{"mage/trim-input":{}}'
        data-validate="{required:true, 'validate-email':true}"
        data-errors-message-box="h1 span"
    />
</form>

This is how it looks like before submitting the form:

And this is how it looks like when submitting the form:

Read more

Moving the Add to Cart validation error message on product page

Moving the Add to Cart validation error message on product page

One quite often overlooked, but very important issue might happen because of design changes in the Add to Cart section on the Product Detail Page (PDP) in Magento 2.

This section is very likely to vary from project to project, but regardless of the scope of work and the volume of these changes, error validation on the Quantity field must not cause any issues whatsoever.

In this article, I will show you what needs to be done in such a case, which should be very easy and straightforward to implement in your custom theme.

Read more

Lazy load your images and iframes

lazyload images and iframes

Lazy loading is an effective way to improve your frontend performance. And that’s especially important on eCommerce websites. In this article, you will read (and learn) how to reduce page load time by loading your

  1. images on scroll and
  2. iframes on demand.

Let’s get started with lazy load!

Read more

Sticky Sidebar in Magento

Sticky sidebar

An idea for writing this blog post inspired me for implementing this feature on two Magento 1 projects, on first project it was one of many changes that were part of A/B testing, on the second one it was part of creating a new visual identity for clients store.

So, what basically is sticky sidebar and why should it be used to improve your conversion rate? Well, just like sticky header, the purpose of sticky sidebar is to have the sidebar element displayed in the viewport at all times (or an at least, when some conditions are met). This is ideal place to move the product options (configurable dropdowns, image swatches etc), add to cart button or any other element that is important for your product. With this being said, your customer is free to browse all of the content on your product and once the decision has been made to purchase the product, the add to cart button is just waiting to be clicked on!

Read more

Build your custom form validation rule

Build your custom form validation rule

This article is sort of a follow up on my previous article on custom form validation, which explains step-by-step what it takes to validate any form. The Magento 2 way, of course.

But what if you have to implement another field that has to be in a particular format or that kind of rule does not even exist? Well… Keep reading, my dear visitor, keep reading.

Read more

More/Less functionality in Magento2

More/Less functionality in Magento2

While working on a Magento 2 project for our client, I was supposed to create more/less button, which is not part of neither Blank or Luma themes. The button should be on product page, but only inside of Details tab on desktop (accordion on mobile), which displays product description field in Admin.

Before we get started, I have created a custom theme (Inchoo/MoreLess that is extending Blank theme), make sure to update the correct path for your theme as we go along. The code was written on latest (2.1.6) installation with sample data.

Read more

How to create a custom Grunt task in Magento 2

How to create a custom Grunt task in Magento 2

With almost 10 months after Magento 2 has been officially launched, Google has indexed a decent number of articles related to creating themes, fallback mechanisms and LESS compiling. Great job, community! =). But there was not a single one on how to create your own Grunt task. =(

Read more

Interactive Bash script for managing themes in Magento 2

Interactive Bash script for managing themes in Magento 2

Do you remember, how many times you did something that was time consuming and/or required certain amount of steps to achieve your goal? After some time you had to repeat the whole process… And again… And again… I am pretty sure you came to an idea, “Wouldn’t it be really useful if I can somehow simplify the process?” Yes, you are correct, the same question troubled me when trying to figure out how the make my life easier when creating a custom theme. Unlike Magento 1, Magento 2 has a different (and more complex) way of setting up themes, so I started developing a Bash script that will make my life easier. Hopefully, yours as well.

Read more