user1392897
user1392897

Reputation: 851

Dynamic Modal Data with Twig

I am display a list of users using Twig:

{% for user in user.users %}
    <div class="row user" data-id="{{ user.id }}">
        <div class="col">{{ user.firstname }} {{ user.lastname }}</div>
        <div class="col">{{ user.email }}</div>
        <div class="col">{{ user.lastLogin|date("F j, Y \\a\\t g:i a") }}</div>
    </div>
{% endfor %}

When the user clicks on this row, I would like a modal dialog to open with additional details about this specific user.

I have considered simply including the modal within the for loop. However, if the list contains several hundred users, I do not want to render all of this additional data on every page load.

My thought was to do something like this:

$('body').on('click', '.user', function() {
  $('#user').modal();
});

But I am not sure how to dynamically render only the clicked user's data in the modal via twig:

<div class="modal fade" id="user" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            {{ user.firstname }} //additonal data for a given user
        </div>
    </div>
</div>

Upvotes: 1

Views: 2816

Answers (3)

user1392897
user1392897

Reputation: 851

Following the general guidance provided by the other two posters, I ultimately developed the solution using an AJAX request. General outline below:

Controller:

if ($request->isXMLHttpRequest()) {

    $user = $this->entityManager->getRepository(User::class)->find($request->get('user_id'));

    return $this->render(
        'ui/user-details-modal.html.twig',
       ['user' => $user]
    );
}

Javascript:

$('body').on('click', '.user', function() {
    let id = $(this).data('id');
    return $.ajax({
        type: 'POST',
        url: url,
        data: {user_id: id},
        dataType: 'html',
        success: function(response) { 
            $('#user-details').html(response);
            $('#user').modal();     
        }
    });
});

Hopefully it will be helpful for anyone else looking to do something similar.

Upvotes: 3

Walse
Walse

Reputation: 71

As Max said, there's two way of achieving this. I would prefer the first approach because you don't need to add all data-attributes, you can plug twig templates to backend function as mentioned here https://symfony.com/doc/current/frontend/encore/server-data.html => enter image description here

Upvotes: 1

Max Lipsky
Max Lipsky

Reputation: 1842

  1. Simple: You can set data into .row like data-id (data-firstname, data-lastname etc.) And replace text inside popup like:
$('body').on('click', '.user', function() {
  $('#user .modal-content').html($(this).data('firstname'));
  $('#user').modal();
});
  1. Better: To make ajax request to server by user id and show response into popup.

Upvotes: 1

Related Questions