Back-end validation of product variant I'm creating a product page for a product with multiple variants. In this case the variant represents a different size (with unique SKU, stock, etc..).

It's laid out like so (don't mind the ugly styling):



I don't want to pre-select a size option because I want to avoid people adding the wrong product to their cart. 

In the template there's a hidden field with the purchasableId of the variant. The value attribute starts empty and when people click one of the options it is set to the corresponding id.

&lt;input type="hidden" name="purchasableId" value=""&gt;


However, when people click 'Add to cart' right away, without selecting a size the following Craft\Exception is shown:

Not a purchasable ID


How can I customize this error message to notify the customer that they have to select a size option?

I could of course solve this problem by using javascript but that doesn't seem very solid to me. So is there a way of validating the stuff added to the cart in the back-end and getting something like a JSON response?
Well, if you submit to your add to cart form via ajax, you will already get a json response - with an error - you can simply grab that error, test for Not a purchasable ID and then change the text to whatever you want.

If you're submitting in a non ajax fashion, you won't get a JSON response no matter what clearly.

I agree with the comment above - I'd generally handle this in front end JS, by disabling the add to cart until a size is selected.  And I guess if you're allowing your site to use no-js, then in that case I would probably just pre-select the most popular option (Medium, presumably).

You can also write a plugin that listens to https://craftcommerce.com/docs/events-reference#commerce_cart.onbeforeaddtocart and does whatever validation you need, and returns a response any way you want, including via JSON (i.e. $this-&gt;returnJson(["success"=&gt;true]); or e.g. $this-&gt;returnErrorJson($errors); where $errors holds your validation errors...)