使用Symfony 3 Forms插入DateType字段时出现问题


Issue when inserting DateType Field with Symfony 3 Forms

我搜索了很多,但在StackOverflow中找不到关于我的问题的任何信息。。。

我有这样的结构:(续)

$form = $this->createFormBuilder($vendedor)
            // ...
            ->add('datanascimento', DateType::class, [
                'label' =>'D.Nascimento',
                'attr'  =>['class'=>'input-sm'],
                'format'=>'d-M-yyyy',
                'years'=>range(1970, 2010)
            ])
            // ...
            ->getForm();

我在我的实体中有这样的配置:

//...
/**
     * @var 'DateTime
     *
     * @ORM'Column(name="dataNascimento", type="date", nullable=true)
     */
    private $datanascimento;
//...
/**
     * Set datanascimento
     *
     * @param string $datanascimento
     *
     * @return CadPfPj
     */
    public function setDatanascimento($datanascimento)
    {
        $this->datanascimento = $datanascimento;
        return $this;
    }
    /**
     * Get datanascimento
     *
     * @return string
     */
    public function getDatanascimento()
    {
        return $this->datanascimento;
    }

当我尝试插入一个新的寄存器时,我得到了这个错误:

Catchable Fatal Error: Object of class DateTime could not be converted to string
500 Internal Server Error - ContextErrorException

当我调试并转储对象时。。。我发现了这个:

//...
-datanascimento: DateTime {#530 ▼
    +"date": "1970-01-01 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "America/Sao_Paulo"
  }
//...

我的数据库是mySQL,字段类型是datetime。。。如何配置symfony以停止发送数组并只发送"日期"?

谢谢你的帮助!

您需要更改表单条目的widget类型–默认为choice,但您需要textsingle_text

        ->add('datanascimento', DateType::class, [
            'label'  =>'D.Nascimento',
            'widget' =>'single_text',         
            'attr'   =>['class'=>'input-sm'],
            'format' =>'d-M-yyyy',
            'years'  =>range(1970, 2010)
        ])