symfony 3.4 Type error: Argument 1 passed to … must be an instance of DateTime, null given,

前提是你 提交于 2019-12-11 18:17:22

问题


In the entity the date time is decalared:

 /**
 * @var \DateTime
 * @ORM\Column(name="task_date_start", type="datetime", nullable=true)
 */
 private $taskDateStart;

in the form

$builder->add('taskDateStart', DateType::class, [
    "widget" => "single_text",
    "html5" => false,
    "format" => "dd-MM-yyyy"  ,
    "attr" => ["class" => "js-datepicker"], 
    "required" => false                                                    
]);

i've this error when inserting null in to the field

Argument 1 passed to ... must be an instance of DateTime, null given


回答1:


The problem was solved by modifying the setter (new setter without prototype):

 function setTaskDateStart(\DateTime $taskDateStart = null ) {
     $this->taskDateStart = $taskDateStart;
 }

become

 function setTaskDateStart( $taskDateStart ) {
     $this->taskDateStart = $taskDateStart;
 }



回答2:


Better solution is to allow set the null and let the validation reports the error.

/**
 * @var \DateTime
 * @ORM\Column(name="task_date_start", type="datetime", nullable=false)
 * @Assert\NotBlank()
 */
 private $taskDateStart;

and

 function setTaskDateStart(?\DateTime $taskDateStart) {
     $this->taskDateStart = $taskDateStart;
 }


来源:https://stackoverflow.com/questions/48826086/symfony-3-4-type-error-argument-1-passed-to-must-be-an-instance-of-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!