Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: How to render date field without a day?

I'm trying to build form with date field, where user can pick a month and year only (without day of month), but i can't figure out how to achieve this.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add(
        'month',
        'date',
        array(
            'label' => 'Month & year',
            'input' => 'array',
            'widget' => 'choice',
        ));

    $builder->add('submit',
                  'submit');
}

Ideal result is two dropdown lists: list of months (number representation) and list of years (4 digit, 5 last years).

I think i can use 2 choice type fields but maybe there is a more elegant solution?

like image 340
Andrey Kryukov Avatar asked Jan 12 '23 15:01

Andrey Kryukov


1 Answers

You can do something like this in your twig file.

    {{ form_widget(yourForm.month.month) }}
    {{ form_widget(yourForm.month.year) }}

This will display two choice fields, one for month and one for year. I suggest change field name from month to something else. I'm not sure but it may conflict. I hope this helps..!

EDIT: To show the last 5 years, in your Form builder,

   $builder->add(
     'month',
     'date',
     array(
        'years' => range(date('Y'), date('Y')-5)
        'label' => 'Month & year',
        'input' => 'array',
        'widget' => 'choice',
     ));
like image 109
Tejas Gosai Avatar answered Jan 16 '23 23:01

Tejas Gosai