问题
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?
回答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 %}
回答2:
You can also use:
'choices' => range(Date('Y') - 4, date('Y'))
回答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));
}
回答4:
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 }}
回答5:
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.
回答6:
A simpler method to get, for example, a five year range of years, with a choice type :
'choices' => array(
Date('Y') => Date('Y'),
Date('Y') - 1 => Date('Y') - 1,
Date('Y') - 2 => Date('Y') - 2,
Date('Y') - 3 => Date('Y') - 3,
Date('Y') - 4 => Date('Y') - 4,
)
Note that is creates returns a string of the year selected.
回答7:
Check out this answer here: How to display a month-year dropdown in Symfony2
Just use a different date_widget block (twig).
回答8:
I have written my code this way and inserting in database is correct
->add('yearfield', 'datetime', array(
'widget' => 'single_text',
'format' => 'yyyy'
))
来源:https://stackoverflow.com/questions/8035077/symfony-2-date-input-with-only-year-selector