martes, 17 de septiembre de 2013

Personalizar o Programar el comportamiento de los botones (Editar / Eliminar) de la barra de Navegacion (Pager) del Jqgrid con una funcion.



Buenas tardes el día de hoy voy a publicar como personalizar el comportamiento de dos botones (Editar / Eliminar) de la barra de Navegacion  del Jqgrid, mediante la función processAddEdit  la cual ejecutara  algún código que necesitemos.

Bien esto es bastante sencillo:


Paso 1:
Definimos nuestro   Pager o Barra de Navegacion como ustedes lo deseen llamar:

jQuery("#grps1").jqGrid('navGrid','#pgrps1',{del:true,add:false,edit:false,search: false,refresh: false}, //options

Paso 2:
Personalizamos el boton "del"  invocando la function llamada processAddEdit

jQuery("#grps1").jqGrid('navGrid','#pgrps1',{del:true,add:false,edit:false,search: false,refresh: false}, //options{},// edit{}, //add
{ //del      
//beforeSubmit:processAddEdit, (Puedes llamar la function Antes del Submit)
afterSubmit: processAddEdit, (O Puedes llamar la function despues del Submit)
closeAfterAdd: true,
closeAfterEdit: true,
reloadAfterSubmit:false,
recreateForm:true
},{}//search);

Paso 3:
Contruimos la function con el codigo que necesitamos:

function processAddEdit(response, postdata) 
{
//(Obtenemos el valor  de las columnas de la fila que fue borrada: ) por ejemplo:

var sel_id = jQuery("#grps1").jqGrid('getGridParam', 'selrow');
 
var Unidades_solicitada=jQuery("#grps1").jqGrid('getCell', sel_id, 'Unidades_Solicitada');

var Peso_Solicitado =jQuery("#grps1").jqGrid('getCell', sel_id, 'Peso_Solicitado');

//Realizamos alguna operación:

Var total =( Unidades_solicitada* Peso_Solicitado);

Alert(total);
   
} // cierra   function processAddEdit     



Ahora si deseamos trabajar con el boton editar seria algo asi:

jQuery("#grps").jqGrid('navGrid','#pgrps',{}, //options
{
        afterSubmit:processAddEdit,
        closeAfterAdd: true,
        closeAfterEdit: true,
        reloadAfterSubmit:false,
        recreateForm:true
    },
{reloadAfterSubmit:false,closeAfterAdd:true,recreateForm:true}, // add options
{reloadAfterSubmit:false}, // del options
{multipleSearch:true,closeAfterSearch: true, closeOnEscape: true}
);
function processAddEdit(response, postdata)
{

//Observa como podemos manipular el contenido de las columnas de la fila afectada con
postdata

          
                  $.getJSON('Busca_Kilos.php',{Codigo:postdata.Articulo},Busca_Texto);
                  function Busca_Texto(datos1)
                     {
                         $.getJSON('Busca_Cantidades.php',{Codigo:postdata.Articulo},Busca_Texto);
                         function Busca_Texto(datos)
                            {
                                var z1 =(parseInt(datos1)*postdata.Cantidad*parseInt(datos));
                                $("#grps").jqGrid('setCell',postdata.id,'Peso_Total', z1);
                           
                                var z =(parseInt(datos)*postdata.Cantidad);
                                $("#grps").jqGrid('setCell',postdata.id,'Total_Unidades', z);
                            }// cierra $.getJSON('Busca_Cantidades.php'
                     
                     
                     }// cierra function Busca_Texto(datos)
                       
                  return [true,"",]; // importante devolver falso o verdadero en funcion del resultado del codigo
}// cierra function processAddEdit


 ******CODIGO COMPLETO************


$("#grps1").jqGrid({
url:'Sube_Salida.php?filtro='+<?php echo $_GET['rp'];?>,
datatype: 'json',
mtype: 'GET',
 colNames: ['Articulo','Presentacion','Medida_Item_Solicitada','Unidades_Solicitada','Peso_Solicitado','Lote','Fecha_Vencimiento'],
          colModel: [
{name: 'Articulo', index: 'Articulo', width: 80, align: 'left',editable: false,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: darticulo},sortable: true},
{name: 'Presentacion', index: 'Presentacion', width: 80, align: 'left',editable: false,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: dpresentacion},sortable: true},
{name: 'Medida_Item_Solicitada',  index: 'Medida_Item_Solicitada',  width: 85, align: 'left',editable: true,editrules:{number:true},formatter: 'number',edittype:"text"},
{name: 'Unidades_Solicitada', index: 'Unidades_Solicitada', width: 80, align: 'left',editable: true,editrules:{number:true},formatter: 'number',edittype:"text"},
{name: 'Peso_Solicitado',   index: 'Peso_Solicitado',   width: 80, align: 'left',editable: false,editrules:{number:true},formatter: 'number',edittype:"text"},
{name: 'Lote', index: 'Lote', width: 80, align: 'left',editable: false,editrules:{required:true},formatter:'text',edittype:"text"},
{name: 'Fecha_Vencimiento', index: 'Fecha_Vencimiento', width: 50, align: 'center', editable:false,editrules:{required:true},formatter: 'text', formatoptions: {newformat: 'd-m-Y'}, datefmt: 'd-M-Y'},
  ],

    gridview: true,
    rownumbers:true,
    pager: '#pgrps1',
    rowNum:200,
    rowList:[200],
    autowidth: true,
    viewrecords: true,
    width: "98%",
    height: "100%",
    editurl: "someurl.php",
    caption: 'ITEMS A SER DESPACHADOS',
    footerrow: true,
    cellEdit: true,
    cellurl:"otro.php",  
   
      gridComplete: function(){
              var sum = jQuery("#grps1").jqGrid('getCol', 'Medida_Item_Solicitada', false, 'sum');
              var sum1 = jQuery("#grps1").jqGrid('getCol', 'Unidades_Solicitada', false, 'sum');
              var sum2 = jQuery("#grps1").jqGrid('getCol', 'Peso_Solicitado', false, 'sum');
              $(this).jqGrid('footerData','set',{Medida_Item_Solicitada: sum, Unidades_Solicitada: sum1,Peso_Solicitado: sum2});
        },
   

  });// Aqui cierra el Jqgrid
