我正在研究Symfony 2中的一个项目,我在视图中有一个调用删除表单的链接;我跟着Best practices - Delete links with Symfony 2来处理这个案子,它已经有效了,但我遇到的问题是,当我在动作结束时使用重定向时,我遇到了以下问题:
重定向转到
/Stock/boncommande/27/boncommande
但我希望它是
/Stock/boncommande
以下是所涉及的不同部分的代码:
控制器/动作
/**
* Deletes a Boncommande entity.
*
* @Route("/{id}", name="boncommande_delete")
* @Method("DELETE")
*
*/
public function deleteAction(Request $request, $id) {
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('StockStockBundle:Boncommande')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Boncommande entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl("boncommande"));
}
/**
* Creates a form to delete a Boncommande entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id) {
return $this->createFormBuilder()
->setAction($this->generateUrl('boncommande_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
路由文件
#bon de commande
boncommande:
pattern: /boncommande
defaults: { _controller: StockStockBundle:Boncommande:index }
boncommande_delete:
pattern: /boncommande/{id}/delete
defaults: {_controller: StockStockBundle:Boncommande:delete}
requirements:
_method: POST|GET
视图中的链接
<a href="{{path('boncommande_delete', { 'id': entity.idbc })}}" id="stock_stockbundle_annuler" class="as-form btn red"
data-method="delete"> Annuler</a>
JQuery代码
$('.as-form').on('click',function(){
var $form = $('<form/>').hide();
//form options
$form.attr({
'action' : $(this).attr('href'),
'method':'post'
})
//adding the _method hidden field
$form.append($('<input/>',{
type:'hidden',
name:'_method'
}).val($(this).data('method')));
//add form to parent node
$(this).parent().append($form);
$form.submit();
return false;
});
提前感谢您的帮助!