In Twig, I want to find out if a discount is valid based on start/end date. startDate and endDate don't seem to exist and I can't inspect the discount object by using the json_encode filter (returns {}).

How can we do this?

This is the code used to grab the discount object:

{% set discount = null %}
{% for d in craft.commerce.discounts %}
    {% if d.id == 1 %}{% set discount = d %}{% endif %}
{% endfor %}

name, description and enabled variables are available but no startDate/endDate.

  • Can you share the code you're using to retrieve the discount model? – Brad Bell Aug 30 at 0:16
  • Sure it's in the description now. – biko Aug 30 at 5:21
  • @BradBell I forgot to mention you in my last comment but the code is now in the description. Thanks in advance. – biko Aug 31 at 4:47
up vote 1 down vote accepted

In Commerce 1, craft.commerce.discounts will return an array of Commerce_DiscountModel objects of all available discounts.

public function getAllDiscounts($criteria = [])
{
    $records = Commerce_DiscountRecord::model()->findAll($criteria);

    return Commerce_DiscountModel::populateModels($records);
}

Commerce_DiscountModel objects have a dateFrom and a dateTo property, which is probably what you're looking for.

Completely untested, but something like this:

{% set discount = null %}
{% for d in craft.commerce.discounts %}
    {% if d.id == 1 %}
        {% set discount = d %}
        {% if discount.dateTo > '2018-01-01 00:00:00' and discount.dateFrom < '2018-12-31 23:59:59' %}
            Matches!
        {% endif %}
    {% endif %}
{% endfor %}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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