View information in Modal with foreach

Asked

Viewed 563 times

1

I’m having a lot of trouble displaying the database information via a modal. I’m accessing the database by a foreach, but the problem is that it only displays the modal with the last table record.

Excerpt from the code:

 <div class="table-responsive">
              <table class="table table-striped table-sm">
                <thead>
                  <tr>
                    <th>#Id</th>
                    <th>Nome | Paciente</th>
                    <th>Data</th>
                    <th>Exame</th>
                    <th>Médico Solicitante</th>
                    <th>Convênio</th>
                  </tr>
                </thead>

          <?php foreach($dwl->findAll() as $value):?>

                <tbody>
                  <tr>
                    <td><?php echo $value->co_patientid; ?></td>
                    <td><?php echo $value->na_patientname; ?></td>
                    <td><?php echo $value->na_studydate; ?></td>
                    <td><?php echo $value->na_description; ?></td>
                    <td><?php echo $value->na_requestername; ?></td>
                    <td><?php echo $value->na_insuranceplan; ?></td>
            <td>
             <button type="button" class="btn btn-danger">Excluir</button>
             <button type="button" class="btn btn-warning">Editar</button>
             <button type="button" class="btn btn-info" data-toggle="modal" data-target="#ModalView-<?php echo $value->co_patientid; ?>">Visualizar</button>
           </td>
          </tr>
          </tbody>

       <?php endforeach ; ?>

         </table>
            </div>

        <div class="modal fade" id="ModalView-<?php echo $value->co_patientid; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="modalWorkView"><td>Informações</td></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="table-responsive">

                  <p><b>#Id:</b> <?php echo $value->co_patientid; ?> </p>
                  <p><b>Paciente:</b> <?php echo $value->na_patientname; ?> </p>
                  <p><b>Data do Exame:</b> <?php echo $value->na_studydate; ?> </p>
                  <p><b>Descrição Exame:</b> <?php echo $value->na_description; ?> </p>
                  <p><b>Médico Solivitante:</b> <?php echo $value->na_requestername; ?> </p>
                  <p><b>Convênio:</b> <?php echo $value->na_insuranceplan; ?> </p>
                  <p><b><hr></b></p>
                  <p><b>Comentário</p></b>
                  <p><?php echo $value->na_comment; ?> </p>

              </div>
            </div>
          </div>
        </div>


          </main>
        </div>
      </div>

3 answers

0

Italo, I don’t know how your modals are, but if you don’t create a modal on the page for each record, I believe that your line of reasoning won’t work (and even if you had so many modals, it certainly wouldn’t be appropriate to do it this way)You see, if you have 50 records to show on the page, it would have to have 50 modals. oo

Correct Solution: Create only one modal, such as "modal-record" and when the user clicks to view the record, you call a javascript function that inserts the data into the modal using ajax and displays it. If you use jQuery it is very easy to do.

Let’s take a short step by step:

1- Create a div with id="record" inside the "modal-record" which will display the records

<div class="modal fade" id="modal-registro" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title" id="modalWorkView"><td>Informações</td></h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <div id="registro" class="table-responsive"></div>
    </div>
  </div>
</div>

2- Add the onclick event to the log view button by passing the ID as parameter

<button type="button" class="btn btn-info" onclick="mostrarRegistro(<?=$value->co_patientid?>);">Visualizar</button>

3- Create the function that receives the id of the record, search its data using ajax and finally add the response in modal and show it.

function mostrarRegistro(id){
  $.post("consultar-registro.php", { 'id':id},
      function (resposta) {
          // Subistitui o conteúdo da div com id="registro"
          $("#registro").html(resposta);
          // Mostra o modal usando jquery
          $('#modal-registro').modal('show');
      }
  );
}

4- Now just create the php page with the query by the registry id, something like:

// Recebe o id via post
$id = (isset($_POST['id'])) ? $_POST['id'] : null;
...
...
// Consulta os dados do id recebido no banco de dados
$sql - SELECT * FROM...
...
...
// Imprime o resultado para que o jquery insira no modal e o exiba
echo"
   <p><b>#Id:</b>".$value->co_patientid."</p>
   ...
   ...
   ...
   ...
   <p><b>Comentário</p></b>
   <p>".$value->na_comment."</p>
