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>
--!>


lunes, 15 de julio de 2013

Como colocar un calendario (datepicker) dentro del Jqgrid . (Postgres, php,Jqgrid,Jquery, datepicker)



Buenas Días el día de hoy voy e demostrar como so coloca un calendario en el jqgrid (Jqgrid +datepicker)




Realmente es bastante sencillo basta con colocar  esta referencia 

<script type="text/javascript" src="js/ui.datepicker.js"></script>


Y luego agregas este codigo al campo de tipo fecha que quieres trabajar.

{name: 'Fecha', index: 'Fecha', 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;
                  }
                }
              },


                                                                      CODIGO COMPLETO



 <?php if (!isset($_SESSION["mapa"])){?>
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<br/>
    <table width="400" border="0" align="center" cellpadding="5" cellspacing="0">
  <tr>
    <td align="center" background="images/blue.png"><strong class="Titulos">Debe Entrar con un usuario valido</strong></td>
  </tr>
  <tr>
    <td align="center"><a href="index.php" class="menu">Entrar</a></td>
  </tr>
</table>
<?php } else{ ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento sin t&iacute;tulo</title>


<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>

<!--  DEBES INCLUIR ESTA LIBRERIA PARA PODER UTILIZAR EL CALENDARIO-->

<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();
$( "#fecha_Cambio" ).datepicker();
$( "#Fecha_Desde" ).datepicker();
$( "#Fecha_Hasta" ).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


 $('#Combo_Plantilla').bind('change',function(){
              var plantilla=$('#Plantilla_Id option:selected').val();
              $("#grps").jqGrid('setGridParam',{url:'Sube_Plantilla.php?Plantilla='+plantilla,datatype:'json',mtype: 'GET'}).trigger('reloadGrid');
  
              //----------------------
            
              $("#grps").setColProp("Rubro_des", {editoptions: { value: drubro}});
                             $.ajax({
                             url: "Rubro_Filtrado.php?Id="+plantilla,
                             dataType: "html",
                             success: function(data)
                             {
                         
                         
                             if ($(e.target).is(".FormElement"))
                                {
                              
                                   var form = $(e.target).closest("form.FormGrid");                                                    
                                   $("select#Rubro_des.FormElement", form[0]).html(data);
                                
                                }else{
                                 // inline editing
                                  var row = $(e.target).closest("tr.jqgrow");
                                  var rowId = row.attr("id");
                                   $("select#" + rowId + "_Rubro_des", row[0]).html(data);
                             
                             
                              }// cierra el if
                           
                           }// cierra funcion de comprobacion de exito
                        
                        
                        }); // cierra el ajax
                      
            
            
            
            
              //------------------------
            
            
            
            });  





 if(Identifica_accion!=0)
 {


 $.getJSON('Busca_Data.php',{Num_Reque:Identifica_accion},function(solicitud){  
      
             var plantilla=(solicitud.Plantilla_Id);
            //$('select[id="Tipo_solicitud_Id"] option:selected').val(solicitud.Tipo_solicitud_Id);
          
            $('#Tipo_solicitud_Id').val(solicitud.Tipo_solicitud_Id);
            $('#Status_decision_Id').val(solicitud.Status_Decision_Id);
            $('#Plantilla_Id').val(solicitud.Plantilla_Id);
            $('#Unidad_requerente_Id').val(solicitud.Unidad_requerente_Id);
            //$('#Unidad_requerente_Id_a option:selected').val(solicitud.Unidad_requerente_Id_a);
            $('#fechaR').val(formafecha(solicitud.Solicitud_maestro_status_fecha));
            $('#fecha_Cambio').val(formafecha(solicitud.Solicitud_maestro_fecha));
            $('#Num_Reque').val(solicitud.Solicitud_Numero);
            $('#Fecha_Desde').val(formafecha(solicitud.Fecha_Desde));
            $('#Fecha_Hasta').val(formafecha(solicitud.Fecha_Hasta));
            $('#Matricula').val(solicitud.Matricula);
            $('#Oculto_Reque').val(solicitud.Solicitud_maestro_Id);
          

     //----------------------
            
              $("#grps").setColProp("Rubro_des", {editoptions: { value: drubro}});
                             $.ajax({
                             url: "Rubro_Filtrado.php?Id="+plantilla,
                             dataType: "html",
                             success: function(data)
                             {
                         
                         
                             if ($(e.target).is(".FormElement"))
                                {
                              
                                   var form = $(e.target).closest("form.FormGrid");                                                    
                                   $("select#Rubro_des.FormElement", form[0]).html(data);
                                
                                }else{
                                 // inline editing
                                  var row = $(e.target).closest("tr.jqgrow");
                                  var rowId = row.attr("id");
                                   $("select#" + rowId + "_Rubro_des", row[0]).html(data);
                             
                             
                              }// cierra el if
                           
                           }// cierra funcion de comprobacion de exito
                        
                        
                        }); // cierra el ajax
                      
              //------------------------

        });// cierra getJSON
      

 }// cierra el if identifica_accion



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


         $.jgrid.formatter.currency.thousandsSeparator = '.';
          $.jgrid.formatter.currency.decimalSeparator = ',';
          $.jgrid.formatter.currency.decimalPlaces = 2;

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

            return list;
        })();




