0

我正在尝试使用 Symfony2 在 AJAX 中插入/更新记录。我正在使用 JQuery 提交我的表单。这是我的控制器:

public function myEntitysAction(){

    $em = $this->getDoctrine()->getEntityManager();
    $request = $this->getRequest(); 
    $AJAXresponse = array();

    $myEntity = new myEntity();       
    $form = $this->createForm(new myEntityType(), $myEntity);

    if ($request->getMethod() == 'POST') {

        $form->bindRequest($this->getRequest());

        if ($form->isValid()) {
            $AJAXResponse['code'] = 'OK';
            $em->persist($myEntity);        
            $em->flush();
        }else{          
            $AJAXResponse['code'] = 'ERR';  
        }

        if ($request->isXmlHttpRequest() == true) {
            $response = new Response(json_encode($AJAXResponse));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }

    } 

}

问题是这段代码插入得很好,但我无法更新数据;它继续插入。我是否必须通过将新 ID 发送回响应来实现自己的更新方式,或者 Symfony 有没有办法自动处理它?

非常感谢你的帮助。

4

1 回答 1

1

你可以试试这样的

//Firt, update your route (p. ex)
site_add:
    pattern:  /edit/add
    defaults: { _controller: YOURBUNDLE:YOURCONTROLLER:myEntitys }

site_update:
    pattern:  /edit/{id}
    defaults: { _controller: YOURBUNDLE:YOURCONTROLLER:myEntitys }


//Then in your controller

//...
public function myEntitysAction($id = null){

$em = $this->getDoctrine()->getEntityManager();
$request = $this->getRequest();
$AJAXresponse = array();

//To modify
if(isset($id)){
    $myEntity = $em->find('YOURBUNDLE:YOURENTITY', $id);
}
//To create
else{
    $myEntity = new myEntity();
}
//Both return an objet

//Form will be render depeding on objet.
$form = $this->createForm(new myEntityType(), $myEntity);

if ($request->getMethod() == 'POST') {

    $form->bindRequest($this->getRequest());

    if ($form->isValid()) {
        $AJAXResponse['code'] = 'OK';
        $em->persist($myEntity);
        $em->flush();
    }else{
        $AJAXResponse['code'] = 'ERR';
    }

    if ($request->isXmlHttpRequest() == true) {
        $response = new Response(json_encode($AJAXResponse));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

}

}

于 2014-01-19T13:11:03.763 回答