Skip to content

Instantly share code, notes, and snippets.

@Veve2
Last active November 22, 2016 13:13
Show Gist options
  • Save Veve2/1a9ff2f0ce6274ac95f1cba312f1cd6e to your computer and use it in GitHub Desktop.
Save Veve2/1a9ff2f0ce6274ac95f1cba312f1cd6e to your computer and use it in GitHub Desktop.
Symfony - AJAX delete action
<?php
/**
* @Route("category/delete/{id}", name="category_delete")
* @Method({"GET", "DELETE"})
*/
public function deleteAction(Request $request, $id)
{
/*
* Check Permission.
*/
$response = array(
'success' => true,
'message' => '',
'html' => '',
);
$repository = $this->getDoctrine()->getRepository('AppBundle:Category');
$category = $repository->find($id);
$form = $this->createDeleteForm($category);
if ($request->getMethod() == 'DELETE') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($category);
$em->flush();
// Get response ready as per your need.
$response['success'] = true;
$response['message'] = 'Deleted Successfully!';
} else {
$response['success'] = false;
$response['message'] = 'Sorry category could not be deleted!';
}
return new JsonResponse($response);
// In case you want to redirect.
// $this->addFlash('notice', 'Deleted Successfully!');
// return $this->redirectToRoute('category_index');
}
$render = $this->render(':category:delete_confirm.html.twig', array(
'delete_form' => $form->createView(),
'category' => $category,
));
$response['html'] = $render->getContent();
return new JsonResponse($response);
}
{{ form_start(delete_form) }}
<div class="uk-modal-header">
<h3 class="uk-modal-title">Delete this Category?</h3>
</div>
<p>
Are you sure you want to delete '{{ category.name }}'?<br/>
This cannot be undone.
</p>
<div class="uk-modal-footer uk-text-right">
<div>
<button type="submit" class="md-btn md-btn-danger" title="Click to proceed!">
<i class="uk-icon-trash"></i> Delete
</button>
<button type="button" class="md-btn md-btn-warning uk-modal-close">Cancel</button>
</div>
</div>
{{ form_end(delete_form) }}
@Veve2
Copy link
Author

Veve2 commented Nov 22, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment