Modal Bootstrap for changing records

0

Good evening, everyone !!

Would anyone know of a basic example on how to create a modal bootstrap for changing records? I have an on-screen listing that has a link to call the modal change. The call is already occurring, but my question is how to associate bank data with modal fields.

Thank you in advance!

    
asked by anonymous 27.02.2018 / 01:33

2 answers

0

I'll assume you're showing the results in a table ... and, at the end of each row there's the edit button (which calls the modal), right?

Well, on this button, you would call the function

<button onclick="modal_edit(123)">Editar</button>

Where 123 is the record ID. Within this function, you run an ajax, returning the data (JSON, for example) of ID 123. Upon successful receiving, you use JSON.parse to transform the JSON return into a javascript object.

Returning to your modal, you already leave the fields pre-defined and configured (and empty), only to receive the data coming from the previous step.

...
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<input type="text" name="address" id="address">
<button type="submit">Enviar</button>
....

Returning to your JS function, after transforming the return in JSON to object, you make a for, within your function.

...
for(var i in response){
    #vou supor que vc esteja usando jQuery
    #response[i].name, email e address são os nomes das colunas no seu banco
    $("#name").val(response[i].name)
    $("#email").val(response[i].email)
    $("#address").val(response[i].address)
}
...
  

You could dismiss the for, but I believe it to be simpler than this.   form. You already scroll through all the elements. But I will not go into details.

When the user clicks the "Send" button, it processes another ajax (or can send via normal http) the changed fields, also taking the ID (123, in the case), for you to do UPDATE.

(I just did it in a simple way, without many examples and assuming many things I hope it helps)

    
27.02.2018 / 02:00
0

I did so, I hope it helps. List contents of a table. HTML

<table id="TabEvolucao" class="table table-hover" cellspacing="0" width="100%">
                    <thead>
                        <tr >                                           
                            <th>#</th>
                            <th width="100px">Data</th>
                            <th>Descrição</th>
                            <th>Usuário</th>
                            <th>Ativo</th>            
                        </tr>
                    </thead>
                     <tfoot>
                        <tr >                                           
                            <th>#</th>
                            <th width="100px">Data</th>
                            <th>Descrição</th>
                            <th>Usuário</th>
                            <th>Ativo</th>            
                        </tr>
                    </tfoot>
                    <tbody>
                    </tbody>
                </table>

Datatables with active SELECT.

$('#TabEvolucao').DataTable({
        "processing" : true, 
        "select": true      ,
        "ajax" : {
            "type" : "POST",
            "url" : "estrutura/tabevolucao.php",
            dataSrc : '',
            "data" : function(d){
                d.idcliente = vlsidcliente;
                d.acao = "select";
                }
        },
        "columns" : [   {"data" : "id"}, 
                        {"data" : "data"}, 
                        {"data" : "descricao"},
                        {"data" : "nome"},
                        {"data" : "ativo"}
                    ],      
        "aaSorting": [[1,'asc']],
         "iDisplayLength": 7,
         "bFilter": true,
         "aaSorting": [[1,'asc']],              
        "language": {               
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página ",
            "sLoadingRecords": "Carregando...",
            "sProcessing": "Processando...",
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
                },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }   

    });

Click the register to open MODAL by passing the ID. JAVA

var TabEvolucao = $('#TabEvolucao').DataTable();
    TabEvolucao
        .on( 'select', function ( e, dt, type, indexes ) {
            var rowData = TabEvolucao.rows( indexes ).data().toArray();                     
            var id = rowData["0"].id; 
            document.getElementById('idevolucao').value = id;
            $('#modalVWEVOLUCAO').data('id', id).modal('show');     

        } );

MODAL

<div class="modal fade" id="myModalUpdateEVO" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-sm modal-notify modal-danger" role="document">
                <!--Content-->
                <div class="modal-content text-center">
                    <!--Header-->
                    <div class="modal-header d-flex justify-content-center">
                        <p class="heading">Continuar com atualização?</p>
                    </div>

                    <!--Body-->
                    <div class="modal-body">

                        <i class="fa fa-times fa-4x animated rotateIn"></i>

                    </div>

                    <!--Footer-->
                    <div class="modal-footer flex-center">

                        <button type="button" class="btn  btn-outline-secondary-modal" id="btnUpdateYesEVO" href="#">Sim</button>
                        <button type="button" class="btn  btn-primary-modal waves-effect" data-dismiss="modal">Não</button>

                    </div>
                </div>
                <!--/.Content-->
            </div>
        </div>

Button action JAVA

$('#btnUpdateYesEVO').click(function () {
        var id = $('#myModalUpdateEVO').data('id');         
        var idevolucao = document.getElementById('idevolucao').value;
        var descricaoevolucao = document.getElementById('descricaoevolucao').value;
        var boatao = document.getElementById('acaobotaoevolucao').value;
        var iduser=$('#iduser').val();

        if(boatao == 'DESATIVAR'){

            $.post('estrutura/excluirevolucao.php',{
                    acao:'delete',
                    id:id,
                    user_id:iduser                  
                    },function(r) { 
                       var m = jQuery.parseJSON(r);        
                       if (m.success) {

                        $('#myModalUpdateEVO').modal('hide');
                        toastr["success"](m.msg);             
                        $("#listevolucao").load(location.href + " #listevolucao>", "");     

                       } else {            
                        toastr["error"](m.msg);
                        $('#myModalUpdateEVO').modal('hide');

                       }             
                    });
        }

PHP

<?php 
include("../includes/config.php");
if ($_POST) {
    $data = array('success' => '0',
                  'msg' => 'Ocorreu um erro, nada foi excluído!');

        $id         = (int) $_POST['id'];
        $user_id    = (int) $_POST['user_id'];
        $ip         = "";
        $navegaodr  = "";


        if ($_POST['acao'] == 'delete' && is_int($id)) {


             //GRAVA LOG
            $data               = date("y-m-d H:i:s"); 
            $modulo             = "EVOLUCAO";
            $acao               = "DESATIVOU REGISTRO: " . $id ;

            $rs = $con->prepare("INSERT INTO logs_acessos VALUES (:user_id, :ip, :data, :navegaodr, :modulo, :acao)");
            $rs->bindParam(':user_id', $user_id );
            $rs->bindParam(':ip', $ip );
            $rs->bindParam(':data', $data );
            $rs->bindParam(':navegaodr', $navegaodr );
            $rs->bindParam(':modulo', $modulo );
            $rs->bindParam(':acao', $acao );       
            $result = $rs->execute();           

            $select = "update evolucao set ativo = 'N' where id = " . $id;
            $rs = $con->prepare($select);
            if($rs->execute()){     
                if($rs->rowCount() > 0){
                    $data = array('success' => '1',
                                 'msg' => 'Registro desativado com sucesso!');

                }           
            }


        }
   echo json_encode($data);
   die();
}

?>
    
27.02.2018 / 02:21