'Inserting the current date doctrine

I have created a symfony project and am having a date issue. I would like to make a request which inserts the current date in the database. In my entity my fields are date time.

Here is the repository, the controller and the error obtained.

Repository :

 /**
 * @ORM\Column(type="datetime", nullable=true)
 */
private $date_maj;

Controller :

 $qb = $this->getDoctrine()
        ->getManager()
        ->createQueryBuilder()
        ->update(Tache::class, 't')
        ->set('t.date_maj', date(('Y-m-d H:i:s'), time()))
        ->where('t.id = :id')
        ->setParameter('id', $id)
        ->getQuery()
        ->execute();

Error :

[Syntax Error] line 0, col 87: Error: Expected end of string, got '06'



Solution 1:[1]

You want to set a parameter with a PHP \DateTime as the value, similar to :id in the where clause. The query builder will handle the conversion to the database string value:

$now = new \DateTime();
$qb = $this->getDoctrine()
    ->getManager()
    ->createQueryBuilder()
    ->update(Tache::class, 't')
    ->set('t.date_maj', ':now')
    ->where('t.id = :id')
    ->setParameter('now', $now)
    ->setParameter('id', $id)
    ->getQuery()
    ->execute();

Solution 2:[2]

You should use your entity with persist and flush instead using queryBuilder. Your entity looks like thhis :

 /**
 * @ORM\Column(type="datetime", nullable=true)
 * @var DateTime|null
 */
private $date_maj;

public function getDateMaj(): ?DateTime
{
    return $this->date_maj;
}

public function setDateMaj(?DateTime $dateMaj): self
{
    $this->date_maj = $dateMaj;
}

And controller-side :

// it's for example, using injection dependency is better 
$em = $this->getDoctrine()->getManager();

// Get your entity (if it's from Form, this line is useless, retrieve entity from $form->getData())
$tache = $em->getRepository(Tache::class)->find($id);

$now = new \DateTime();
$tache->setDateMaj($now);

$em->persist($tache);
$em->flush();

If it's ok, you can edit typo DateTime to DateTimeInterface too

Solution 3:[3]

You can put it in your construct using new \DateTime()

public function __construct()
    {
        $this->date_maj=new \DateTime();
      
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arleigh Hix
Solution 2 Hamham
Solution 3 L3xpert