Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a list of years since a specific year using Twig and Symfony2

Tags:

twig

symfony

With this application I'm building I want the user to be able to look at records from previous years. So if that user has records dating back to 2005, I want to be able to display a list of years since then including that year, for example:

List of years: 2012 | 2011 | 2010 | 2009 | 2008 | 2007 | 2006 | 2005

I've worked out the SQL to retrieve the oldest record from the database, which is as follows:

    // Retrieve Oldest Record
    $minimumyear = $dm->createQuery('
    SELECT min(msu.endDate) as msuMin
    FROM InstructorBundle:MapSubscriptions msu 
    LEFT JOIN InstructorBundle:MapContacts mc WHERE msu.contact = mc.id
    LEFT JOIN InstructorBundle:MapFamilies mf WHERE mc.family = mf.id
    WHERE mf.branch = :centre'
    )->setParameter('centre', $centreid);

    $minyear = $minimumyear->getResult();

The problem I have is that now I've got the oldest year, I'm not sure how I can use Twig to display the list I need. I have thought about extending Twig to allow this, but I don't want to go down that avenue for the time being just incase there is a function in Twig that would allow me to do this.

How can I display the list I need using Twig?

like image 500
mickburkejnr Avatar asked Sep 12 '13 09:09

mickburkejnr


1 Answers

Just use twig's date function to get the current year using "now" then loop from the minimum year to the current one with a for loop.

{% set minimumYear = 2010 %}

List of years: {{ minimumYear }}
{% for year in (minimumYear+1).."now"|date("Y") %}
    | {{ year }}
{% endfor %}

outputs:

List of years: 2010 | 2011 | 2012 | 2013

.. or to get the current year first

{% set minimumYear = 2010 %}
{% set currentYear = "now"|date("Y") %}   

List of years: {{ currentYear }}
{% for year in (currentYear-1)..minimumYear %}
   | {{ year }}
{% endfor %}

outputs:

List of years: 2013 | 2012 | 2011 | 2010

like image 166
Nicolai Fröhlich Avatar answered Oct 15 '22 02:10

Nicolai Fröhlich