1

I'm looking to create a select (dropdown) form field that includes the days and dates for the next 14 days, starting from today, as options.

My initial thoughts on how to construct this would be to set today {% set today = now|date("l dS F Y") %} and then set a date 13 days from now {% set finalDate = now|date_modify("+13 day")|date("l dS F Y") %} and then somehow put that into a range loop. It is the last part I'm having trouble getting working, if it is at all possible.

Once I have that range I would ultimately like to pass it as option values to the select macro mentioned in another question like so:

{{ forms.select({
    options: ['Today', 'Tomorrow', ...]
}) }}

Thanks

5

You're close! If there's one thing I've learned about Twig, it's easy to overthink it...

Create an array with the first date, then merge the rest of dates into the same array with a for loop. Just increment the day in the range:

 {% set rangeOfDates = [ now|date("l dS F Y") ] %}

 {% for i in range (1,13) %}

     {% set rangeOfDates = rangeOfDates|merge( [ now|date_modify("+" ~ i ~ " day")|date("l dS F Y") ]) %}

{%endfor%}

Then in your forms macro:

{{ forms.select({
    options: rangeOfDates
}) }}
| improve this answer | |
  • So simple, twig rocks. One problem with the above code is that the variable dates in the for loop doesn't exist, it needs to be rangeOfDates. If you update you answer with {% set rangeOfDates = rangeOfDates|merge( [ now|date_modify("+" ~ i ~ " day")|date("l dS F Y") ]) %} I will mark it as correct. – since1976 Jun 24 '15 at 21:21
  • Oops thank you, fixed! In the spirit of clarify I had changed the variable name at the last minute but of course forgot to change it in that critical spot! – RitterKnight Jun 25 '15 at 20:16

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.