Passing a data id from a table to the modal?

1

Good morning, for a college work 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 user information on a grid with new, delete, edit and checkbox to remove multiple records. In the buttons I have the information of the id in the tags with the reference of the same ones to the window of register of the user.

At the time of the click I would like to call the modal to confirm the deletion or cancel the operation. But I do not know how to pass an id that is the reference of the same 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>

It will not work execution because it needs the dependencies, in case I need to send the project.

Thank you ..

I would like to thank everyone who made themselves available to help me with my question. Mostly the user Miguel who accompanied me during the day .. Thank you very much .....

    
asked by anonymous 27.05.2016 / 12:55

2 answers

2

I've done an example that I think you can adjust to whatever you want. What I did was for each button delete in the table add attributes html5 date , is even very useful in these situations, you can remove data-name if you do not need to include it in the modal confirmation question:

Notice the hrefs of the Mod button Yes to change depending on the tab 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><scriptsrc="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>
    
27.05.2016 / 13:24
1

The logic is simple, retrieve the registry ID and switch to your modal using set Attributes - attr () from jquery . Here in this example I parsed the id value for the modal class attribute. To save the registration ID you can do it in a few different ways when you are generating the page with php. I usually keep as id in element tr. That is, that line belongs to a specific record. Then you retrieve the id of the line and switch 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 where the button is inserted. You can use a compound string to store the element id <tr>

    
27.05.2016 / 13:48