$("#grps1")







jQuery("#grps1").jqGrid('navGrid','#pgrps1',{del:true,add:false,edit:false,search: false,refresh: false}, //options
{},// edit
{}, //add
{ //del       //beforeSubmit:processAddEdit,
        afterSubmit: processAddEdit,
        closeAfterAdd: true,
        closeAfterEdit: true,
        reloadAfterSubmit:false,
        recreateForm:true
},
{}//search
);// Aqui cierra el Pager o Barra de Navegacion

function processAddEdit(response, postdata) {
var sel_id = jQuery("#grps1").jqGrid('getGridParam', 'selrow');
var IdArticulo = jQuery("#grps1").jqGrid('getCell', sel_id, 'Articulo');
var Medida_Item =jQuery("#grps1").jqGrid('getCell', sel_id, 'Medida_Item_Solicitada');
var Unidades_solicitada=jQuery("#grps1").jqGrid('getCell', sel_id, 'Unidades_Solicitada');
var Peso_Solicitado =jQuery("#grps1").jqGrid('getCell', sel_id, 'Peso_Solicitado');
var Lote_solicitado =jQuery("#grps1").jqGrid('getCell', sel_id, 'Lote');
var Fecha =jQuery("#grps1").jqGrid('getCell', sel_id, 'Fecha_Vencimiento');

var Contador_Articulo =0;

//alert(Fecha);
var anio=Fecha.substr(6,4);
var mes =Fecha.substr(3,2);
var dia =Fecha.substr(0,2);



   var rows = jQuery("#grps1").getDataIDs();
   for(a=0;a<rows.length;a++)
     {
       row=jQuery("#grps1").getRowData(rows[a]);
       var anio_comparar =row.Fecha_Vencimiento.substr(6,4);
       var mes_comparar =row.Fecha_Vencimiento.substr(3,2);
       var dia_comparar =row.Fecha_Vencimiento.substr(0,2);
       if(row.Articulo==IdArticulo && eval(anio_comparar)>=eval(anio) && eval(mes_comparar)>=eval(mes) && eval(dia_comparar)>eval(dia))
         {
          Contador_Articulo++;
         }// cierra if
   
     }// cierra for
 
    if(Contador_Articulo==0)
       {
        var a=0;
        var rows = jQuery("#grps").getDataIDs();
        for(a=0;a<rows.length;a++)
         {
              row=jQuery("#grps").getRowData(rows[a]);
             if(row.Articulo==IdArticulo && row.Lote==Lote_solicitado && row.Vencimiento==Fecha)
               {
             $("#grps").jqGrid('setCell', rows[a], 'Existencia_Actual_Medida_Item', (eval(row.Existencia_Actual_Medida_Item)+eval(Medida_Item)));
             $("#grps").jqGrid('setCell', rows[a], 'Existencia_Unidades', (eval(row.Existencia_Unidades)+eval(Unidades_solicitada)));
             $("#grps").jqGrid('setCell', rows[a], 'Existencia_Peso', (eval(row.Existencia_Peso)+eval(Peso_Solicitado)));
             //$("#grps").jqGrid('setCell', rows[a], 'Cantidad', (eval(row.Cantidad)-eval(Medida_Item)));
               }// cierra if
   
        }// cierra for
          return [true,"",];
       }// cierra condicion Contador_Articulo==0
    if(Contador_Articulo>0){return [false,"Debe Borrar El Articulo con Fecha vencimiento mas lejana ",null];}
       
   
} // cierra   function processAddEdit  
 

miércoles, 28 de agosto de 2013

Jquery Jqgrid Almacenamiento de un vector de respuesta Ajax en una variable para uso posterior.



Jquery  Jqgrid Almacenamiento de un vector  de respuesta Ajax en una variable para  uso posterior.

Este es un procedimiento bastante sencillo primero establecemos la variable destino y el código Ajax:

var Prueba = $.ajax({
                                                 type: 'POST',      
                                                 url: "Busca_Existencia_Total.php",
                                                 data: {BuscaArticulo: row.Articulo, Lote:row.Lote,Vencimiento:row.Fecha_Vencimiento},
                                                 dataType: 'html',
                                                 context: document.body,
                                                 global: false,
                                                 async:false,
                                                 success: function(data){return data;}}).responseText;

Paso 2: Estructuramos la salida de la variable:

var obj1 = jQuery.parseJSON(Prueba);


Paso 3:Obtenemos los datos:

Cantidad_Producto=(obj1['Total']);
                                                                                                                                               Unidades_A_Restar=(obj1['Unidades']);
                                                                                                                                               Peso_Actual=(obj1['Peso']);


Por último el código del Busca_Existencia_Total.php para que veas como se estructura el vector:


<?php
extract($_POST);
extract($_GET);
$Kilos= array();
require('funciones/Conectar.php');
               
                                 
                                 $Sql_Inyecta=' SELECT  "Existencia_Actual_Medida_Item" as "Total", "Existencia_Actual_Unidad" as "Total_Unidades" ,
"Existencia_Actual_Peso" as "Total_Peso" FROM "Inventario_Actual" WHERE  "Inventario_Actual"."Id_Articulo" IN'."(".$_POST['BuscaArticulo'].") and ".'"Lote" IN'."('".$_POST['Lote']."') and ".'"Fecha_Vencimiento"='."'".$_POST['Vencimiento']."'";

                                 
                                  $Sql_Inyecta=($Sql_Inyecta.$Sql_Valores.$Agrupa);
                                   $Data_Funciones_N = $conn->Execute("$Sql_Inyecta");
                                  $Kilos=array('Total'=>$Data_Funciones_N->fields[0],'Unidades'=>$Data_Funciones_N->fields[1],'Peso'=>$Data_Funciones_N->fields[2]);
                                  $Data_Funciones_N->Close(); //opcional
                                  print json_encode($Kilos);

  ?>





jueves, 1 de agosto de 2013

Validar cualquier campo presente en el colModel del Jqgrid con una función personalizada JavaScript



