I am trying to setup some error trapping on the discount code to output an error message if there are no products that qualify for the discount code the user enters. Here is the code I have;
{% set currentDiscount = craft.commerce.getDiscountByCode(cart.couponCode)%}
{% for item in cart.lineItems %}
{% set cartProductIds = item.purchasable.product.id %}
{% if currentDiscount %}
{% if not cartProductIds in currentDiscount.productIds %}You have no products in the cart that meet this discount{% endif %}
{% endif %}
{% endfor %}
Currently this doesn't give me anything back. Can anyone point me further in the right direction...?
Edit: I have since found the code I pasted as an answer no longer works or never fully worked. I am struggling to loop through an array and check against the other array and if no id's match then set an error. I want to check if any of the cart Id's match against any of the discount code id's.
Here is my revised code, but it just doesn't match fully. I don;t think it is a bug, but more likely a failing of my code. Can anyone shed any light?
{# THIS CHECKS THE DICOUNT CODE FOR IF THERE ARE ANY VALID/ELIGABLE PRODUCTS IN THE CART #}
{% set currentDiscount = craft.commerce.getDiscountByCode(cart.couponCode) %}
{% set codeError = null %}
{% if currentDiscount %}
{% set cartProductIds = [] %}
{% set discountProductsIds = [] %}
{% for item in cart.lineItems %}
{% set cartProductIds = cartProductIds|merge([item.purchasable.product.id]) %}
{% endfor %}
{% set cartProductIds = cartProductIds|join('|') %}
{% for product in currentDiscount.products %}
{% set discountProductsIds = discountProductsIds|merge([product.id]) %}
{% endfor %}
{% set discountProductsIds = discountProductsIds|join('|') %}
Products in Cart = {{cartProductIds}}
Products in Discount = {{discountProductsIds}}
{% if cartProductIds not in discountProductsIds %}
{% set codeError = 'Sorry there are no products in your cart that are eligiable for the code ' ~ cart.couponCode %}
{% endif %}
{% endif %}