@Oleg 非常接近正确答案。您必须使用视图转换器来确保 DateTime 得到一天。
/* In your formType.php */
$builder->add(
$builder->create('date1', 'date', array(
'format' => 'MMMM-yyyyd', // you need to have 'y', 'M' and 'd' here
'years' => range(date('Y'), date('Y') - 30, -1)
))
->addViewTransformer(new IncompleteDateTransformer()));
)
创建一个转换器:
class IncompleteDateTransformer implements DataTransformerInterface
{
/**
* Do nothing when transforming from norm -> view
*/
public function transform($object)
{
return $object;
}
/**
* If some components of the date is missing we'll add those.
* This reverse transform will work when month and/or day is missing
*
*/
public function reverseTransform($date)
{
if (!is_array($date)) {
return $date;
}
if (empty($date['year'])) {
return $date;
}
if (empty($date['day'])) {
$date['day']=1;
}
if (empty($date['month'])) {
$date['month']=1;
}
return $date;
}
}
创建一个树枝模板,您可以在其中使用来自文件本身的自定义表单主题:
{# example.html.twig #}
{% form_theme form _self %}
{% block date_widget %}
{% spaceless %}
{% if widget == 'single_text' %}
{{ block('field_widget') }}
{% else %}
<div {{ block('widget_container_attributes') }}>
<div class="datetime_widget">
{{ date_pattern|replace({
'{{ year }}': form_widget(form.year),
'{{ month }}': form_widget(form.month),
'{{ day }}': '',
})|raw }}
</div>
</div>
{% endif %}
{% endspaceless %}
{% endblock date_widget %}
<h2>Select a date</h2>
{{ form(form) }}
参考: