Symfony 2 date input with only year selector
Solution 1
You can use form customization:
{% block date_widget %}
{% spaceless %}
{% if widget == 'single_text' %}
{{ block('field_widget') }}
{% else %}
<div {{ block('widget_container_attributes') }}>
{{ date_pattern|replace({
'{{ year }}': form_widget(form.year),
'{{ month }}': '',
'{{ day }}': '',
})|raw }}
</div>
{% endif %}
{% endspaceless %}
{% endblock date_widget %}
Solution 2
You can also use:
'choices' => range(Date('Y') - 4, date('Y'))
Solution 3
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));
}
Solution 4
You can override 'date_pattern':
{{ form_row(form.fieldName, {'date_pattern': '<span style="display: none;">{{ day }}{{ month }}</span>{{ year }}'}) }}
NOTE! Hide fields with display: none
, Do not remove them to pass validation.
Solution 5
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 }}
szilagyif
Currently I am a JAVA developer at Pillar Mérnökiroda (Budapest, Hungary). In my free time I make iOS apps with Swift and play guitar. From January 2016 I started to learn English again with a native teacher to improve my skills.
Updated on June 16, 2022Comments
-
szilagyif about 2 years
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?
-
Acyra over 12 yearsThis is a bit of a hack that solves the problem but doesn't answer the question-- how do you do this with the FormBuilder?
-
Sam almost 12 yearsI want to do exactly the same thing. Could you please explain me how you do please?, I have this error:
Twig_Error_Runtime: Variable "date_widget" does not exist
-
mario almost 9 yearsYou saved my day! Thanks. (Why does it fix it?) ps. Best answer is here