Modal Bootstrap for changing records

Asked

Viewed 893 times

0

Good night, you guys!!

Would anyone know 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 change modal. The call is already occurring, however, my doubt is how to associate database data with modal fields.

Thanks in advance!

  • Are you using ajax or something similar?

  • Hello, @Marcogarcia. Yes, I intend to use it. Actually I already use it at other points of my application.

  • Well, at first, when you make the modal call (you will only have 1 modal on the page), you pass the ID of the line you want to edit. Load the data via ajax, and send to the modal fields. This would be the first part. The user changes the information and sends. Again, call another ajax function, passing the changed data + the ID it edited. End.

  • Cool, @Marcogarcia. But how I associate the values returned from the bank to the fields on screen. I have found some examples on the internet, but very confusing. If you have a link from some example, I can manage. Thanks!!

  • I’ll answer the question... due to Qtd of characters.

2 answers

0


I will assume that you are showing the results in a table...and at the end of each row there is the edit button (which calls the modal), right?

Well, on that button, you’d call the function

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

Where 123 is the registry ID. Within this function, vc executes an ajax, returning the data (JSON, for example) from ID 123. When receiving successfully, you use JSON.parse to turn the JSON return into javascript object.

Going back to your modal, you already leave the fields predefined and configured (and empty), only to receive the data 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>
....

Going back to its JS function, after transforming the return into JSON for object, vc makes a for, within its 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 to be simpler of this form. You already go through all the elements. But I won’t go into detail.

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

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

  • Great, @Marcogarcia!! I will try to follow the logic of your explanation and example to implement in my case. I really appreciate the attention! Back to mark as answered. Thanks!

  • If in doubt, come back here and post an excerpt of the code with the doubt.

  • Good evening, Marco. I came back to say that it worked perfectly. Thank you very much for your support. I basically created a function (with Jquery/Ajax) to be called for value assignment. Already in PHP I made the selection of the data putting the return in an array and later converting to a JSON (echo json_encode($arrayDados)).

  • Oops, wonder Genivaldo.

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 on the registration 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();
}

?>
  • good evening. Thanks for the support too. I reconciled Marcos' instructions with yours and succeeded. Thanks!!

Browser other questions tagged

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