问题
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