Symfony表单日期类型字段datepicker无法正常工作

时间:2017-03-04 14:49:27

标签: php symfony date

在这样的表格中使用日期类型时

        $builder
            ->add('invoiceDate', DateType::class, [
                'translation_domain' => 'invoicing',
                'label' => 'invoice_date',
                'widget' => 'single_text',
                'format' => 'dd.MM.yy',
                'required' => true
            ]);

js:

$(document).ready(function () {

$('#economy_bundle_outbound_invoice_invoiceDate').datepicker({
    dateFormat: 'dd.mm.yy'
});

当我选择一些数据时,请使用正确的数据格式mm/dd/yyyy但是当检查表格有效时会出现错误invoiceDate: ERROR: This value is not valid.

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

我通常使用bootstrap-datepicker库来解决这个问题。

示例代码可以是:

//Controller
$form = $this->createFormBuilder()
    ->setMethod('POST')
    ->setAction($this->generateUrl('homepage'))
    ->add('invoiceDate', DateType::class, [
        'label'=>'invoice_date',
        'widget'=>'single_text',
        'required'=>true,
    ])
    ->getForm()
;
//...
return $this->render('default/index.html.twig', ['form'=>$form->createView()]);

// base.html.twig
{% block stylesheets %}
    <link rel="stylesheet" href="{{asset('bootstrap/dist/css/bootstrap.min.css')}}">
    <link rel="stylesheet" href="{{asset('bootstrap-datepicker/css/bootstrap-datepicker.min.css')}}">
{% endblock %}
//...
<body>
    //...
    {% block javascripts %}
        <script src="{{asset('jquery/dist/jquery.min.js')}}"></script>
        <script src="{{asset('bootstrap/dist/js/bootstrap.min.js')}}"></script>
        <script src="{{asset('bootstrap-datepicker/js/bootstrap-datepicker.min.js')}}"></script>
    {% endblock %}
</body>

// default/index.html.twig
{% extends 'base.html.twig' %}

{% block body %}
    {{form_start(form)}}
        {{form_row(form.invoiceDate, { attr:{ class:'js-datepicker' } })}}
    {{form_end(form)}}
{% endblock %}

{% block javascripts %}
    {{parent()}}
    <script>
        $('.js-datepicker').datepicker({
            format:'yyyy.MM.dd'
        });
    </script>
{% endblock %}