Search code examples
javascriptdatatablemodal-dialogtwig

How to get an id in a datatable and show twig variable inside a datatable


I have a DataTable and want to get an item id to display more information about the item in a modal. Im using twig and dont know how to get the item id and how to display the other information in that modal window using twig.

Datatable

<td>
    <a href='#ModalInfo' class="btn" data-toggle="modal" title='info'>
        <i class="fa-solid fa-info text-warning" data-target="#ModalInfo"></i>
    </a>
</td>

Modal

<div class="modal fade" id="ModalInfo" tabindex="-1" role="dialog" aria-labelledby="ModalCentral" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="TituloModalCentralizado">Aditional information</h5>
                </button>
            </div>
        <div class="modal-body">
            <p>Responsible: {{alerta.resp}}</p>
            <p>Investment: {{alerta.investment}}</p>
        </div>

javascript

<script type="text/javascript">
    $('#ModalInfo').on('shown.bs.modal', function () {
        $('#meuInput').trigger('focus')
    })
</script>

Solution

  • All your modals have the same id. This is invalid and will cause problems in showing the correct modal window. You should append the id of your "alerta"

    You should also place one modal per "alerta"

    {% for alerta in alertas %}
    <div class="modal fade" id="ModalInfo{{ alerta.id }}" tabindex="-1" role="dialog" aria-labelledby="ModalCentral" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Aditional information</h5>
                </div>
            <div class="modal-body">
                <p>Responsible: {{alerta.resp}}</p>
                <p>Investment: {{alerta.investment}}</p>
            </div>
        </div>
    </div>
    {% endfor %}
    
    <td>
        <a href='#ModalInfo{{ alerta.id }}' class="btn" data-toggle="modal" title='info'>
            <i class="fa-solid fa-info text-warning" data-target="#ModalInfo{{ alerta.id }}"></i>
        </a>
    </td>
    

    Sidenote: The HTML of your modal is invalid...