$("#grps").jqGrid({
url:'Carga_Datos.php?filtro='+<?php echo $_GET['rp'];?>,
datatype: 'json',
mtype: 'GET',
  colNames: ['Cantidad','Unidad_medida_Des','Rubro_des','Costo','Fecha'],
          colModel: [
     { name: 'Cantidad', index: 'Cantidad', width: 80, align: 'left',editable: true,editrules:{required:true,number:true},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: 'Unidad_medida_Des', index: 'Unidad_medida_Des', width: 80, align: 'left',editable: false,editrules:{required:true},formatter:'text',edittype:"text"},

 { name: 'Rubro_des', index: 'Rubro_des', width: 80, align: 'left',editable: false,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: drubro},sortable: true}, 

    
 { name: 'Costo', index: 'Costo', width: 80, align: 'left',editable:false,editrules:{required:true,currency:true},formatter: 'currency',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  
    
     // ESTE CODIGO TE PERMITIRA AGREGAR UN CALENDARIO EN TU FORMULARIO DE CARGA
      

{name: 'Fecha', index: 'Fecha', 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;
                  }
                }
              },
    

      ],

  
    
    rownumbers:true,
    pager: '#pgrps',
    rowNum:100,
    rowList:[10,25,50,100],
    autowidth: true,
    viewrecords: true,
    width: "98%",
    height: "100%",
    editurl: "someurl.php",
    caption: 'Carga de Requisiciones',
    footerrow: true,
  
beforeEditCell : function(rowid, cellname, value, iRow, iCol)
{
    selICol = iCol;
    selIRow = iRow;
},


afterSaveCell: function (rowid, cellname, value,iRow, iCol) {
                    if (cellname === 'Cantidad') {
                        var sum = jQuery("#grps").jqGrid('getCol', 'Cantidad', false, 'sum');
                        jQuery("#grps").jqGrid('footerData','set', {Unidad_medida_Des: 'Total:', Cantidad: sum});
                    }

                    if (cellname === 'Costo') {
                        var sum1 = jQuery("#grps").jqGrid('getCol', 'Costo', false, 'sum');
                        jQuery("#grps").jqGrid('footerData','set', {Unidad_medida_Des: 'Total:', Costo: sum1});
                    }


                },
      

afterInsertRow:function() {
             var sum = jQuery("#grps").jqGrid('getCol', 'Cantidad', false, 'sum');
             var sum1 = jQuery("#grps").jqGrid('getCol', 'Costo', false, 'sum');
               jQuery("#grps").jqGrid('footerData','set', {Unidad_medida_Des: 'Total:', Cantidad: sum});
             jQuery("#grps").jqGrid('footerData','set', {Unidad_medida_Des: 'Total:', Costo: sum1});
        },
 