";

Anyway, this is a basic and simple example to show how to do, just you adapt to your purpose, I did not get to test, sometimes there may be some divergence in relation to names and typos, so stick to logic. I hope it helped.

Editing:

Sometimes it works like this, but it turns into a wicked scam that will weigh your page and bring you headaches in the future, just as curiosity and for educational purposes...

Added the modal into the foreach, so it will create a modal for each record, which is not advisable, especially if you have many requests for that page...

<div class="table-responsive">
  <table class="table table-striped table-sm">
    <thead>
      <tr>
        <th>#Id</th>
        <th>Nome | Paciente</th>
        <th>Data</th>
        <th>Exame</th>
        <th>Médico Solicitante</th>
        <th>Convênio</th>
      </tr>
    </thead>

    <?php foreach($dwl->findAll() as $value):?>

    <tbody>
      <tr>
        <td><?=$value->co_patientid;?></td>
        <td><?=$value->na_patientname;?></td>
        <td><?=$value->na_studydate;?></td>
        <td><?=$value->na_description;?></td>
        <td><?=$value->na_requestername;?></td>
        <td><?=$value->na_insuranceplan;?></td>
        <td>
          <button type="button" class="btn btn-danger">Excluir</button>
          <button type="button" class="btn btn-warning">Editar</button>
          <button type="button" class="btn btn-info" data-toggle="modal" data-target="#ModalView-<?php echo $value->co_patientid; ?>">Visualizar</button>
       </td>
      </tr>
    </tbody>
    
    
    <div class="modal fade" id="ModalView-<?=$value->co_patientid;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="modalWorkView"><td>Informações</td></h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="table-responsive">

            <p><b>#Id:</b> <?=$value->co_patientid;?> </p>
            <p><b>Paciente:</b> <?=$value->na_patientname;?> </p>
            <p><b>Data do Exame:</b> <?=$value->na_studydate;?> </p>
            <p><b>Descrição Exame:</b> <?=$value->na_description;?> </p>
            <p><b>Médico Solivitante:</b> <?=$value->na_requestername;?> </p>
            <p><b>Convênio:</b> <?=$value->na_insuranceplan;?> </p>
            <p><b><hr></b></p>
            <p><b>Comentário</p></b>
            <p><?=$value->na_comment;?> </p>

        </div>
      </div>
    </div>
  </div>


   <?php endforeach ; ?>

  </table>
</div>


</main>
</div>
</div>

0

Using Jquery

Add:

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Replace this part:

<button type="button" class="btn btn-info" data-toggle="modal" data-target="#ModalView-<?php echo $value->co_patientid; ?>">Visualizar</button>

For:

<button type="button" data-paciente='<?php echo json_encode($value) ?>' class="btn btn-info visualizar">Visualizar</button>

Replace this part:

<div class="modal fade" id="ModalView-<?php echo $value->co_patientid; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

For this:

<div class="modal fade" id="idModal" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">

Below, create a script (javascript), this way:

  <script>
   //Quando clicar em visualizar:
    $('.visualizar').click(function() {
      //Os dados
      let data = JSON.parse($(this).attr('data-paciente'));

      //Veja o código no console
      console.log(data);

      //#IdModal: Id do seu modal.
      //Show: abre o modal.
      $('#idModal').modal('show');

      /*O elemento em que você queira mostrar os dados,
      ao clicar no botão de visualizar. 
      Aqui, você poder fazer qualquer coisa:*/
      $('#get-data-modal').html(JSON.stringify(data));
    })
  </script>

0

Friend Taffarel, thank you so much for your help ! I think I expressed my doubt wrong, in fact this foreach lists all the records of my table patients as shown in the image below. PRINT 01 Until this stage everything happens as expected however, when clicking on the visualization button of that patient it displays the Modal but returns only the last record inserted in the table, that is, it does not open the modal with the corresponding ID. In the submitted print there are 4 patients, when clicking on the modal of the first 3 records(Stallone, Joana, ana) it only retouches the information of the last record (Rgio).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.