问题
My Entity:
/**
* @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;
}
My form builder:
$builder->add('publishedAt');
My view:
{{ 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
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')
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)?
EDIT: 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:
I used to deal with this just like Max wrote but then I discovered Data transformers. It's very efficient way and does not imply modifications to model (or it's getter/setter methods)...
EDIT: Check out the title "Using Transformers in a custom field type". They write about DateTime
there...
回答2:
Doctrine want to call \DateTime::format(). From a string.
You can check the argument in the setter method:
public function setPublishedAt($publishedAt)
{
if($publishedAt instanceof \DateTime) {
$this->publishedAt = $publishedAt;
} else {
$date = new \DateTime($publishedAt);
$this->publishedAt = $date;
}
}
回答3:
To solve this problem you can
1.change the assert from @Assert\Date()
to @Assert\Type('\DateTime')
OR
2.change the form builder to $builder->add('publishedAt','date')
OR
3.specify the input
option in the form builder: $builder->add('publishedAt',null,array('input' => 'datetime'))
来源:https://stackoverflow.com/questions/12970681/symfony2-1-form-date-field-argument-1-passed-to-must-be-an-instance-of-date