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. 🙂
Consider the following (and simplified) scenario – Add to Cart button is positioned on the right hand side of the Quantity field. You can achieve this with the following two CSS rules:
.box-tocart .fieldset {
display: flex;
align-items: center;
}
.box-tocart .actions {
margin-left: 16px;
}
In case an error occurs (such as amount of 0 as Quantity), it will push the button away, which does not look good.
You can resolve situation like this very easily by making two small changes in addtocart.phtml
file in a custom theme:
- add HTML element with some specific ID (it will be used as target element once defined in step 2)
<p id="qty-error-message"><!--?= $block--->escapeHtml('Error message will appear here') ?></p>
- on
input#qty
element, add the following data attribute:<input id="qty" name="qty" type="number" ...="" data-errors-message-box="#qty-error-message">
Note that your selector as defined in
data-errors-messsage-box
must exist in your markup (this was done in step 1)
If you reload the page now, you should see the following:
And if you generate the error (qty = 0), the button remains on same place. 🙂
That’s it! Error message placeholder can be placed where ever you like, you are good to go as long as it is defined somewhere on the page. 🙂