I am working with DATATABLE, how can I save the current page that I am in, and then return to show the same page?

0

Greetings, I'm new to the community! I hope corrections in case the question is wrongly formulated!

I have data in a Dashboard from a DB that are paginated. I'm using DataTable. When pressing on one of the products I go to the details of it. When I want to go back to the previous view, with the BACK button, I would like to go to the page of the table where I was. If it was understood, could someone give me a hand?

Thank you very much !!

This is the View where I have the table

<link href="<?= base_url(); ?>assets/plugins/bootstrap- 
datepicker/css/datepicker.css" rel="stylesheet" />
<link href="<?= base_url(); ?>assets/plugins/bootstrap-
datepicker/css/datepicker3.css" rel="stylesheet" />
<link href="<?= base_url(); ?>assets/plugins/parsley/src/parsley.css" 
rel="stylesheet" />
<link href="<?= base_url(); ?>assets/plugins/DataTables-1.9.4/css/data-
table." rel="stylesheet" />
<style type="text/css">

tr{cursor:pointer;}
.stats-info > h4, .stats-info > p{
    color: black !important;
}

</style>
<div id="content" class="content">

<?php if($data['rol'] <= 3){ ?> 


<div class="panel panel-inverse">
    <div class="panel-heading">
        <div class="panel-heading-btn">
            <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
            <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-success" data-click="panel-reload"><i class="fa fa-repeat"></i></a>
            <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>               
        </div>
        <h4 class="panel-title">Formularios Mantenimiento</h4>
    </div>
    <div class="panel-body">
        <div class="panel-body">
            <div class="row">
                <div class="col-xs-4"><button id="nueva" type="button" class="btn btn-primary m-l-20 m-t-20">Nueva Solicitud</button></div>
                <div class="col-xs-8">
                    <div class="col-sm-2 col-xs-2 ui-sortable" style='background-color:#FFBABA;'>
                        <div class="widget widget-stats" >
                            <div class="stats-info">
                                <h4>Pendientes</h4>
                                <p><?=$estados['pendientes']?></p>  
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-2 col-xs-2 ui-sortable" style='background-color:#FFE8AD;'>
                        <div class="widget widget-stats" >
                            <div class="stats-info">
                                <h4>En Proceso</h4>
                                <p><?=$estados['proceso']?></p> 
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-2 col-xs-2 ui-sortable" style='background-color:#94DDCF;'>
                        <div class="widget widget-stats" >
                            <div class="stats-info">
                                <h4>Cerrados</h4>
                                <p><?=$estados['cerrado']?></p> 
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <br>
            <div class="table-responsive">
                <table id="data-table" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>Nº</th>
                            <th>Fecha Registro</th>
                            <th>Origen</th>
                            <th>Cierre</th>
                            <th>Fecha Cierre</th>
                            <th>Estado</th>
                            <?php if($data['rol'] == 1): ?>
                            <th>Eliminar</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                    <?php 
                        foreach ($solicitudes as $solicitud) 
                        {
                            $fechaR = new DateTime($solicitud->fecha);

                            if (isset($solicitud->fecha_cierre)) 
                            {
                                $fechaC = new DateTime($solicitud->fecha_cierre);
                                $fechaC = date_format($fechaC,'d-m-Y');
                            }
                            else
                                $fechaC = '';

                            $estado = $solicitud->estado;
                            if($estado == 0) $estado = "<td style='background-color:#FFBABA;'>Pendiente</td>";
                            elseif ($estado == 1) $estado = "<td style='background-color:#FFE8AD;'>En Proceso</td>";
                            else $estado = "<td style='background-color:#94DDCF;'>Cerrado</td>";

                            echo "<tr id='".$solicitud->id_solicitud."'>";
                            echo "<td>".$solicitud->id_solicitud."</td>";
                            echo "<td>".date_format($fechaR,'d-m-Y')."</td>";                               
                            echo "<td>".$solicitud->origen."</td>";
                            echo "<td>".$solicitud->nombre.", ".$solicitud->apellido."</td>";
                            echo "<td>".$fechaC."</td>";                                
                            echo $estado;
                            if($data['rol'] == 1)
                                if($solicitud->estado == 0)
                                    echo "<td class='action'>"."<a class='btn btn-danger btn-icon btn-circle btn-sm btn-delete'><i class='fa fa-times'></i></a>"."</td>";
                                else
                                    echo "<td></td>";
                            echo "</tr>";
                        }
                    ?>                          
                    </tbody>
                </table>
            </div>
        </div>
    </div>                
</div>
<?php } ?>  
</div>

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" id="modal_delete">
   <div class="modal-dialog modal-sm" 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">Eliminar orden</h4>
      </div>
      <div class="modal-body">
        ¿Está seguro que desea eliminar la orden?
      </div>
      <div class="modal-footer">
        <form method="POST" action="<?=base_url()?>insumos/eliminar">
            <input type="hidden" name="solicitud" id="solicitud">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
            <button type="submit" class="btn btn-primary">Aceptar</button>
        </form>
      </div>
    </div>
  </div>
