I have a model where one field is a date. I want to display elements from that model, grouped by year and by month, like this:
== 2013 ==
=== April ===
* Element 1
* Element 2
=== March ===
* Element 3
...
== 2012 ==
...
What if the best way to achieve that? Should I build a nested array directly in the Controler? Or is there a way to display the year and month headers only using Fluid template? Or should I write a custom ViewHelper to extract and display the year and month headers?
First you need to iterate your resultset in the controller, save it into array, and make sure that every row has extracted date to separate indexes for
year
andmonth
.In such case you'll be able to use
<f:groupedFor ...>
view helper.Other option is adding these fields (
year
andmonth
) to your model and setting proper values while saving/updating the object. Using this approach you'll avoid the need of the controller's iteration mentioned above, buuuutttt... if you are going to access these records with common TYPO3's backend, you will need to use some postprocess hooks to set these fields after database operations.Finally, I solved this problem by using a custom ViewHelper, derived from GroupedBy ViewHelper, inspired from https://gist.github.com/daKmoR/1287203, and adapted for extbase.
Here is the complete code for the ViewHelper, located in MyExt/Classes/ViewHelpers/GropuedForDateTimeViewHelper.php
And here is an example of a template using it: