我正在尝试使用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是否有办法自动处理?
非常感谢你的帮助。
答案 0 :(得分: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;
}
}
}