Para validar cualquier campo presente en el colModel del Jqgrid con una función personalizada es bastante sencillo:

Pasó 1 Crea la función

Usemos una función que valide si la persona escribió el valor o si escribió letras en vez de números:

(Importante esta función debes colocarla antes del cuerpo del Jqgrid, fijate en el código completo del ejemplo más abajo)

function fol(value, colname) {

                if(!isNaN(value))
                                                                                {
                         if(parseFloat(value) == 0 )
                                                                                                 {
                               return[false,"No puede Grabar el Valor 0"];
                           } else {
                               return[true, ""];
                           }
                      } else {
                              return [false, "Debe Escribir solo numeros"];
                      }
                                                                               
                };



Pasó 2:
Luego en la línea correspondiente dentro del jqgrid llamas la función:
Importante los parámetros de editrules debe estar así 

editrules:{custom:true, number:true, custom_func:fol}


{name: 'Cantidad', index: 'Cantidad', width: 80, align: 'left',editable: true,editrules:{custom:true, number:true, custom_func:fol},formatter: 'number',edittype:'text'},



CODIGO COMPLETO

 

<!--

<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link rel="stylesheet" type="text/css" media="screen" href="text/css/ui-lightness/jquery-ui-1.10.1.custom.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="text/js/jquery-ui-1.10.1.custom.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script language="javascript" src="scripts/sisminalve.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript" src="scripts/validar.js"></script>
<script type="text/javascript" src="text/js/jquery.ui.datepicker-es.js"></script>

<?php
extract($_POST);
extract($_GET);
        include('funciones/Conectar.php');//Conexion a la Base de datos
        include('funciones/FuncionesListBox.php');
        include('funciones/globales.php');
        include('funciones/librerias.php');
     
?>
 <script>
 function formafecha(fecha)
 {
 Anio =fecha.substr(0,4);
 mes=fecha.substr(5,2);
 dia=fecha.substr(8,2);
 fecha=dia+"/"+mes+"/"+Anio;
 return (fecha);
 }

