1

So I'm trying to get all entries that have a particular year assigned to a custom date field. (Could be any day/month in that year).

The custom field is startDate and my attempt at a query - which doesn't work - is below...

PS. year is a 4 digit variable set via the last segment of the url and pulled into the template as a variable, and giving you 2018, 2019 or whatever...

{% set query = {
  section: 'programme',
  isOngoing: 0
} %}
{% set programmeEntries = craft.entries(query).search('startDate:' ~ year|date('Y-m-d')) %}

PS. I think it's more like this but I can't get the syntax right...

{% set query = {
  section: 'programme',
  isOngoing: 0,
  startDate: ( ['and', '>=' ~ (year~'-01-01')|date('Y')|atom, '<=' ~ (year~'-01-01')|date('Y')|date_modify('+12 months')|atom])
} %}
2

I think your problem is you're converting the date to a year string then converting that to an atom value. Just convert the date straight to an atom value:

{% set yearStart = "#{year}-01-01"|atom %}
{% set yearEnd = "#{year}-12-31"|atom %}

{% set entries = craft.entries({
    section: "programme",
    isOngoing: 0,
    startDate: ["and", ">= #{yearStart}", "< #{yearEnd}"]
}).all %}
  • Thanks! I think the year vars aren't quite right though, getting this error: DateTime::__construct(): Failed to parse time string (#{year}-01-01) at position 0 (#): Unexpected character – James Greig Sep 11 at 8:21
  • I don't usually use escaped variables, I was just mimicking the docs. Anyway glad you got it working. – kmgdev Sep 11 at 16:23
  • Oh apparently interpolated variables only work inside double quotes. Updated the answer to match. – kmgdev Sep 11 at 22:21
2

EDIT: kmgdev's solution is now updated and marked correct! :)

Fixed by slightly modifying kmgdev's solution slightly so that the year variables were interpolated correctly:

{% set yearStart = (year ~ '-01-01')|atom %}
{% set yearEnd = (year ~ '-12-31')|atom %}

{% set query = {
  section: 'programme',
  isOngoing: 0,
  startDate: ( ['and', '>=' ~ yearStart, '<=' ~ yearEnd])
} %}

{% set programmeEntries = craft.entries(query).all() %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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