</div>



<?php $this->load->view('view_scripts') ?>


<script src="<?= base_url(); ?>assets/plugins/bootstrap-
datepicker/js/bootstrap-datepicker.js"></script>
<script src="<?= base_url(); ?>assets/js/form-plugins.js"></script>
<script src="<?= base_url(); ?>assets/plugins/parsley/dist/parsley.js">
</script>
<script src="<?= base_url(); ?>assets/plugins/DataTables-
1.9.4/js/jquery.dataTables.js"></script>
<script src="<?= base_url(); ?>assets/plugins/DataTables-1.9.4/js/data-
table.js"></script>
<script src="<?= base_url(); ?>assets/plugins/gritter/js/jquery.gritter.js">
</script>
<script src="<?= base_url(); ?>assets/js/apps.min.js"></script>


<script>
$(document).ready(function() {
    var detalles = <?php echo json_encode($detalles); ?>;


    App.init();
    FormPlugins.init();

    //cambio el item activo en el sidebar
    $("#ULsidebar > li").removeClass("active");
    $("#LIinsumos").addClass("active");


    if(<?=$mensaje;?>== 1){
        $.gritter.add({
            title: "Exito",
            text: "Registrado con exito"
        });
    }
    if(<?=$mensaje;?>!= 1 && <?=$mensaje;?>!= 0) {
        $.gritter.add({
            title: "Exito",
            text: "Registrado con exito. Nro de Solicitud: "+<?=$mensaje;?>
        });
    }


    $("#nueva").click(function(){
        location.href="<?=base_url()?>insumos/nuevaSolicitud";
    });


    $('#data-table tbody').on('click', 'tr > td', function () {
        if($(this).hasClass('action'))
        {
            $("#solicitud").val($(this).parent().attr("id"));
            $('#modal_delete').modal('show');
        }
        else

        location.href = '<?= base_url(); ?>insumos/form/'+ $(this).parent().attr('id');                 
    });
    $('#modal_delete').on('hidden.bs.modal', function (){ $("#solicitud").val("");});



});
</script>
<style type="text/css">
#formulario{  border-left: 1px solid #E4E4E4; }
</style>    
</body>
</html>

This is the Data-Table.Js

$.extend( true, $.fn.dataTable.defaults, {
"sDom": "<'row'<'col-md-6 col-sm-6'l><'col-md-6 col-sm-6'f>r>t<'row'<'col-md-6 col-sm-6'i><'col-md-6 col-sm-6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
    "sLengthMenu": "_MENU_ filas por página"
}
} );



/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );


$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
    "iStart":         oSettings._iDisplayStart,
    "iEnd":           oSettings.fnDisplayEnd(),
    "iLength":        oSettings._iDisplayLength,
    "iTotal":         oSettings.fnRecordsTotal(),
    "iFilteredTotal": oSettings.fnRecordsDisplay(),
    "iPage":          oSettings._iDisplayLength === -1 ?
        0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
    "iTotalPages":    oSettings._iDisplayLength === -1 ?
        0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};