$(function() {
$( "#fechaR" ).datepicker();

});
</script>
<script type="text/javascript">
$(function(){
 var identificador_rubro=$('#Renglon_Oculto').val();
 var Identifica_accion =<?php echo $_GET['rp'];?>;
 var selICol; //iCol of selected cell
 var selIRow; //iRow of selected cell





$("#enlace").click(function() {
     location.href = this.href; // ir al link
});


  $.jgrid.formatter.integer.thousandsSeparator = ',';
        $.jgrid.formatter.number.thousandsSeparator = '.';
         $.jgrid.formatter.number.decimalSeparator = ',';
         $.jgrid.formatter.number.decimalPlaces = 2;
         $.jgrid.formatter.currency.thousandsSeparator = '.';
          $.jgrid.formatter.currency.decimalSeparator = ',';
          $.jgrid.formatter.currency.decimalPlaces = 2;
       
       
var darticulo = (function () {
            var list = null;
         
            $.ajax({
                async: false,
                global: false,
                url: 'Articulo.php',
                dataType: 'json',
                success: function (data) {
                    list = data;
                }
            });

            return list;
})();

var drubro = (function () {
            var list = null;
         
            $.ajax({
                async: false,
                global: false,
                url: 'Rubro.php',
                dataType: 'json',
                success: function (data) {
                    list = data;
                }
            });

            return list;
})();


 function fol(value, colname) {

 
                    if(!isNaN(value))
                      {
                         if(parseFloat(value) == 0 )
                           {
                               return[false,"No puede Grabar el Valor 0"];
                           } else {
                               return[true, ""];
                           }
                      } else {
                              return [false, "Debe Escribir solo numeros"];
                      }
                 
                };





$("#grps").jqGrid({
url:'Carga_Datos.php?filtro='+<?php echo $_GET['rp'];?>,
datatype: 'json',
mtype: 'GET',
  colNames: ['Rubro','Articulo','Lote','Cantidad','Peso_Total','Fecha_Vencimiento','Observaciones'],
          colModel: [
{ name: 'Rubro', index: 'Rubro', width: 80 ,align: 'left',editable: true,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: drubro,dataEvents: [{type: 'change',
                 fn: function(e)
                {
                     
                // RUTINA PARA CREAR LA RELACION EN LOS COMBOS    EL CODIGO MEDIDA_FILTRO.PHP SE ENCUENTRA EN LA PARTE FINAL DE LA PAGINA. 
                
                          $("#grps").setColProp("Articulo", {editoptions: { value: darticulo}});
                           var v = parseInt($(e.target).val(), 10);
                              $.ajax({
                             url: "Articulo_Filtrado.php?Id="+v,
                             dataType: "html",
                             success: function(data)
                             {
                        
                        
                             if ($(e.target).is(".FormElement"))
                                {
                             
                                   var form = $(e.target).closest("form.FormGrid");                                                   
                                   $("select#Articulo.FormElement", form[0]).html(data);
                               
                                }else{
                                 // inline editing
                                  var row = $(e.target).closest("tr.jqgrow");
                                  var rowId = row.attr("id");
                                   $("select#" + rowId + "_Articulo", row[0]).html(data);
                            
                            
                              }// cierra el if
                          
                           }// cierra funcion de comprobacion de exito
                       
                       
                        }); // cierra el ajax
                    
                }//cierra funcion e
 
           }]//cierra evento change
 
 
     }// cierra editoptions
 
 
 
     }, // cierra la linea de sistema



{name: 'Articulo', index: 'Articulo', width: 80, align: 'left',editable: true,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: darticulo},sortable: true},
{name: 'Lote', index: 'Lote', width: 80, align: 'left',editable: true,editrules:{required:true},formatter:'text',edittype:"text"},
{name: 'Cantidad', index: 'Cantidad', width: 80, align: 'left',editable: true,editrules:{custom:true, number:true, custom_func:fol},formatter: 'number',edittype:'text'},

{name: 'Peso_Total', index: 'Peso_Total', width: 80, align: 'left',editable: false,editrules:{custom:true, number:true, custom_func:fol},formatter: 'number',edittype:'text',editoptions:{dataEvents: [
    {
        type: 'keypress',
        fn: function(e) {
            var key = e.charCode || e.keyCode; // to support all browsers
             if (key == 13){setTimeout("jQuery('#grps').editCell(" + selIRow + " + 1, " + selICol + ", true);", 100);}
             if((key < 48 || key > 57) &&   key !== 46 && key !== 44 && key !== 8 &&  key !== 37 && key !== 39){ return false;}
        }// cierra la funcion e
    }// cierra el control del keypress
 
    ] 
     }// cierra editoptions
     }, // cierra la linea de sistema
 
 {name: 'Fecha_Vencimiento', index: 'Fecha_Vencimiento', width: 50, align: 'center', editable: true,editrules:{required:true},formatter: 'text', editoptions:{size:20,
                  dataInit:function(el){
                        $(el).datepicker({dateFormat:'dd/mm/yy'});
                  },
                  defaultValue: function(){
                    var currentTime = new Date();
                    var month = parseInt(currentTime.getMonth() + 1);
                    month = month <= 9 ? "0"+month : month;
                    var day = currentTime.getDate();
                    day = day <= 9 ? "0"+day : day;
                    var year = currentTime.getFullYear();
                    return day+"/"+month + "/"+year;
                  }
                }
              },
 {name: 'Observaciones', index: 'Observaciones', width: 80, align: 'left',editable: true,editrules:{required:true},formatter:'text',edittype:"text"},
  ],





    rownumbers:true,
    pager: '#pgrps',
    rowNum:10,
    rowList:[10,25,50,100],
    autowidth: true,
    viewrecords: true,
    width: "98%",
    height: "100%",
    editurl: "someurl.php",
    caption: 'Carga Asientos Contables',
    footerrow: true,
    //cellEdit: true,
    //cellurl:"otro.php", 


afterInsertRow:function(rowid,rowdata,rowelem) {




                  var ret = jQuery("#grps").jqGrid('getRowData', rowid);
                  $.getJSON('Busca_Kilos.php',{Codigo:ret.Articulo},Busca_Texto);
                  function Busca_Texto(datos)
                     {
                      var z =(parseInt(datos)*ret.Cantidad);
                      $("#grps").jqGrid('setCell',rowid,'Peso_Total', z);
                  }
  

        },





  });


 