gridComplete: function(){
             var sum = jQuery("#grps").jqGrid('getCol', 'Cantidad', false, 'sum');
             var sum1 = jQuery("#grps").jqGrid('getCol', 'Costo', false, 'sum');
             jQuery("#grps").jqGrid('footerData','set', {Unidad_medida_Des: 'Total:', Cantidad: sum});
             jQuery("#grps").jqGrid('footerData','set', {Unidad_medida_Des: 'Total:', Costo: sum1});
        },

  });

jQuery("#grps").jqGrid('navGrid','#pgrps',{}, //options
{height:280,width:600,reloadAfterSubmit:false,closeAfterEdit:true},// edit
{height:280,width:600,reloadAfterSubmit:false,closeAfterAdd:true}, // add options
{reloadAfterSubmit:false}, // del options
{multipleSearch:true,closeAfterSearch: true, closeOnEscape: 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

      
  
            
                if(!confirm(" Esta seguro  de Grabar la Requisicion?"))
                {

                    return false;
                }else{
                
                     var Identifica_Usuario=$('#Id_Usuario').val();
                     var busca_error =0;
                     var mensaje ="";
                     var plantilla=$('#Plantilla_Id option:selected').val();
                     var Tipo_Requisicion = $('#Tipo_solicitud_Id option:selected').val();
                     var status = $('#Status_decision_Id option:selected').val();
                     var Fecha = $('#fechaR').val();
                     var Num_r =$('#Oculto_Reque').val();
                     var Num_r1 =$('#Num_Reque').val();
                     var Unidad =$('#Unidad_requerente_Id option:selected').val();
                     var Fecha_Solicitud = $('#fecha_Cambio').val();
                     var Fecha_Desde = $('#Fecha_Desde').val();
                     var Fecha_Hasta = $('#Fecha_Hasta').val();
                     var Matricula =$('#Matricula').val();
                     cantidad = $("#grps tbody").find("tr").length;


                     if (cantidad==1){busca_error=2;mensaje="No Puede Grabar Registros en blanco";}
                     if (Fecha_Solicitud==""){busca_error=1;mensaje="Fecha_Solicitud";}
                     if (Fecha_Desde==""){busca_error=1;mensaje="Fecha_Desde";}
                     if (Fecha_Hasta==""){busca_error=1;mensaje="Fecha_Hasta";}
                     if ($("#Num_Reque").val()==""){busca_error=1;mensaje="Numero Requisicion";}
                     if ($("#Status_decision_Id option:selected").text()=="Seleccione"){busca_error=1;mensaje="Status Requisicion";}
                     if (Fecha==""){busca_error=1;mensaje="Fecha Transcripcion";}
                     //if (Num_r==""){busca_error=1;mensaje="Numero Requisicion";}
                     if (Matricula==""){busca_error=1;mensaje="Matricula";}
                     if ($("#Unidad_requerente_Id option:selected").text()=="Seleccione"){busca_error=1;mensaje="Unidad";}
                     if ($("#Tipo_solicitud_Id option:selected").text()=="Seleccione"){busca_error=1;mensaje="Tipo de Requisicion";}
                     if ($("#Plantilla_Id option:selected").text()=="Seleccione"){busca_error=1;mensaje="Tipo de Plantilla";}
                    
                    
                  

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]=parseInt(rowData.Cantidad)+';'+rowData.Rubro_des+';'+rowData.Costo;
                            z++;
                       }// cierra el for

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

          
                      $.post("Graba.php",{jObject:  jObject,status:status,Fecha:Fecha,Num_r:Num_r,plantilla:plantilla,Unidad:Unidad,Fecha_Solicitud:Fecha_Solicitud,Fecha_Desde:Fecha_Desde,Fecha_Hasta:Fecha_Hasta,Tipo_Requisicion:Tipo_Requisicion,Identifica_accion:Identifica_accion,Fecha_Desde:Fecha_Desde,Fecha_Hasta:Fecha_Hasta,Matricula:Matricula,Num_r1:Num_r1,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>
</head>





      


<body>

<table width="900" border="0" align="center" cellpadding="5" cellspacing="0">
  <tr>
    <td><a href="index.php?m=1&amp;p=0" id='enlace' name='enlace'>Volver al listado</a></td>
  </tr>
</table>
<br />
<form id="Forma_Solicitud" name="Forma_Solicitud" method="post" action="Solicitud.php">






<div id="Tabla"align="center">
  <p>&nbsp;</p>
  <table width="1013" border="1" align="center" cellpadding="3" cellspacing="0" class="srcTabla">
  <tr>
    <td colspan="9" align="center" valign="middle" nowrap="nowrap" bgcolor="#ECECEC"><div align="center"><strong>SOLICITUD DE REQUISICION </strong></div></td>
  </tr>
  <tr>
    <td><div align="left"><strong>Plantilla</strong></div></td>
    <td><span style=" float:left">
      <div id="Combo_Plantilla" style=" float:left"><?php LlenarCombo('"Plantilla_Id","Titulo_Plantilla"', 'Plantilla', 'Seleccione','Plantilla_Id') ?></div>
    </span></td>
    <td width="94"><strong>Tipo Requision:</strong></td>
    <td width="74"><strong><span style=" float:left">
      <?php LlenarCombo('"Tipo_solicitud_Id","Tipo_solicitud_Des"', 'Tipo_solicitud', 'Seleccione','Tipo_solicitud_Id') ?>
    </span></strong></td>
    <td colspan="2"><strong>Status Requisicion </strong></td>
    <td><div id="Combo_Status" style=" float:left"><?php LlenarCombo('"Status_decision_Id","Status_decision_Des"', 'Status_decision', 'Seleccione','Status_decision_Id') ?>
      </div></td>
    <td width="124"><strong>Fecha Transcripcion:</strong></td>
    <td width="148"><input  name="fechaR" type="text" id="fechaR"   />

</td>
  </tr>
  <tr>
    <td width="104"><strong>Numero Requisicion:</strong></td>
    <td width="146"><input type="text" name="Num_Reque" id="Num_Reque" />
    <div id="Combo_Solicitante" style=" float:left"></div>    </td>
    <td><span style=" float:left">
     <div id="Combo_Unidad" style=" float:left"></div>
    </span><strong>Unidad </strong></td>
    <td><span style=" float:left">
      <?php LlenarCombo('"Unidad_requerente_Id","Unidad_requerente_Des"', 'Unidad_requerente', 'Seleccione','Unidad_requerente_Id') ?>
    </span></td>
    <td width="75"><strong>Matricula</strong></td>
    <td width="86"><input type="text" name="Matricula" Id="Matricula" /></td>
    <td width="88"><strong>Fecha de Solicitud:</strong></td>
    <td colspan="2"><input name="fecha_Cambio" type="text" id="fecha_Cambio" />
    
      </td>
  </tr>
  <tr>
    <td><strong>Periodo:</strong></td>
    <td colspan="2"><span style=" float:left">
    
    </span><strong>Fecha Desde:</strong></td>
    <td><input name="Fecha_Desde" type="text" id="Fecha_Desde" />
       </td>
    <td colspan="4"><strong>Fecha Hasta</strong>:
      <input type="hidden" name="Oculto_Reque"  Id="Oculto_Reque"/>
      <div id="Combo_Tipo_Requision" style=" float:left"></div>      <div id="Combo_Renglon" style=" float:left"></div></td>
    <td><input name="Fecha_Hasta" type="text" id="Fecha_Hasta" />
      </td>
  </tr>
</table>
  <p>
    <input type="hidden" name="Renglon_Oculto" Id="Renglon_Oculto" value="<?php echo($_POST['Renglon_Oculto']); ?>" />
    <input type="hidden" name="Id_Renglon_Oculto" Id="Id_Renglon_Oculto"  value="<?php echo($_POST['Id_Renglon_Oculto']); ?>" />
  </p>
</div>


  <table id="grps"></table>
  <p>&nbsp;</p>
  <div id="pgrps"></div>
 
<div id="boton" align="center">
<input type="BUTTON" id="bedata" value="Grabar Requisicion" />
</div>
</form>
</body>

</html>
<?php }//Cierra Nivel de Seguridad ?>
<p>
    <input type="hidden" name="Id_Usuario"  Id="Id_Usuario" value="<?php echo $_SESSION["nombres"].' '.$_SESSION["apellidos"]?>"/>
  </p>