3

I am trying to query entries (scripts) when a custom expiration date field is within a certain range.

These questions/answers helped me get as far as I am, but I'm still stuck: Advanced query/filter based on date and values and How can you return elements between two values?

Here's the full scenario. On this app's homepage, it lists a handful of recent scripts (prescriptions). It also has sections where it displays scripts that are expired and scripts that are about to expire (within two weeks of the current date).

I did some testing and found that the following conditionals filter the scripts just how I want:

{# When expiration date is between now and 2 weeks #}
{% if expirationDate >= now and expDate <= now|date_modify('+2 weeks') %}

{# When expiration date is anytime before now #}
{% if expirationDate < now %}

Those work great. How can I move this filter into the query itself?

I was thinking something like the following, but it obviously doesn't work because of all the commas. But this is what I'm trying to do. How do I use this correctly in a hash?

{% set scriptsAboutToExpire = {
    section: 'scripts',
    order: 'expirationDate asc',
    expirationDate: 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks')
} %}
Steven Thate
  • 687
  • 4
  • 20

1 Answers1

6

I got the answer to this thanks to @BrandonKelly from a comment in this question: How can you return elements between two values?

Turning it into a subarray does the trick: expirationDate: [ 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks') ]

Thanks, @BrandonKelly!

Steven Thate
  • 687
  • 4
  • 20
  • 2
    This is no longer accurate in Craft v3. The dates in the query need to be explicitly formatted as strings. For example expirationDate: [ 'and', '>=' ~ now|date('U'), '<=' ~ now|date_modify('+2 weeks')|date('U') ] See https://craftcms.stackexchange.com/a/25826 – Jameal G Nov 18 '20 at 16:15