Confirmation for deletion

Asked

Viewed 743 times

0

I have the following problem, I need to validate the deletion of a field, and I am doing this via modal of the globe bootstrap. However the field comes from a table and accurate enough in the modal two information, the client code to be deleted and the type of this client to delete in the database.

Both are on the same page, however I give a include on the page listing in a table all customers.

How do I get this code sent to the modal ?

My codes:

Mymodal:

                                <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                                <div class="modal-dialog" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                            <h4 class="modal-title" id="myModalLabel">Tem certeza que deseja excluir este contato ?</h4>
                                        </div>
                                        <div class="modal-body" align="center">
                                            <form action="C_DeletaCliente.php" method="get">
                                                <?php
                                                $cdCli = $_GET['P_COD_IDENT_CLIEN'];
                                                $tipo = $_GET['P_FLG_TIPOX_CLIEN'];

                                                echo $cdCli+","+$tipo;
                                                ?>
                                                <button type="submit" class="btn btn-default"><a> Sim</a></button>
                                            </form>
                                            <button type="submit" data-dismiss="modal" class="btn btn-default"><a> Não</a></button>
                                        </div>
                                    </div>
                                </div>
                            </div>

Lista Clientes:

    // executa  query de consulta e armazena o resultado devolvido na variável $resultado
$resultado = mysql_query("SELECT COD_IDENT_CLIEN, TXT_NOMEX_CLIEN, FLG_TIPOX_CLIEN, FLG_IDENT_STATU from tbl_CLIENTES ORDER BY FLG_TIPOX_CLIEN, TXT_NOMEX_CLIEN ASC");

// se não existir cargos cadastrados exibe uma mensagem
if (mysql_num_rows($resultado) <= 0) {
    echo "<div class='alert alert-error'>";
    echo "<b>Atenção!</b><br>";
    echo "Não existe clientes cadastrados no momento.";
    echo "</div>";
}

// se existir produtos cadastrados lista-os
else {
    echo "<table class='lista-clientes table table-striped'>";
    echo "<thead>";
    echo "<th>Nome do Cliente</th>";
    echo "<th>Tipo de Cliente</th>";
    echo "<th>Status do Cliente</th>";
    echo "<th>Excluir</th>";
    echo "<th>Alterar</th>";
    echo "<th>Uploads</th>";
    echo "<th>Agenda</th>";
    echo "<th>Publicações</th>";
    echo "<th>Recados</th>";
    echo "</thead>";

    while ($linha = mysql_fetch_array($resultado)) {
        echo "<tr>";
        echo "<td>$linha[1]</td>";
        switch ($linha[2]) {
            case 'F':
                echo "<td>Pessoa Fisica</td>";
                break;

            case 'J':
                echo "<td>Pessoa Juridica</td>";
                break;

            default:
                echo "<td>Não cadastrado</td>";
                break;
        }
                switch (@$linha[FLG_IDENT_STATU]) {
            case 'A':
                echo "<td>Ativo</td>";
                break;

            case 'I':
                echo "<td>Inativo</td>";
                break;

            default:
                echo "<td>Não cadastrado</td>";
                break;
        }
        echo "<td><a href='#myModal2?P_COD_IDENT_CLIEN={$linha[0]}&P_FLG_TIPOX_CLIEN={$linha[2]}' data-toggle=\"modal\" data-target=\"#myModal2\"><i class='icon-remove' ></i></a></td>";
        switch ($linha[2]) {
            case 'F':
                echo "<td><a href='alteraPF.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-pencil' ></i></a></td>";
                break;
            case 'J':
                echo "<td><a href='alteraPJ.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-pencil' ></i></a></td>";
                break;
        }
        echo "<td><a href='uploadCliente.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-upload-alt' ></i></a></td>";
        echo "<td><a href='agendaCliente.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-calendar' ></i></a></td>";
        switch ($linha[2]) {
            case 'F':
                echo "<td><a href='publicacaoPF.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-file' ></i></a></td>";
                break;
            case 'J':
                echo "<td><a href='publicacaoPJ.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-file' ></i></a></td>";
                break;
        }
        echo "<td><a href='listaRecadosClientes.php?P_COD_IDENT_CLIEN={$linha[0]}'><i class='icon-inbox' ></i></a></td>";
        echo "</tr>";
    }

    echo "</table>";
}

The purpose of this question is to try to do something to validate the deletion of the field if there is any more effective way, or easier to develop accepted statements.

  • What do you call this modal? It is an external file or is on the same page?

  • It’s on the same page, and the way to call it is when I click the X button, it fires an event through the data-toggle="modal".

3 answers

1

Create two empty fields in your modal:

<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<input type="hidden" data-name="mdClientCode">
<input type="hidden" data-name="mdClientType">

You can also create these fields automatically via javascript...

Create a file jquery.functions.js and put the following function on it. The file should be included in your code after jQuery.

$.fn.dataByPrefix = function( pr ){
  var d=this.data(), r=new RegExp("^"+pr), ob={};
  for(var k in d) if(r.test(k)) ob[k]=d[k];
  return ob;
};