/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap": {
    "fnInit": function( oSettings, nPaging, fnDraw ) {
        var oLang = oSettings.oLanguage.oPaginate;
        var fnClickHandler = function ( e ) {
            e.preventDefault();
            if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                fnDraw( oSettings );
            }
        };

        $(nPaging).addClass('pagination').append(
            '<ul class="pagination m-t-0 m-b-0">'+
                '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+
                '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+
            '</ul>'
        );
        var els = $('a', nPaging);
        $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
        $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
    },

    "fnUpdate": function ( oSettings, fnDraw ) {
        var iListLength = 5;
        var oPaging = oSettings.oInstance.fnPagingInfo();
        var an = oSettings.aanFeatures.p;
        var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

        if ( oPaging.iTotalPages < iListLength) {
            iStart = 1;
            iEnd = oPaging.iTotalPages;
        }
        else if ( oPaging.iPage <= iHalf ) {
            iStart = 1;
            iEnd = iListLength;
        } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
            iStart = oPaging.iTotalPages - iListLength + 1;
            iEnd = oPaging.iTotalPages;
        } else {
            iStart = oPaging.iPage - iHalf + 1;
            iEnd = iStart + iListLength - 1;
        }

        for ( i=0, ien=an.length ; i<ien ; i++ ) {
            // Remove the middle elements
            $('li:gt(0)', an[i]).filter(':not(:last)').remove();

            // Add the new list items and their event handlers
            for ( j=iStart ; j<=iEnd ; j++ ) {
                sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                $('<li '+sClass+'><a href="#">'+j+'</a></li>')
                    .insertBefore( $('li:last', an[i])[0] )
                    .bind('click', function (e) {
                        console.log((parseInt($('a', this).text(),10)));
                        e.preventDefault();
                        oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                        fnDraw( oSettings );
                    } );
            }

            // Add / remove disabled classes from the static elements
            if ( oPaging.iPage === 0 ) {
                $('li:first', an[i]).addClass('disabled');
            } else {
                $('li:first', an[i]).removeClass('disabled');
            }

            if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                $('li:last', an[i]).addClass('disabled');
            } else {
                $('li:last', an[i]).removeClass('disabled');
            }
        }
    }
}
} );


 /*
 * TableTools Bootstrap compatibility
 * Required TableTools 2.1+
 */
 if ( $.fn.DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, $.fn.DataTable.TableTools.classes, {
    "container": "DTTT btn-group",
    "buttons": {
        "normal": "btn",
        "disabled": "disabled"
    },
    "collection": {
        "container": "DTTT_dropdown dropdown-menu",
        "buttons": {
            "normal": "",
            "disabled": "disabled"
        }
    },
    "print": {
        "info": "DTTT_print_info modal"
    },
    "select": {
        "row": "active"
    }
} );
// Have the collection use a bootstrap compatible dropdown
$.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
    "collection": {
        "container": "ul",
        "button": "li",
        "liner": "a"
    }
} );
 }


/* Table initialisation */
$(document).ready(function() {
$('#data-table').dataTable( {
    "sDom": "<'row'<'col-md-6 col-sm-6'l><'col-md-6 col-sm-6'f>r>t<'row'<'col-md-6 col-sm-6'i><'col-md-6 col-sm-6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sLengthMenu": "_MENU_ filas por página"
    }
});

$('#data-table2').dataTable( {
    "sDom": "<'row'<'col-md-6 col-sm-6'l><'col-md-6 col-sm-6'f>r>t<'row'<'col-md-6 col-sm-6'i><'col-md-6 col-sm-6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sLengthMenu": "_MENU_ filas por página"
    },
    "bSort": false
});
} );

In this View I show product details

<link href="<?= base_url(); ?>assets/plugins/bootstrap-
datepicker/css/datepicker.css" rel="stylesheet" />
<link href="<?= base_url(); ?>assets/plugins/bootstrap-
datepicker/css/datepicker3.css" rel="stylesheet" />
<link href="<?= base_url(); ?>assets/plugins/parsley/src/parsley.css" 
rel="stylesheet" />
<link href="<?= base_url(); ?>assets/plugins/DataTables-1.9.4/css/data-
table.css" rel="stylesheet" />
<style type="text/css">
tr{cursor:pointer;}
@media print
{
    .panel-body{
        margin-top: -90px;
        margin-bottom: 0px;
    }       
    .form-horizontal.form-bordered .form-group>div{
        padding: 4px !important;
    }
}
</style>

