How to display a month-year dropdown in Symfony2

forms, symfony

Solution

Example for credit card expiration date:

$builder->add('expirationDate', 'date', array(
 'label' => 'Expiration date',
 'widget' => 'choice',
 'empty_value' => array('year' => 'Year', 'month' => 'Month', 'day' => 'Day'),
 'format' => 'dd-MM-yyyy',
 'input' => 'string',
 'data' => date('Y-m-d'),
 'years' => range(date('Y'), date('Y') + 10),
));

Then you must render this field manually.

Your form's twig template:

{{ form_row(form.expirationDate, {'date_pattern': '<span style="display: none;">{{ day }}</span> {{ month }} <span class="delim">&#47;</span> {{ year }}'}) }}

Overriding `date_pattern` will hide day select. You will get month / year format.

Problem

In my application, the user hsa to give a date by only selecting a month and a year in two dropdown lists. How can I achieve that? Here is what I've tried so far : In my Form : ``` $builder->add('date1', 'date', array( 'widget' => 'choice', 'empty_value' => '', 'format' => 'MMMM-yyyy', 'input' => 'datetime', 'years' => range(date('Y'), date('Y') - 30, -1) ) ``` which actually works and displays it exactly as I want but when validating the form, I get an error : ``` This value is not valid ``` A screenshot of the wanted result :

Original source