1

This is what I have:

  • One select field with months
  • One select field with years

But in the month select field I would like to add an default option like:

<option value="current">Current</option> 

I have no idea how to add the default option, an placeholder is no option. This is my code right now, using a dateType

->add('startDate', DateType::class, [
    'label' => 'Start date',
    'label_attr' => array('class' => 'sr-only'),
    'placeholder' => [
        'year' => 'Year',
        'month' => 'Month',
    ],
    'years' => range(date('Y')-70, date('Y')),
])

Who can help me with this? Thanks!

Yester
  • 11
  • 2
  • Post the controller action you use that type with. In short: Just set the value in the entity (either in the constructor or in the controller action that generates this form). – ccKep Apr 16 '17 at 20:44
  • Might be just as easy to do this outside of symfony, like in jQuery. Just add a link next to the form that says "Current date", then onClick set the Year and Month select fields accordingly. – ehymel Apr 17 '17 at 00:05

2 Answers2

3

To set default value use , array('data' => new \DateTime())

->add('startDate', DateType::class, [
    'label' => 'Start date',
    'label_attr' => array('class' => 'sr-only'),
    'placeholder' => [
       'year' => 'Year',
       'month' => 'Month',
       ],
    'years' => range(date('Y')-70, date('Y')),
    'data' => new \DateTime(),
])
Grene
  • 434
  • 6
  • 18
0

range is used to generate an array, so the easiest way to do that, would be just add your value at the begining of the array.

Something like:

'years' => array_merge(['current'=>'current'], range(date('Y')-70, date('Y')))

Growiel
  • 775
  • 1
  • 7
  • 20
  • Thanks for your answer, unfortunately it wont work because I need to add the default option to my 'month' select. – Yester Apr 17 '17 at 07:57
  • By adding a range on the month ('months' => array_merge(['current'=>'current'], range(date('m'), 12)),) Warning: gmmktime() expects parameter 4 to be integer, string given – Yester Apr 17 '17 at 08:16
  • 1
    I think i misunderstood what you wanted then. Do you want to add an option with the 'current' (string) value and text ? Or do you want to have the current month `selected="selected"` by default ? – Growiel Apr 18 '17 at 03:45
  • I want to add an option 'current' value and text (string). Maybe I have to use the ChoiceType instead of the DateType? – Yester Apr 19 '17 at 05:08
  • Based on the error you had before with `gmmktime()`, that would be my guess too. `DateType` is running all the years in `gmmktime()` so that he can then run them through the `TimeFormatter` to match whatever `format` you choose. `ChoiceType` will accept anything, but also means that you have to ensure the validity of the data (that it's indeed a date) yourself. For me selecting the current year as default seems like a better option. – Growiel Apr 19 '17 at 06:53