我的实体:
/**
* @var \DateTime $publishedAt
*
* @ORM\Column(name="published_at", type="date")
*
* @Assert\Date()
*/
private $publishedAt;
/**
* Set publishedAt
*
* @param \DateTime $publishedAt
* @return MagazineIssue
*/
public function setPublishedAt(\DateTime $publishedAt)
{
$this->publishedAt = $publishedAt;
return $this;
}
/**
* Get published_at
*
* @return \DateTime
*/
public function getPublishedAt()
{
return $this->publishedAt;
}
我的表单构建器:
$builder->add('publishedAt');
我的观点:
{{ form_widget(form) }}
当我在选择中选择日期并提交表单时,我会收到错误:
Catchable Fatal Error: Argument 1 passed to ... must be an instance of DateTime,
string given, called in .../vendor/symfony/symfony/src/Symfony/Component/Form
/Util/PropertyPath.php on line 537 and defined in ... line 214
为什么会这样?如果我用public function setPublishedAt($publishedAt)
替换字段设置器,我收到错误:
Fatal error: Call to a member function format() on a non-object
in .../vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateType.php on line 44
如果我将表单构建器更改为
$builder->add('publishedAt','date')
一切正常。为什么会这样?为什么symfony无法猜测并传递给字段设置器正确的日期格式(\ DateTime而不是字符串)?
编辑:如果我删除@Assert\Date()
,那么一切正常。我认为猜测日期字段类型
答案 0 :(得分:1)
我曾经像 Max 那样处理这个问题,但之后我发现了 Data transformers 。这是非常有效的方式,并不意味着修改模型(或它的getter / setter方法)......
编辑:查看标题“在自定义字段类型中使用变形金刚”。他们写了DateTime
那里......
答案 1 :(得分:0)
Doctrine想要调用\ DateTime :: format()。从一个字符串。
您可以在setter方法中检查参数:
public function setPublishedAt($publishedAt)
{
if($publishedAt instanceof \DateTime) {
$this->publishedAt = $publishedAt;
} else {
$date = new \DateTime($publishedAt);
$this->publishedAt = $date;
}
}
答案 2 :(得分:0)
要解决此问题,您可以
1.将断言从@Assert\Date()
更改为@Assert\Type('\DateTime')
OR
2.将表单构建器更改为$builder->add('publishedAt','date')
OR
3.在表单构建器中指定input
选项:$builder->add('publishedAt',null,array('input' => 'datetime'))