Symfony - How to use route for form submission using Sweet Alert?

2.6k Views Asked by At

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 {}
    });
}
2

There are 2 best solutions below

4
On

In html add the user id

 <button class="btn btn-danger waves-effect" data-userId="1" data-type="delete-user"><i class="material-icons">delete forever</i></button>

at the time of button click u need to take the user id value and pass it through the function

var type = $(this).data('type');
if (type === 'delete-user') {
  var userId = $(this).data('userId');
    showDeleteUserMessage(userId);
}

Inside the function(isConfirm) u can call ajax

 if (isConfirm) {
      //ajax request here
   var data = {id : userId};  //u need to post  id

    $.ajax({
        type: "POST",
        url: "{{ path('fos_user_deleteUser') }}",
        data: data,
        success: function(data, dataType)
        {
            alert(data);
        },

        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert('Error : ' + errorThrown);
        }

    } else {
        swal("Cancelled", "not deleting", "error");
    }

plz check ur js file open an close braces

3
On

you can generate routes in your Javascript code with the FosJsRoutingBundle or move your js-code into a twig-template to use the path twig function