我正试图以一种形式提出两个动作,即更新和创建:
<form id="form-add1" method="post" action="{{ entity.id ? path('entities_edit') : path('entities_new')}}">
<div class="choice-fields">
<div class="move-left">
<label for="title">title</label>
<input class="form-control" type="text" id="title" name="title" value="{{ entity.title }}" >
</div>
<div class="move-left">
<div class="color-style">
<div class="input-name">Color</div>
<input type="color" name="color" class="color-picker" id="color" value="{{ entity.color }}" >
</div>
</div>
</div>
<div class="clear"></div>
<div>
<label for="description">Description</label>
<textarea id="description" name="description">{{ entity.description }}</textarea>
</div>
<div class="btn-add">
<button type="submit" class="save">Enregistrer</button>
<button type="reset" class="reset">Réintialiser</button>
</div>
<div id="here"></div>
<div class="clear"></div>
</form>
这是我的职能:
create
:
public function newAction(Request $request)
{
$entity = new Entities();
$form = $this->createForm(new EntitiesType(), $entity);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AppBundle:Entities')->findAll();
$em = $this->getDoctrine()->getManager();
$entity->setColor($request->get('color'));
$entity->setTitle($request->get('title'));
$entity->setDescription($request->get('description'));
$em->persist($entity);
$em->flush();
$identity = $entity->getId();
if($request->isXmlHttpRequest())
{
$json = json_encode(array(
'entities' => $request->get('title'),
'identity' => $identity
));
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-Type', 'application/json');
$response->setContent($json);
return $response;
}
return $this->redirectToRoute('entities_index');
}
update
:
public function editAction(Request $request, Entities $entity, $id)
{
$entity = $em->getRepository('AppBundle:Entities')->find($id);
$entity->setTitle($request->get('title'));
$entity->setColor($request->get('color'));
$entity->setDescription($request->get('description'));
$em->persist($entity);
$em->flush();
$json = json_encode(array());
return $this->redirectToRoute('Entities_index');
}
我的路线:
entities_new:
path: /new
defaults: { _controller: "AppBundle:Entities:new" }
methods: [GET, POST]
entities_edit:
path: /{id}/edit
defaults: { _controller: "AppBundle:Entities:edit" }
methods: [GET, POST]
当实体被调用为updated
时,新实体为added
。任何人都可以解释一下吗?
答案 0 :(得分:1)
update
方法的签名是错误的。应该是这样的:
public function editAction(Request $request, Entities $entity)
或者
public function editAction(Request $request, $id)
在第一种情况下,您使用ParamConverter
功能通过Request
的ID自动加载实体,在这种情况下,您没有使用find($id)
方法,因为实体已经加载。
在第二种情况下,您通过手动find
方法从数据库加载实体。
在您的签名中,$ id被定义为第三个参数,因此它始终为null,因此它将始终加载一个新实体。但是你也修改了现有的实体,所以基本上给它分配了一个空ID。
这就是它被插入的原因。
答案 1 :(得分:0)
在您的编辑方法中删除第二个参数,以便您只拥有请求和ID。然后更新你的twig&#39; entities_edit&#39; path('entities_edit', {'id':entityId})
的路径您需要添加模板var&#34; entityId&#34;到您的表单页面