1

So on a cart page, I need to list out the discounts that have been applied to a cart. I need to list them one by one, but only discounts that are applied with a code. I'm having trouble figuring out how to get the discount code, and I need to output the code. Something like this:

Item Total: $200.00
Promotional (25OFF): -$25.00
Promotional (FATHERSDAY): -$10.00
...

I'm looking over the discount info like this:

{% for discount in cart.adjustments %}
    {{ dump(discount) }}
    <br>
{% endfor %}

I don't see an accessible code variable jumping out at me. The only places I can see pulling it is from the optionsJson string, but that is not practical as Twig doesn't have a default JSON filter to decode.

So I can get the discount ID easily enough from that loop; but I'm not sure how to pull a Discount model based on ID. I'm not super versed with Craft and Twig, so I'm hoping there is a simple solution to look up Discounts based on discount ID.

So like this:

{% for discounts in cart.adjustments %}
    {# look up discount based on discount.id #}
        {% if discount.code | length %}
            Promotional ({{ discount.code }}): {# discount amount, probably have to do math here if it is a percentage #}
        {% endif %}
    {% endfor %}
{% endfor %}

I imagine I'm going about this wrong.

1 Answer 1

2

(There can be only one code on a cart at any one time)

Here's some example code that does the sort of thing you want:

{% if cart.couponCode %}
    {% set coupon = craft.commerce.getDiscountByCode(cart.couponCode) %}
{% endif %}

{% if cart.totalDiscount or coupon is not null %}

    {% for adjustment in cart.adjustments if adjustment.type == "Discount" %}
        {% set isCoupon = adjustment.optionsJson.code ? true : false %}                

    <strong>Applied: </strong>

        {% if isCoupon %}                
            <div class="coupon-item">
                <div class="clear">
                    <div class="cartSection__text">

                        Coupon: <strong>{{ adjustment.optionsJson.code }}</strong>
                    </div>
                </div>

                <div class="cartSection__description">
                    {{ adjustment.description }}
                </div>
            </div>
            {% set couponPrinted = true %}
        {% else % }
            etc...
1
  • Goddamnit, I thought I tried that. I think I was just accessing the optionsJson code array node on the wrong parent. Thank you! Worked exactly as needed.
    – jrothafer
    Commented Jul 30, 2017 at 1:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.