Symfony2.1 表单日期字段:传递给...的参数 1 必须是 DateTime 的实例 [英] Symfony2.1 form date field: Argument 1 passed to ... must be an instance of DateTime

查看:40
本文介绍了Symfony2.1 表单日期字段:传递给...的参数 1 必须是 DateTime 的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体:

/**
 * @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) }}

当我在选择中选择日期并提交表单时,我发现错误:

When I select the date in the selects and submit the form I catche the error:

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) 替换字段设置器,我会收到错误:

Why it happens? If I replace the field setter with public function setPublishedAt($publishedAt) I got the error:

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 

如果我将表单生成器更改为

If I change the form builder to

 $builder->add('publishedAt','date')

一切正常.为什么会发生?为什么 symfony 无法猜测并传递给字段设置器正确的日期格式(\DateTime 而不是字符串)?

all works fine. Why it happens? Why symfony can't guess it and pass to field setter the proper date format (\DateTime instead of string)?

如果我删除 @Assert\Date() 然后一切正常.我认为这是猜测日期字段类型的 sf2.1 错误

if I remove the @Assert\Date() then all works fine too. I think it's a sf2.1 bug with guessing the date field type

推荐答案

解决这个问题你可以

1.将断言从@Assert\Date()改为@Assert\Type('\DateTime')

2.将表单生成器更改为$builder->add('publishedAt','date')

2.change the form builder to $builder->add('publishedAt','date')

3.在表单构建器中指定input选项:$builder->add('publishedAt',null,array('input' => 'datetime'))

3.specify the input option in the form builder: $builder->add('publishedAt',null,array('input' => 'datetime'))

这篇关于Symfony2.1 表单日期字段:传递给...的参数 1 必须是 DateTime 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