2014-09-05 190 views
0

我想通过ajax调用控制器来将实体更新到db中。但是,我只知道如何使用Symfony的形式更新实体。目前我有一个表单将被jQuery方法附加并通过ajax提交,但是我在控制器中做了什么。Symfony2,Doctrine2,更新实体

阿贾克斯:

$("#editctrno").on("submit", function(event) { 
    event.preventDefault(); 

    $.ajax({ 
     url: "{{ path('containers_edit') }}", 
     type: "POST", 
     data: {'ctrno' : $("#ctrno").val(), 
       'refno' : $("#refno").val()}, 
     dataType: "json", 
     success: function(data) { 
      console.log(data[0].ctrno); 
     } 
    }); 
}); 

现在我控制器上:

/** 
* @Route("/edit/", name="containers_edit", defaults={"_format" = "json"}) 
*/ 
public function editCtr(Request $request) { 
    $ctrno = $request->get('ctrno'); 
    $refno = $request->get('refno'); 

    $em = $this->getDoctrine()->getManager()->getRepository('Bundle:Ref'); 

    // I want to access in the database to find the 'refno' and update the 'ctrno', 
    // something like: 
    // $entity = $em->findRefno($refno); 
    // $entity->setCtrno($ctrno); 
    // $em->flush(); 

    return new Response(json_encode($entity)); 
} 

这有什么建议?

+0

喜欢有正常形式,只是不要忘记在jQuery中序列化数据。 – 2014-09-05 17:53:56

+1

看看这里 - http://codemonkeys.be/2013/01/ajaxify-your-symfony2-forms-with-jquery/ – dmnptr 2014-09-05 17:59:02

+0

什么不工作? – Toskan 2014-09-05 18:05:39

回答

0

查看评论中的链接dmnptr它拥有您需要的一切。

只是有一点增加,在你的代码,你需要将方法名从

editCtr()更改为editCtrAction()

在控制器类中的所有方法都是“动作”。希望这可以帮助。

相关问题