Function taken from this reply on Soen

Create a call function from your own modal:

$(document).on('click', '[data-toggle="meumodal"]', function(event){
   // Evento padrão do click
   event.preventDefault();

   // Seleciona o modal
   var modal = $( $(this).data('target') );

   // Pega os dados que estão no elemento clicado (a[data-toggle="meumodal"])
   var dados = $(this).dataByPrefix("md");

   // Loop nos dados
   for(i in dados){

     var el = modal.find('input[type="hidden"][data-name=" '+i+' "]');

     // Verifica se tem um input do dado dentro do modal
     // Se não tiver cria-o
     if (el.length == 0){
        el = $('<input />').attr('type','hidden')
                           .attr('data-name', 'i');
        modal.append(el);
     }
     // Atribui o valor a ele
     el.val( dados[i] );
   }

   modal.modal('show');
});

Build the call as follows:

<a 
  href='#myModal2' 
  data-md-client-code='{$linha[0]}' 
  data-md-client-type='{$linha[2]}' 
  data-toggle='meumodal' 
  data-target='#myModal2'
>

Pass the data using the prefix md date, that is to say data-md-minhakey="meu-valor". The prefix md is just a suggestion, you can use the prefix you want.

  • My jquery and via web ? how do I ? and is making a mistake on it @Kaduamaral

  • create a file and call it after linking jQuery

  • It is not calling my modal, the error jquery just however does not appear the modal.

  • Did you change the date-toggle to 'meumodal', or whatever name you gave it? Log in to this chat http://chat.stackexchange.com/rooms/25038/javascript

1


You can use a plugin like Bootbox just implement it into your code.

The call can be made like this

$(document).on('click', '.confirma-delete', function(event){
   // Evento padrão do click
   event.preventDefault();

   // ve se tem titulo
   var title = $(this).data('title');
   var id    = $(this).data('id');
   var tipo  = $(this).data('type');

   var msg = 'Realmente deseja deletar <span class="text-danger">' + title + '</span>?';

   bootbox.confirm(msg, function(res){

     if (res) deletaDados(id, tipo);

   });


});

And in your loop make the links like this:

<a 
  href='#myModal2' 
  data-title='{$linha[1]}' 
  data-id='{$linha[0]}'
  data-type='{$linha[2]}' 
  class='confirma-delete'
>

Example

$(document).on('click', '.confirma-delete', function(event){
   // Evento padrão do click
   event.preventDefault();

   // ve se tem titulo
   var title = $(this).data('title');
   var id    = $(this).data('id');
   var tipo  = $(this).data('type');

   var msg = 'Realmente deseja deletar <span class="text-danger">' + title + '</span>?';

   bootbox.confirm(msg, function(res){

     if (res) {
       // Chama sua função para deletar os dados
       // deletaDados(id, tipo);
       bootbox.alert('Deletado com sucesso!');
     }

   });


});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min.js"></script>

<table class="table">
      <caption>Optional table caption.</caption>
      <thead>
        <tr>
          <th>#</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Username</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">1</th>
          <td>Mark</td>
          <td>Otto</td>
          <td>@mdo</td>
          <td><button class="confirma-delete btn btn-danger" data-title="Mark" data-id="1" data-type="user">x</button></td>
        </tr>
        <tr>
          <th scope="row">2</th>
          <td>Jacob</td>
          <td>Thornton</td>
          <td>@fat</td>
          <td><button class="confirma-delete btn btn-danger" data-title="Jacob" data-id="1" data-type="user">x</button></td>
        </tr>
        <tr>
          <th scope="row">3</th>
          <td>Larry</td>
          <td>the Bird</td>
          <td>@twitter</td>
          <td><button class="confirma-delete btn btn-danger" data-title="Larry" data-id="1" data-type="user">x</button></td>
        </tr>
      </tbody>
    </table>

  • Missing call the bootbox file not ?

  • I put an example there @Renanrodrigues

0

Putting the data in two fields Hidden I believe it works:

<input type="hidden" name="cod_cli" value="<?php echo $_GET['P_COD_IDENT_CLIEN']; ?>">
<input type="hidden" name="tipo_cli" value="<?php echo $_GET['P_FLG_TIPOX_CLIEN']; ?>">

Then just capture in PHP by the method $_POST:

$codigo_cliente = $_POST['cod_cli'];
$tipo_cliente   = $_POST['tipo_cli'];

And erase the dice:

DELETE FROM tbl_CLIENTES 
WHERE  P_FLG_TIPOX_CLIEN='$tipo_cliente'
AND    P_COD_IDENT_CLIEN='$codigo_cliente';

Don’t forget to change the method="get" for method="post".

By the way, there is a better way to do this, via ajax.

  • It did not work, he accuses that the variable has no value, in fact the error ta being in the form of sending, I am not knowing to send the information to the modal..

  • I just need to send the data to the modal, the rest is working perfectly, the problem is to send the data to the modal that is on the same page, review your code because it is not doing what solves my problem.

  • you do not catch post method if send it via get.

Browser other questions tagged

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