Pass id of a table data to modal?

Asked

Viewed 8,428 times

1

Good morning guys, for a college job I’m trying to create a modal, for decision whether or not I want to delete a record from a table, in this table I have the user information on a grid with new buttons, delete, Edit and checkbox for removal of various records. On buttons I have id information in tags with their reference to the user registration window.

at click time I would like to call the modal to confirm the deletion or cancel the operation. But I don’t know how to pass an id that’s in the same reference to it. Or another way that works.

<!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">
        <title>Usuários</title>

        <?php
        include_once './menu_logged.php';
        include_once './_dao/dao_usuario.php';

//        $key = "38ea2ab716998d19"; //Gimenes
//        $aes = new AES($key);
        ?>

        <!-- IMPORTAÇÕES PARA A TABELA EM CSS -->
        <link rel = "stylesheet" href = "_css/table_white_normalize.css">
        <link rel = 'stylesheet prefetch' href = '_css/dataTables.white.bootstrap.css'>
        <link rel = 'stylesheet prefetch' href = '_css/dataTables.white.responsive.css'>
        <link rel = "stylesheet" href = "_css/table_white.css">       
        <link rel = "stylesheet" href = "_css/checkbox_black.css">       
        <!-- FIM IMPORTAÇÕES PARA A TABELA EM CSS -->
 
        <script>
            function newDoc() {
                window.location.assign("tb_users.php");
            }
            document.onkeyup = function (e) {
                if (e.which === 46) {
                    document.formSubmit.submit();
                    return false;
                }
            };            
        </script>

        <style>
            div{
                font-family: Ubuntu-L;
            }
            div#extTable{
                box-shadow: 1px 1px 6px silver; 
                padding: 20px; 
                background-color: white
            }
            h2{
                font-family: Ubuntu-M;
            }
            .pagination > .active > a,
            .pagination > .active > span,
            .pagination > .active > a:hover,
            .pagination > .active > span:hover,
            .pagination > .active > a:focus,
            .pagination > .active > span:focus {
                z-index: 3;
                color: #fff;
                cursor: default;
                /*background-color: #337ab7;*/ 
                /*INICIO D ALTERAÇÃO DO BOOTSTRAP COLOR*/
                color:white !important;
                border:1px solid #111;
                background-color:#585858;
                background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));
                background:-webkit-linear-gradient(top, #585858 0%, #111 100%);
                background:-moz-linear-gradient(top, #585858 0%, #111 100%);
                background:-ms-linear-gradient(top, #585858 0%, #111 100%);
                background:-o-linear-gradient(top, #585858 0%, #111 100%);
                background:linear-gradient(to bottom, #585858 0%, #111 100%);
                /*FIM DA ALTERAÇÃO DO BOOTSTRAP COLOR*/
                border-color: silver;
            }        
            .pagination > li > a,
            .pagination > li > span {
                position: relative;
                float: left;
                padding: 6px 12px;
                margin-left: -1px;
                line-height: 1.42857143;
                color: #337ab7;
                color: #585858;
                text-decoration: none;
                background-color: #fff;
                border: 1px solid #ddd;
            }           
        </style>
    </head>
    <body>

        <br>
        <br>
        <br>

        <div class="container">

            <!-- INICIO / FORM PARA A CAPTAÇÃO DA TECLA DEL -->
            <form action="#" method="post" name="formSubmit" id="formSubmit"> 

                <h2 style="text-align: left;"><span class="glyphicon glyphicon-user"></span> Usuários</h2>

                <!-- INICIO QUADRO EXTERNO PARA A TABELA-->
                <div id="extTable">

                    <div class="row">

                        <div class="col-xs-12">

                            <!-- INICIO DA TABELA -->
                            <table summary="This table shows how to create responsive tables using Datatables' extended functionality" class="table-responsive table table-bordered table-hover dt-responsive" style="margin: 0 auto; width: 100%; height: 100%;">
                                <caption class="text-left" hidden>Usuários cadastrados no sistema.</caption>

                                <?php
                                /* #INICIO - Var de Mensagens para as modais */
                                $msgModal = "";
                                $linhaModal = "";
                                /* #FIM */

                                /* #INICIO - Método de checagem de registros selecionados para exclusão simultanea */
                                if (isset($_POST['check'])) {
                                    try {
                                        if (!DaoUsuario::deleteSelected($_POST['check'])) {
                                            $msgModal = "Não foi possivel excluir os registros selecionados !";
                                            $linhaModal = '<p style="text-align: center;><b><span class="glyphicon glyphicon-remove" style="color: red"></span> &nbsp; ' . $msgModal . ' </b></p>';
                                            echo '<script> $(document).ready(function(){ $("#modalUser").modal(); }); </script>';
                                        } else {
                                            $msgModal = "Os usuários selecionados foram removidos com sucesso !";
                                            $linhaModal = '<p style="text-align: center;"><b><span class="glyphicon glyphicon-ok" style="color: green"></span> &nbsp; ' . $msgModal . ' </b></p>';
                                            echo '<script> $(document).ready(function(){ $("#modalUser").modal(); }); </script>';
                                        }
                                    } catch (PDOException $ex) {
                                        $msgModal = "Conflito na remoção dos registros selecionados. ERRO --> " . $ex->getMessage();
                                        $linhaModal = '<p style="text-align: center;"><b><span class="glyphicon glyphicon-remove" style="color: red"></span> &nbsp; ' . $msgModal . ' </b></p>';
                                        echo '<script> $(document).ready(function(){ $("#modalUser").modal(); }); </script>';
                                    }
                                }
                                /* #FIM - método de checagem de registros selecionados para exclusão simultanea */

                                /* #INICIO - Método de exclusão de registro */
                                if (isset($_GET['id'])) {
                                    try {
                                        if (!DaoUsuario::delete($_GET['id'])) {
                                            $msgModal = "Não foi possivel excluir o registro selecionado !";
                                            $linhaModal = '<p style="text-align: center;><b><span class="glyphicon glyphicon-remove" style="color: red"></span> &nbsp; ' . $msgModal . ' </b></p>';
                                            echo '<script> $(document).ready(function(){ $("#modalUser").modal(); }); </script>';
                                        } else {
                                            $msgModal = "O usuário selecionado foi removido com sucesso !";
                                            $linhaModal = '<p style="text-align: center;"><b><span class="glyphicon glyphicon-ok" style="color: green"></span> &nbsp; ' . $msgModal . ' </b></p>';

                                            echo '<script> $(document).ready(function(){ $("#modalUser").modal(); }); </script>';
                                        }
                                    } catch (PDOException $ex) {
                                        $msgModal = "Conflito na remoção do registro selecionado. ERRO --> " . $ex->getMessage();
                                        $linhaModal = '<p style="text-align: center;"><b><span class="glyphicon glyphicon-remove" style="color: red"></span> &nbsp; ' . $msgModal . ' </b></p>';
                                        echo '<script> $(document).ready(function(){ $("#modalUser").modal(); }); </script>';
                                    }
                                }/* #FIM - Método de exclusão  de registro */
                                ?>

                                <!-- ININIO / THEAD (CABEÇA) da tabela -->
                                <thead>                           
                                    <?php
                                    /* #INICIO - Consulta no banco de dados */
                                    $user_array = DaoUsuario::selectAll();
                                    /* #FIM - Consulta no banco de dados */

                                    /* #INICIO - Construção do cabeçalho da tabela */
                                    echo '<tr>';
                                    echo '<th id="id"></span> &nbsp; &nbsp;#</th>';
                                    echo '<th id="nm"></span> &nbsp; &nbsp;NOME</th>';
                                    echo '<th id="lgn"></span> &nbsp; &nbsp;LOGIN</th>';
                                    echo '<th id="nivel"></span> &nbsp; &nbsp;NÍVEL</th>';
                                    echo '<th id="img"></span> &nbsp; &nbsp;IMAGEM</th>';
                                    echo '<th id="opc">OPÇÕES</th>';
                                    echo '<th id="check"></th>';
                                    echo '</tr>';
                                    /* #FIM - Construção do cabeçalho da tabela */
                                    ?>                            
                                </thead>
                                <!-- FIM / THEAD (CABEÇA) da tabela -->

                                <!-- INICIO / BODY da tabela -->
                                <tbody> 
                                    <?php
                                    /* #INICIO - Geração das linhas da tabela utilizando um vetor recebido pela consulta no banco */
                                    foreach ($user_array as $row) {
                                        echo '<tr id='.base64_encode($row->getId_usuario()).'>';
                                        echo '<td style="text-align: center; vertical-align: middle;">' . $row->getId_usuario() . '</td>';
                                        echo '<td style="text-align: center; vertical-align: middle;">' . $row->getNm_usuario() . '</td>';
                                        echo '<td style="text-align: center; vertical-align: middle;">' . $row->getNm_login() . '</td>';
                                        echo '<td style="text-align: center; vertical-align: middle;">' . $row->getTp_usuario() . '</td>';
                                        echo '<td style="text-align: center; vertical-align: middle;"><img src="' . $row->getImg_link() . '" width="30" heigth="30"/></td>';
                                        echo '<td style="width: 40px; text-align: center; vertical-align: middle;"><a href="form_usuario.php"><button type="button" title="Novo Usuário" class="btn btn-success"><span class="glyphicon glyphicon-plus"><span></button></a> &nbsp;'
                                        . '<a href="tb_users.php?id=' . base64_encode($row->getId_usuario()) . '&ex=true"><button type="button" title="Remover Usuário" class="btn btn-danger"><span class="glyphicon glyphicon-minus"><span></button></a> &nbsp;'
                                        . '<a href="form_usuario.php?id=' . base64_encode($row->getId_usuario()) . '"><button type="button" title="Alterar Usuário"class="btn btn-inverse"><span class="glyphicon glyphicon-pencil"><span></button></a></td>';
                                        echo "<td style='width: 40px; text-align: center; vertical-align: middle;'><input type='checkbox' name='check[]' value='" . base64_encode($row->getId_usuario()) . "' /></td>";
                                        echo '</tr>';
                                    }
                                    /* #FIM - Construção do cabeçalho da tabela */
                                    ?>                               
                                </tbody>
                                <!-- FIM / BODY da tabela -->

                                <!-- INICIO / Footer da tabela -->
                                <tfoot>
                                    <tr>
                                        <td colspan="7" class="text-center">** Para remover um ou mais registros selecione as caixas de marcação e tecle DEL.</td>
                                    </tr>
                                </tfoot>
                                <!-- FIM - Footer da tabela -->

                            </table>
                            <!-- FIM DA TABELA -->
                        </div>
                    </div>  
                </div>
                <!-- FIM QUADRO EXTERNO PARA A TABELA-->
            </form>
            <!-- FIM / FORM PARA A CAPTAÇÃO DA TECLA DEL -->
        </div>    

        <br>
        <br> 

        <!-- Modal -->
        <div id="modalUser" class="modal fade" role="dialog" data-backdrop="static">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Remoção de Usuário</h4>
                    </div>
                    <div class="modal-body">
                        <?php echo $linhaModal; ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" onclick="newDoc()">Fechar</button>
                    </div>
                </div>
            </div>
        </div>  

        <!-- IMPORTAÇÃO DOS SCRIPTS JS PARA A TABELA -->
        <script src='_js/jquery.dataTables.table_white.js'></script>;
        <script src='_js/dataTables.white.bootstrap.js'></script>
        <script src='_js/dataTables.white.responsive.js'></script>
        <script src="_js/table_white.js"></script>
        <!-- FIM DA IMPORTAÇÃO DOS SCRIPTS JS PARA A TABELA -->

        <br>
        <br>
        <br>    

    </body>
</html>

The execution will not work because you need dependencies, in case you need I can send the project.

Thank you..


I would like to thank everyone who offered to help me before my doubt. Mainly the user Miguel who accompanied me throughout the day. Thank you very much.....

  • The modal is not ready... I still need to modify the medium and add the buttons.. would be the fashionUser...

  • I ask you to add the tags, boostrap and jquery. Because actually this is not done in php...

  • Personal pardon this is the modal only for confirmation messages of the operation that already happened, I would create another, with the buttons of cancellation and confirmation for ex. a fashionlQuestion...

  • Yes I’ll add sorry..

  • No problem. The answer below does not help this?

2 answers

2


I made an example that I think you can adjust to what you want. What I did was for each delete button in the table add attributes date of Html5, is really very useful in these situations, can withdraw the data-name if you do not need to include in the modal confirmation question:

Watch the hrefs from the modal yes button to be changed depending on the tile element you clicked to delete.

JSFIDDLE

$('.delete').on('click', function(){
      var nome = $(this).data('nome'); // vamos buscar o valor do atributo data-name que temos no botão que foi clicado
      var id = $(this).data('id'); // vamos buscar o valor do atributo data-id
      $('span.nome').text(nome+ ' (id = ' +id+ ')'); // inserir na o nome na pergunta de confirmação dentro da modal
      $('a.delete-yes').attr('href', 'apagar.php?id=' +id); // mudar dinamicamente o link, href do botão confirmar da modal
      $('#myModal').modal('show'); // modal aparece
});
td {
  min-width: 80px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

<table>
<tr>
  <td>
nome1
  </td>
  <td>
telefone1
  </td>
  <td>
email1
  </td>
  <td>
endereço1
  </td>
  <td><button data-nome="nome1" data-id="1" class="delete btn btn-xs btn-primary">Apagar</button>
</tr>
<tr>
 <td>
nome2
  </td>
  <td>
telefone2
  </td>
  <td>
email2
  </td>
  <td>
endereço2
  </td>
  <td><button data-nome="nome2" data-id="2" class="delete btn btn-xs btn-primary">Apagar</button>
</tr>
<tr>
  <td>
nome3
  </td>
  <td>
telefone3
  </td>
  <td>
email3
  </td>
  <td>
endereço3
  </td>
  <td><button data-nome="nome3" data-id="3" class="delete btn btn-xs btn-primary">Apagar</button>
  </td>
</tr>

</table>

<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Modal Header</h4>
    </div>
    <div class="modal-body">
      Deseja mesmo apagar <span class="nome"></span>
    </div>
    <div class="modal-footer">
      <a href="#" type="button" class="btn btn-default delete-yes">Sim</a>
      <button type="button" class="btn btn-default" data-dismiss="modal">Não</button>
    </div>
  </div>
   </div>
   </div>

1

The logic is simple, recover the registration ID and pass to your modal using set Attributes - attr() of jquery. Here in this example I weighed the id value for the modal class attribute. To save the registration ID you can do a few different ways when generating the page with php. I usually keep as id in element tr. That is, that line belongs to a specific record. Then you recover the id of the line and pass to the modal.

$(document).ready(function(){
    $("#seuBtnDeletar").click(function(){
        //Recupere o Id do registro e passe para o seu modal
        var trid = $(this).closest('tr').attr('id');
        $("#meuModal").attr("class", trid );
    });
});

In the code, $(this). is the button, and closest('tr').attr('id'); retrieves the id of the tr that the button is inserted into. Vc can use a composite string to store the id of the element <tr>

  • I will add an id="record id" to the <tr>, remove the <a href=""> from the button, and add the jquery code. changing the id to the name of my boot, and the name of my modal... That’s it, sorry I couldn’t make it work, I’m still learning less than a month dealing with php.

  • Yeah. I usually do like this: <tr id="id_2" ...>. It then recovers and treats the string to identify the registry id. There are several ways to do this. Another approach, which I think is simpler, is to get the modal ready, when you generate the page dynamically with php. That is, if you inspect the source code of the page, you will see that all the modals are already there. You will not need javascript to pass anything to them. Obviously this has a limit. It depends on your analysis. I will edit my reply to clarify.

Browser other questions tagged

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