0

For example have the following code:

<form action="">
       <select>
               <option>2015</option>
               <option>2014</option>
               <option>2013</option>
               <option>2012</option>
      </select>

      <input type="submit" value="select">
</form>

how to get a entries of the selected year?

2

First thing I recommend is to read through the Search Form guide from the Craft documentation. To explain the rest I'll add some comments to the example code.

form.html

{# Use the `group` filter to get the years, entries were posted in #}
{% set entries = craft.entries.section('news') %}
{% set entriesByYear = entries|group('postDate|date("Y")') %}

<select name="year">

    {# Go through the `year` groups #}
    {% for year, entries in entriesByYear %}
        <option value="{{ year }}">{{ year }}</option>
    {% endfor %}

</select>

results.html

{# Get the params #}
{% set year = craft.request.getParam('year') %}

{# Compose a param in this format: 'and, >= 2014-01-01, < 2015-01-01' #}
{% set dateParam = 'and, >= ' ~ year ~ '-01-01, < ' ~ (year + 1) ~ '-01-01' %}

{# Query and loop through the entries #}
{% set entries = craft.entries.section('news').postDate(dateParam) %}

{% if entries|length %}
    ...
{% endif %}
4
  • Ok, How does this make Ajax, as in the admin panel) – Vitaliy Badalov Mar 3 '15 at 10:15
  • First make everything work as you expect it to and then implement the JS. How to do that exactly would be another question, but basically you need to prevent the full page reload (event.preventDefault() method) and then load in the newly filtered content. There's other great answers on Ajax topics here on Craft SE (→ i.e. these ones here). – carlcs Mar 3 '15 at 10:24
  • As instead of 'postDate | date ("Y")' substitute custom fields? – Vitaliy Badalov Mar 12 '15 at 11:25
  • This should actually work the same for any custom Date/Time fields, just replace the field handle like so 'myCustomDateField|date("Y")'. – carlcs Mar 12 '15 at 12:18

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.