Reputation: 851
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
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
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 =>
Upvotes: 1
Reputation: 1842
$('body').on('click', '.user', function() {
$('#user .modal-content').html($(this).data('firstname'));
$('#user').modal();
});
Upvotes: 1