EDIT: How can I confirm submission of a selected user id in a form of a Sweet Alert? See, I have this table which displays all the registered users in my webpage. My problem is I don't know how to generate Symfony's route to a <button>
tag in my twig template. I can't use <a>
tag because SWAL only executes when data-type
is use and it's only available in <button>
tag, which can't use a href
attribute like href="{{ path('path_to_route') }}"
. I also had problem calling for the {{ user.id }}
because it doesn't get the user id of the button I selected. I have this code from various sources but still there's somethings wrong. Badly need help!
UPDATE: I can't download FOSJsRoutingBundle because we are working in a company with some installation restriction and unfortunately, installing a Bundle is part of it. Is there any alternative?
My Twig:
<div class="row clearfix js-sweetalert">
<div class="btn-group" role="group">
<button class="btn btn-warning waves-effect" data-type="cancel"><i class="material-icons">build</i></button>
<button class="btn btn-danger waves-effect" data-type="delete-user" data-userId="{{ user.id }}"><i class="material-icons">delete</i></button>
</div>
</div>
This is my Controller:
public function deleteUserAction($id)
{
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(['id' => $id]);
if ($user == null) {
throw new NotFoundHttpException('User not found for user' . $user);
}
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
$userManager->deleteUser($user);
$this->setFlash('user_deleted', $user . ' has been successfully deleted!');
$url = $this->generateUrl('fos_user_userList');
return new RedirectResponse($url);
}
This is my Sweet Alert script:
$(function () {
$('.js-sweetalert button').on('click', function () {
var type = $(this).data('type');
if (type === 'basic') {
showBasicMessage();
}
else if (type === 'delete-user') {
var userId = $(this).data('userId');
showDeleteUserMessage();
}
function showDeleteUserMessage() {
swal({
title: "Are you sure you want to delete this user?",
text: "You will not be able to recover this user",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function (isConfirm) {
if (isConfirm) {
var data = {id : userId};
$.ajax({
type: "POST",
url: "{{ path('fos_user_deleteUser') }}",
data: data,
success: function(data, dataType) {
swal("Deleted", "The user has been removed from the Database", "Success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
} else {}
});
}
In html add the user id
at the time of button click u need to take the user id value and pass it through the function
Inside the function(isConfirm) u can call ajax
plz check ur js file open an close braces