I'm working on a project in Symfony 2, and I have inside a view a link which calls a delete form; I followed Best practices - Delete links with Symfony 2, to deal with this case, and it has worked, but the problem that I have is that, when I use redirect in the end of the action, I get the following problem:
The redirect goes to
/Stock/boncommande/27/boncommande
but I want it to be
/Stock/boncommande
Here is the code of the different parts involved:
Controller/Action
/**
* 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()
;
}
Routing file
#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
Link in view
<a href="{{path('boncommande_delete', { 'id': entity.idbc })}}" id="stock_stockbundle_annuler" class="as-form btn red"
data-method="delete"> Annuler</a>
JQuery code
$('.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;
});
Thanks in advance for help!