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?
You can also use:
'choices' => range(Date('Y') - 4, date('Y'))
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));
}
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With