<!-- begin #content -->
<div id="content" class="content">
<?php if($data['rol'] <= 3) { ?>
<div class="panel panel-inverse no-print">              
        <div class="panel-body">
            <ul class="list-inline pull-right" style="margin:0;">
                <li><button type="button" class="btn btn-sm btn-primary m-l-10 volver no-print" style="margin-top: -15px;">Volver</button></li>
                <li><div style="background-color: #AAA; width:1px; height: 30px;"></div></li>                   
                <li><a href="<?= base_url(); ?>insumos/imprimir/<?=$id_solicitud?>"><i class="fa fa-print fa-3x"></i></a></li>
            </ul>
        </div>
    </div>

 <div class="panel panel-inverse">
    <div class="panel-heading no-print">
        <div class="panel-heading-btn">
            <a href="javascript:;" class="btn btn-xs btn-icon btn-circle 
btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
            <a href="javascript:;" class="btn btn-xs btn-icon btn-circle 
btn-success" data-click="panel-reload"><i class="fa fa-repeat"></i></a>
            <a href="javascript:;" class="btn btn-xs btn-icon btn-circle 
btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>                
        </div>
        <h4 class="panel-title">Solicitud de Formulario</h4>
    </div>
    <div class="panel-body">
        <form class="form-horizontal form-bordered" action="<?= base_url(); 
?>insumos/ingresoUpdate" method="POST" data-parsley-validate="true">    
            <input type="hidden" name="id_solicitud" value="<?
=$id_solicitud?>">

            <div class="form-group">
                <label class="col-md-4 control-label ui-sortable">Nº 
Solicitud</label>
                <div class="col-md-8 ui-sortable">
                    <h3 style="margin-top:0;"><?=$id_solicitud?></h3>
                </div>
            </div>


            <div class="form-group">
                <label class="col-md-4 control-label ui-
sortable">Detalle</label>
                <div class="col-md-8 ui-sortable">

                <?php foreach ($detalles as $detalle): 

                    $chk = ''; 
                    if($detalle->estado == 1) 
                        $chk = 'checked'; 

                    if(isset($detalle->fecha_cierre))
                    {
                        $fechaC = new DateTime($detalle->fecha_cierre); 
                        $fechaC = date_format($fechaC,'d-m-Y');
                    }
                    else
                        $fechaC = '';

                ?>

                    <input name="id_detalle[]" type="hidden" id="id_detalle" 
value="<?=$detalle->id_insumo?>">
                    <div class="form-group m-r-10" style="margin-top: 
80px;">
                        <input type="checkbox" <?=$chk?> 
name="inputVerificado[]" value="<?=$detalle->id_insumo?>"/>
                        <label> <?=$detalle->descripcion?> | Días: <?            
=$detalle->dias?> </label>
                        <br>
                        <br>
                        <div class="input-group date" id="datepicker-
autoClose<?=$detalle->id_insumo?>" data-date-format="dd-mm-yyyy" 
style="padding:0;">
                            <input id="inputFechaCierre" 
name="inputFechaCierre[]" type="text" class="form-control" value="<?
=$fechaC?>" placeholder="Fecha Ciere Pedido" /><span class="input-group-
addon"><i class="fa fa-calendar"></i></span>
                        </div>      
                        <br>                    
                        <input type="text" placeholder="Comentario" 
class="form-control" name="inputComentario[]" id="inputComentario" value="<?
=$detalle->comentarios?>" />
                    </div>

                <?php endforeach; ?>    


                </div>


                <div class="form-group no-print" style="display:none">
                    <label class="col-md-4 control-label ui-sortable">Cerrar 
Formulario</label>
                    <div class="col-md-8 ui-sortable">
                        <input type="checkbox" id="cerrarF" name="cerrarF">
                    </div>
                </div>
            </div>




            <div class="form-group no-print">
                <label class="col-md-4 control-label ui-sortable"></label>
                <div class="col-md-8 ui-sortable">
                    <button type="submit" id="btnGuardar" class="btn btn-sm btn-primary m-r-5">Guardar</button>                             
                    <button type="button" class="btn btn-sm btn-primary m-l-10 volver">Volver</button>              
                    <button type="button" id="btnCerrar" class="btn btn-sm btn-default m-l-10">Cerrar</button>              
                </div>
            </div>      
        </form>
    </div>
</div>  

<?php } ?>  