jQuery("#grps").jqGrid('navGrid','#pgrps',{}, //options
{
        afterSubmit:processAddEdit,
        closeAfterAdd: true,
        closeAfterEdit: true,
        reloadAfterSubmit:false,
        recreateForm:true
    },
//{reloadAfterSubmit:false,closeAfterEdit:true,recreateForm:true},// edit
{reloadAfterSubmit:false,closeAfterAdd:true,recreateForm:true}, // add options
{reloadAfterSubmit:false}, // del options
{multipleSearch:true,closeAfterSearch: true, closeOnEscape: true}
);
function processAddEdit(response, postdata) {
                  $.getJSON('Busca_Kilos.php',{Codigo:postdata.Articulo},Busca_Texto);
                  function Busca_Texto(datos)
                     {
                      var z =(parseInt(datos)*postdata.Cantidad);
                      $("#grps").jqGrid('setCell',postdata.id,'Peso_Total', z);
                     }
                  return [true,"",];
}

$("#bedata").click(function()
        {
                  // CODIGO MUY IMPORTANTE SIN EL CUAL NO SE GRABARAN TODAS LAS FILAS DEL GRID
                     var total_registros =jQuery("#grps").jqGrid('getGridParam', 'records');// lee el numero total de filas a recorrer
                     jQuery("#grps").setGridParam({ rowNum: total_registros }).trigger('reloadGrid');// cambia el numero de filas por defecto que tiene el grid

     
        //jQuery("#grps").jqGrid('excelExport',{tag:"pdf","url":"querygrid.php"});
           
                if(!confirm(" Esta seguro  de Grabar los Registros?"))
                {

                    return false;
                }else{
             
                     var busca_error =0;
                      var mensaje ="";
                   
                     var Identifica_Usuario=$('#Id_Usuario').val();
                     var proveedor=$('#Id_Proveedor option:selected').val();
                     var Almacen = $('#Id_Almacen option:selected').val();
                     var Fecha = $('#fechaR').val();
                     var Factura = $("#Factura_Nota").val();
                     var cantidad = $("#grps tbody").find("tr").length;


                     if (cantidad==1){busca_error=2;mensaje="No Puede Grabar Registros en blanco";}
                     if (proveedor==""){busca_error=1;mensaje="Proveedor";}
                     if (Almacen==""){busca_error=1;mensaje="Almacen";}
                     if (Fecha==""){busca_error=1;mensaje="Fecha";}
                     if ($("#Factura_Nota").val()==""){busca_error=1;mensaje="Factura Nota Entrega";}
                 
                 
                 
                 
                 

if(busca_error==0)
{                 
                        var z=0;
                     var texto ="";
                     var columns = new Array ();
                     var lista = jQuery("#grps").getDataIDs();
                     for(i=0;i<lista.length;i++)
                        {
                            rowData=jQuery("#grps").getRowData(lista[i]);
                            columns[z]=rowData.Articulo+';'+rowData.Lote+';'+parseInt(rowData.Peso_Total)+';'+parseInt(rowData.Cantidad)+';'+rowData.Fecha_Vencimiento+';'+rowData.Observaciones;
                            z++;
                       }// cierra el for

 
    var jObject={};
    for(i in columns)
    {
        jObject[i] = columns[i];
    }
 

         
                      $.post("Graba.php",{jObject:  jObject,proveedor:proveedor,Almacen:Almacen,Fecha:Fecha,Factura:Factura,Identifica_Usuario:Identifica_Usuario},function(result)
                         {
                         alert(result);
                         $("#enlace").click();
                         });
                         // return false;
                     

}else{

if (busca_error==1){alert('Ingrese un Valor para el Campo '+mensaje);}
if (busca_error==2){alert(mensaje);}
}




                     }   // cierra el confirm 
                 
                 
                      
        });  // cierra la funcion clic
     
     



     
});
</script>
--!>