Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 date input with only year selector

Is it possible to make a date input field, with only year selector widget in Symfony 2 FormBuilder, or should I use a simple text type input field?

like image 799
szilagyif Avatar asked Nov 07 '11 10:11

szilagyif


3 Answers

You can also use:

'choices' => range(Date('Y') - 4, date('Y'))
like image 139
jeroen Avatar answered Oct 11 '22 20:10

jeroen


It's better to use the choice field type, rather than hacking the date field type or just using text field type.

Using few basic php date/time functions, you will get what you need.

In FormType:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('yearfield', 'choice',
                    array(
                        'required' => true, 'choices' => $this->buildYearChoices()
                    ));
}

public function buildYearChoices() {
    $distance = 5;
    $yearsBefore = date('Y', mktime(0, 0, 0, date("m"), date("d"), date("Y") - $distance));
    $yearsAfter = date('Y', mktime(0, 0, 0, date("m"), date("d"), date("Y") + $distance));
    return array_combine(range($yearsBefore, $yearsAfter), range($yearsBefore, $yearsAfter));
}
like image 21
ihsan Avatar answered Oct 11 '22 21:10

ihsan


This approach was giving me errors with validation:

{{ date_pattern|replace({
    '{{ year }}':  form_widget(form.year),
    '{{ month }}': '',
    '{{ day }}': '',
})|raw }}

I finallay solved the problem by adding css attributes to hide the fields:

{{ date_pattern|replace({
    '{{ year }}': form_widget(form.year),
    '{{ month }}': form_widget(form.month, { 'attr' : { 'style': 'display:none' }}), 
    '{{ day }}':  form_widget(form.day, { 'attr' : { 'style': 'display:none' }}),
})|raw }}
like image 1
Shawn Northrop Avatar answered Oct 11 '22 21:10

Shawn Northrop