Symfony3错误使用Ajax更改实体上的DateTime

时间:2016-06-22 12:11:43

标签: ajax doctrine-orm symfony

我想更改学说实体的日期,但不保存更改。

用ajax调用这个函数:

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));
}

当我提醒结果时,我得到了正确的新值,但重新加载后没有保存更改。

在相同条件下调用此函数有效:

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));
}

1 个答案:

答案 0 :(得分:2)

请参阅docs

  

调用EntityManager#flush()时,Doctrine计算更改集   所有当前管理的实体并将差异保存到   数据库。如果是对象属性(@Column(type =“datetime”)或   @Column(type =“object”))这些比较总是由BY组成   参考。这意味着以下更改将不会保存到   数据库:

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

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

所以,在你的情况下,我建议克隆dateButoire,就像这样

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