Valentin BEAULE Valentin BEAULE - 5 months ago 26
Ajax Question

Symfony3 error changing DateTime on entity with Ajax

I want to change the date of a doctrine entity but the change is not saved.



With ajax a call this function:

public function relancerTicketAction(Request $request, $id)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));

$isAjax = $request->isXMLHttpRequest();

if ($isAjax)
{
$ticket = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Ticket')->find($id);
$ticket->setDateButoire($ticket->getDateButoire()->modify('+7 day'));
$this->getDoctrine()->getManager()->flush();

$response = array("code" => 100, "success" => true, 'date' => $ticket->getDateButoire()->format('d-m-Y'));
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}


When I alert the result I get the right new value, but after reload there is no change saved.

This function called in the same conditions works:

public function traiterTicketAction(Request $request, $id)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));

$isAjax = $request->isXMLHttpRequest();

if ($isAjax)
{
$compte = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Compte')->find($this->get('session')->get('compte')->getId());

$ticket = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Ticket')->find($id);
$ticket->addDestinataire($compte);
$this->getDoctrine()->getManager()->flush();

$response = array("code" => 100, "success" => true);
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}

Answer

see the docs

When calling EntityManager#flush() Doctrine computes the changesets of all the currently managed entities and saves the differences to the database. In case of object properties (@Column(type=”datetime”) or @Column(type=”object”)) these comparisons are always made BY REFERENCE. That means the following change will NOT be saved into the database:

/** @Entity */
class Article
{
    /** @Column(type="datetime") */
    private $updated;

    public function setUpdated()
    {
        // will NOT be saved in the database
        $this->updated->modify("now");
    }
}

So, in your case I suggest to clone dateButoire, like this

$ticket = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Ticket')->find($id);
$newDateButoire = clone $ticket->getDateButoire();
$ticket->setDateButoire($newDateButoire->modify('+7 day'));
$this->getDoctrine()->getManager()->flush();
Comments