WashichawbachaW
WashichawbachaW

Reputation: 235

Symfony - How to use JavaScript variable to be a parameter value in Symfony route?

Note: I can't install FOSJsRoutingBundle because of our company's restrictions.

Scenario: I have a twig template that shows a table of registered users in my database. There are buttons that corresponds to every user. Each button has a function of updating and deleting user. I'm now working on the delete user button.

Problem: My problem is, how to use JavaScript variable to be a parameter value in Symfony route? e.g.

This path: {{ path('route_to_deleteUser', { 'id': user.id }) }}

Change to this example path in Ajax:

var userId = $(this).attr('id');
var route = "{{ path('route_to_deleteUser', { 'id': userId }) }}";

I tried it out but it doesn't do anything. I also tried doing this:

var route = "{{ path('route_to_deleteUser', { 'id': 10 }) }}"; // 10 is the value of user with id = 10

The code above is successful in deleting the user with the id = 10 but it only deletes the id I manually inputted in the path and also it only shows the SWAL success message but not reloading the page to show the new users table without the deleted user.

Goal: I want to have a button that executes a SWAL confirmation message for my deleteUser function and after the success message, it returns the new users table with the updated Database.

This is my Route:

fos_user_deleteUser:
path:      /users/{id}
defaults: { _controller: FOSUserBundle:Profile:deleteUser }

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 twig:

<tbody>
    {% for user in user %}
        <tr>
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.roles[0] }}</td>
            <td>{{ user.lastLogin | date('F m, Y') }}</td>
            <td class="row clearfix js-sweetalert">
                {% if is_granted('ROLE_ADMIN') %}
                    <center>
                    <div class="btn-group" role="group">
                        <button class="btn btn-warning waves-effect" data-type="update-user"><i class="material-icons">supervisor_account</i></button>
                        <button class="btn btn-danger waves-effect" data-type="delete-user" id="{{ user.id }}"><i class="material-icons">delete_forever</i></button>
                    </div>
                    </center>
                {% endif %}
            </td>
        </tr>
    {% endfor %}
</tbody>

This is my script:

<script>
        $(function () {
            $('.js-sweetalert button').on('click', function () {
                var type = $(this).data('type');
                if (type === 'delete-user') {
                    var userId = $(this).attr('id');
                    showDeleteUserMessage();
                }
            });
        });
        function showDeleteUserMessage(userId) {
            swal({
                title: "Delete this user?",
                text: "You will not be able to recover this user",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#dd6b55",
                confirmButtonText: "Delete",
                closeOnConfirm: false
            }, function (isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        type: 'POST',
                        url: "{{ path('fos_user_deleteUser', { 'id': userId }) }}",
                        success: function() {
                            swal("Success", "The user has been removed from the Database!", "success");
                        }
                    });
                } else {}
            });
        }
    </script>

Feel free to edit the question and content for correction.

I hope someone could help me and also replies when asked. My previous question has no reply.

Upvotes: 2

Views: 2105

Answers (1)

Jeet
Jeet

Reputation: 1587

How about passing the url as an data attribute for each rows and collect in js. This way you don't have to build the url in javascript.

<button class="btn btn-danger waves-effect" data-type="delete-user" id="{{ user.id }}" data-href="{{ path('fos_user_deleteUser', { 'id': user.id }) }}">
    <i class="material-icons">delete_forever</i>
</button>

In twig, before you add js :

<script type="text/javascript">
    var user_list_url = "{{ path('route_to_user_listing') }}";
</script>

Why you need above code? So that:

  • Any change to url path /users in your route is respected.
  • / might be tricky when your site will be loaded from a subfolder.

And then, collect the respective url in javascript.

$(function () {
        $('.js-sweetalert button').on('click', function () {
            var type = $(this).data('type');
            if (type === 'delete-user') {
                var userId = $(this).attr('id'); // you might need an id somewhere.
                var deleteUrl = $(this).data('href');
                showDeleteUserMessage(userId, deleteUrl);
            }
        });
    });
    function showDeleteUserMessage(userId, deleteUrl) {
        swal({
            title: "Delete this user?",
            text: "You will not be able to recover this user",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#dd6b55",
            confirmButtonText: "Delete",
            closeOnConfirm: false
        }, function (isConfirm) {
            if (isConfirm) {
                $.ajax({
                    type: 'POST',
                    url: deleteUrl,
                    success: function() {
                        swal("Success", "The user has been removed from the Database!", "success");
                        window.location.href = user_list_url;
                    }
                });
            } else {}
        });
    }

For me it always works.

Hope it helps!

Upvotes: 2

Related Questions