0

I have this YAML definition entity:

Entity\Visit: type: entity table: visit fields: date: type: date id: true count: type: integer nullable: true options: unsigned: true default: 1 lifecycleCallbacks: { } 

And the date field is created:

/** * @var \DateTime * * @ORM\Column(name="date", type="date") * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $date; 

If I try insert a new record in this way:

$date = new \DateTime('now'); $visit = new \Entity\Visit(); $visit->setDate($date); $visit->setCount(1); $em->persist($visit); $em->flush(); 

I have this error:

ContextErrorException in UnitOfWork.php line 1413: Catchable Fatal Error: Object of class DateTime could not be converted to string

And I do it in this way:

$date = new \DateTime('now'); $date = $date->format('Y-m-d'); 

This error is shown:

FatalThrowableError in DateType.php line 53: Call to a member function format() on string

Can anybody help me in order to insert (or update) a 'date' field using Doctrine2? Thanks.

UPDATE: The field in database have to be a 'date' field.

4
  • You have used @ORM\Column(name="date", type="date") and you are saving \DateTime object. So first change type=datetime. Commented Aug 23, 2016 at 17:16
  • @jigar-pancholi But I need that field is 'date' type. Commented Aug 23, 2016 at 17:26
  • docs.doctrine-project.org/projects/doctrine-orm/en/latest/… You chould convert from DateTime to string on prePersist for insert/update. Commented Aug 23, 2016 at 17:47
  • @ka_lin: Thanks, but if I do $this->date = $this->date->format("Y-m-d"); on prePersist event, this error is shown FatalThrowableError in DateType.php line 53: Call to a member function format() on string. Can you help me more? Commented Aug 25, 2016 at 16:22

2 Answers 2

1

Finally, I have found the problem by myself: The problem is because of the primary key is a date column. It seems that Doctrine does not like those stuff.

My new YML file:

Entity\Visit: type: entity table: visit fields: id: type: integer id: true generator: strategy: AUTO options: unsigned: true date: type: date unique: true count: type: integer nullable: true options: unsigned: true default: 1 lifecycleCallbacks: { } 

Now, I can do this:

$date = new \DateTime('now'); $visit = new \Entity\Visit(); $visit->setDate($date); $visit->setCount(1); $em->persist($visit); $em->flush(); 
Sign up to request clarification or add additional context in comments.

Comments

0

Please try with below code:

$date = new \DateTime(); $visit = new \Entity\Visit(); $visit->setDate($date->format('Y-m-d')); $visit->setCount(1); $em->persist($visit); $em->flush(); 

1 Comment

Thanks, but as I wrote in the queestion, if I do that then this error is shown: FatalThrowableError in DateType.php line 53: Call to a member function format() on string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.