</div>

<?php $this->load->view('view_scripts') ?>

<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<script src="<?= base_url(); ?>assets/plugins/bootstrap-
datepicker/js/bootstrap-datepicker.js"></script>
<script src="<?= base_url(); ?>assets/js/form-plugins.js"></script>
<script src="<?= base_url(); ?>assets/plugins/parsley/dist/parsley.js">
</script>
<script src="<?= base_url(); ?>assets/plugins/DataTables-
1.9.4/js/jquery.dataTables.js"></script>
<script src="<?= base_url(); ?>assets/plugins/DataTables-1.9.4/js/data-
table.js"></script>
<script src="<?= base_url(); ?>assets/js/apps.min.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->

<script>
$(document).ready(function() {


    App.init();
    FormPlugins.init();
    //cambio el item activo en el sidebar
    $("#ULsidebar > li").removeClass("active");
    $("#LIinsumos").addClass("active");




    $('.volver').click(function () {
        console.log((parseInt($('a', this).text(),10)));
        location.href = '<?= base_url(); ?>insumos';
    });

    $("#LIinsumos").addClass("active");

    if('<?=$estado_solicitud?>' == '2')
    {
        $('#cerrarF').prop('checked', true);

        $("#inputFechaOrden").prop('disabled', true);
        $("#btnGuardar").prop('disabled', true);
        $("#btnCerrar").prop('disabled', true);

        $("checkbox").each(function(){
            $(this).prop('disabled', true);
        });
        $("input").each(function(){
            $(this).prop('disabled', true);
        });



        $('form').on('submit', function(event) {
            event.preventDefault();
            alert("NO SE PUEDE EDITAR");
        });

    }

    $("#btnCerrar").click(function(){
        $("#cerrarF").prop('checked', true);
        var enviar = true;

        /*$("textarea").each(function(){
            if(this.value=='')
            {
                alert("Debe completar todos los campos");
                enviar = false;
            }               
        });*/

        if(enviar == true)
        {
            $("form").submit();
        }
    });
});

    

    
asked by FabriC 24.10.2017 в 15:43
source

2 answers

1

For the solution to your problem I would do something like this, I hope it works for you, I gladly resolve any doubts you have:

In the function where you give click to the detail button, it would simply capture the current page and save it using the localstorage of the browser:

//Función para ver el detalle
$("#verdetalle").click(function(){
    //Capturas página actual
    var pagina_actual = table.page();

    //Guardamos la página actual en el local storage
    localStorage.setItem("pagina_actual", pagina_actual);
});

Then in the function where you generate the table it would capture the saved value, ask if it exists and in case there is one that would give the order to the table to show that page. (This obviously has to be after printing all the data again from the table)

//capturamos la página guardada anteriormente
var pagina = localStorage.getItem("pagina_actual");

// Pregutnamos si existe el item
if (pagina != undefined) {
    //Decimos a la table que cargue la página requerida
    table.page(pagina).draw('page');;

    //Eliminamos el item para que no genere conflicto a la hora de dar click en otro botón detalle
    localStorage.removeItem("pagina_actual");
}

It is worth clarifying that table is the variable where you keep the line $('#example').DataTable();

Another solution could be to show the detail in a modal

    
answered by 24.10.2017 в 16:19
0

If I have understood the question correctly, the solution is the following:

$('#mytable').DataTable({
stateSave: true,
...
})

stateSave saves the view of the table exactly as you left it the last time you visited the page. You can make F5 leave the view, re-enter, etc ... and the table will appear the same.

    
answered by 26.06.2018 в 17:13