Postgresql y Jqgrid Parte II
Buenos días quiero agradecer por esta oportunidad para agregar un nuevo avance con el trabajo del Jqgrid y Postgresql hoy voy a mostrar como:
· Grabar el contenido completo del Grid
· Totalizar al final de una columna
· Buscar un código y mostrarlo en Pantalla
//LIBRERIAS NECESARIAS PARA JQGRID
<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<script src="js/jquery-1.7.2.min.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 type="text/javascript">
$(function(){
//CONFIGURACION DEL FORMATO NUMERICO DEL JQGRID
// $.jgrid.formatter.integer.thousandsSeparator = ',';
$.jgrid.formatter.number.thousandsSeparator = '.';
$.jgrid.formatter.number.decimalSeparator = ',';
$.jgrid.formatter.number.decimalPlaces = 2;
// $.jgrid.formatter.currency.thousandsSeparator = ',';
//Esta funcion permite leer los datos de la tabla centro de costos y mostrarla como si fuera un combo dentro del jqgrid. (El codigo de Centro_Costo.php y Doc_Asociado.php se encuentran en la parte final de la pagina)
var ccosto = (function () {
var list = null;
$.ajax({
async: false,
global: false,
url: 'Centro_Costo.php',
dataType: 'json',
success: function (data) {
list = data;
}
});
return list;
})();
var dasocia = (function () {
var list = null;
$.ajax({
async: false,
global: false,
url: 'Doc_Asociado.php',
dataType: 'json',
success: function (data) {
list = data;
}
});
return list;
})();
$("#grps").jqGrid({
//url:'Carga_Datos.php',
datatype: 'json',
mtype: 'GET',
colNames: ['Id_Registro','Codigo_Cuenta','Centro_Costo', 'Doc_Asoc','Tipo', 'Descripcion', 'Monto'],
colModel: [
{ name: 'Id_Registro', index: 'Id_Registro', width: 100, align: 'left',editable: false},
{ name: 'Codigo_Cuenta', index: 'Codigo_Cuenta', width: 100, align: 'left',editable: true,editrules:{required:true},edittype:"select",editoptions:{dataUrl:'Plan_Cuentas.php'} ,sortable: true, resizable: false},
{ name: 'Centro_Costo', index: 'Centro_Costo', width: 100, align: 'left',editable: true,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: ccosto},sortable: true, resizable: false},
{ name: 'Doc_Asoc', index: 'Doc_Asoc', width: 100, align: 'left',editable: true,editrules:{required:true},edittype:"text"},
{ name: 'Tipo', index: 'Tipo', width: 100, align: 'left',editable: true,editrules:{required:true},edittype:"select",formatter:'select',editoptions: { value: dasocia},sortable: true, resizable: false},
{ name: 'Descripcion', index: 'Descripcion', width: 200, align: 'left',editable: true,editrules:{required:true},edittype:'text'},
{ name: 'Monto', index: 'Monto', width: 200, align: 'left',editable: true, formatter: 'number',editrules:{number:true}},
],
rownumbers:true,
pager: '#pgrps',
rowNum:15,
rowList:[10,25,50,100],
autowidth: true,
// sortname: 'Id_Registro',
// sortorder: 'desc',
viewrecords: true,
width: "98%",
height: "100%",
editurl: "inlineEdit.php",
caption: 'Carga Asientos Contables',
footerrow: true,
cellEdit: true,
cellurl:"otro.php", //Esta es una pagina vacia php
// este codigo permite totalizar al final de la columna Monto.
afterSaveCell: function (rowid, cellname, value) {
if (cellname === 'Monto') {
var sum = jQuery("#grps").jqGrid('getCol', 'Monto', false, 'sum');
jQuery("#grps").jqGrid('footerData','set', {Id_Registro: 'Total:', Monto: sum});
}
},
// Este codigo permite buscar la descripcion del codigo de Cuenta contable al hacer doble en la fila clic el codigo de Funciones.php se encuentra al final de la pagina.
ondblClickRow: function(rowid,iRow,iCol,e){
var myCellData = $('#grps').jqGrid('getCell', rowid, 'Codigo_Cuenta');
$.post('Funciones.php',{Codigo:myCellData},Busca_Texto);
function Busca_Texto(datos)
{
$("#Cuenta").val(datos);
}
} ,
// Totaliza luego de Insertar
afterInsertRow:function() {
var sum = jQuery("#grps").jqGrid('getCol', 'Monto', false, 'sum');
jQuery("#grps").jqGrid('footerData','set', {Id_Registro: 'Total:', Monto: sum});
},
//Totaliza luego de que se encuentra total mente cargado el grid
gridComplete: function(){
var sum = jQuery("#grps").jqGrid('getCol', 'Monto', false, 'sum');
jQuery("#grps").jqGrid('footerData','set', {Id_Registro: 'Total:', Monto: sum});
},
});
jQuery("#grps").jqGrid('navGrid','#pgrps',{edit:false}, //options
{},// edit
{height:280,width:600,reloadAfterSubmit:false,closeAfterAdd:true}, // add options
{reloadAfterSubmit:false}, // del options
{multipleSearch:true,closeAfterSearch: true, closeOnEscape: true}
);
// Este codigo agrega un nuevo botom y permite buscar la descripcion del Codigo de Cuenta Contable.
jQuery("#grps").jqGrid('navButtonAdd','#pgrps',{
caption:"Cuenta",
title:"Cuenta",
onClickButton : function () {
var prueba=0;
var id = jQuery("#grps").jqGrid('getGridParam','selrow');
if (id)
{
var ret = jQuery("#grps").jqGrid('getRowData',id);
var prueba=ret.Codigo_Cuenta;
}
$.getJSON('Funciones.php',{Codigo:prueba},Busca_Texto);
function Busca_Texto(datos)
{
alert(datos);
$("#Cuenta1").html(datos);
}
} ,
});
// Este codigo recorre todo el grid toma todos los registros y los envia a la pagina pruebaz.php donde son grabados.(El codigo de prueba z esta al final de la pagina)
$("#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 que tiene el grid al numero de total_registros
if(!confirm(" Esta seguro de Grabar los asientos?")) {return false;}
else {
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.Codigo_Cuenta+';'+rowData.Centro_Costo+';'+rowData.Doc_Asoc+';'+rowData.Tipo+';'+rowData.Descripcion+';'+rowData.Monto;
z++;
}// cierra el for
var jObject={};
for(i in columns)
{
jObject[i] = columns[i];
}
$.post("pruebaz.php",{jObject: jObject},function(result){alert(result);});
// return false;
} // cierra el confirm
}); // cierra la funcion clic
});
</script>
// codigo html del formulario
<table width="900" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td><a href="index.php?m=1&p=0">Volver al listado</a></td>
</tr>
</table>
<br />
<form action="?m=82" method="post" enctype="application/x-www-form-urlencoded" name="rp" id="rp" onSubmit="return ValidaRP1(this)">
<table width="900" border="0" align="center" cellpadding="3" cellspacing="0" class="srcTabla">
<tr>
<th scope="col" style="text-align:center" >Carga de Asientos </th>
</tr>
<tr>
<td align="center" valign="middle" nowrap="nowrap" bgcolor="#ECECEC">
<table width="100%" border="1" cellspacing="0" cellpadding="5" class="srcTabla">
<tr>
<th scope="col" width="140">Tipo de Asiento </th>
<th scope="col" width="85">Numero</th>
<th scope="col" width="125">Fecha</th>
<th width="492" scope="col">Comentario</th>
</tr>
<tr>
<td height="50" valign="middle" nowrap="nowrap"><div id="Combo_Asiento" style=" float:left">
<select name="Tipo_Asiento" id="Tipo_Asiento">
<option value="ad" title="ad">ad</option>
<option value="b" title="b">b</option>
<option value="cierre" title="cierre">cierre</option>
<option value="n" title="n">n</option>
<option value="p" title="p">p</option>
</select>
</div>
</td>
<td valign="middle" nowrap="nowrap"><input type="text" name="Num_Comprobante" Id="Num_Comprobante" />
</td>
<td valign="middle" nowrap="nowrap"><input name="fecha_Cambio" type="text" id="fecha_Cambio" size="12" maxlength="10" value="" onkeyup = "this.value=formateafecha(this.value);"/>
<img src="images/calendar.png" alt="Elija una fecha" name="cal_x_fecha_reg" width="16" height="16" align="bottom" id="cal_x_fecha_reg" style="cursor:pointer;cursor:hand;" onMouseOver="crearcalendar();" /> </td>
<td valign="middle" nowrap="nowrap"><input name="Comentario" type="text" Id="Comentario" size="70" /></td>
</tr>
</table></td>
</tr>
<tr>
<td bgcolor="#ECECEC"><table width="100%" border="1" cellspacing="0" cellpadding="5">
</table></td>
</tr>
</table>
<br />
<br />
<table id="grps"></table>
<div id="pgrps"></div>
<p> </p>
<p>
<label id="Cuenta1"> </label>
</p>
<div id="boton" align="center">
<input type="BUTTON" id="bedata" value="Grabar Comprobante y Asientos Cargados" />
</div>
</form>
<br/><br/><br/>
***********PAGINAS ADICIONALES**************
CENTRO DE COSTOS.PHP
**-------------------------
<?php
require('funciones/Conectar.php');
$SQL_Funciones ='SELECT "Codigo_Centro","Descripcion_Centro" FROM "Centros_Costo" ORDER BY "Codigo_Centro"';
// $combo = "<select name=Combo_Codigo_Centro";
$combo ='"';
$cierra=';';
$Contador=0;
//echo($SQL_Funciones);
$Data_Funciones_N = $conn->Execute("$SQL_Funciones");
$Total_Registros=$Data_Funciones_N->RecordCount();
while (!$Data_Funciones_N->EOF)
{
$Contador++;
if($Contador<$Total_Registros){$cierra=';';}else{$cierra='';}
$combo.=$Data_Funciones_N->fields[0].':'.utf8_encode($Data_Funciones_N->fields[1]).$cierra;
$Data_Funciones_N->MoveNext();
}
//$combo .= "</select>";
$combo .= '"';
$Data_Funciones_N->Close(); //opcional
echo $combo;
?>
**-------------------------
DOC_ASOCIADO.PHP
**----------------------------------
<?php
require('funciones/Conectar.php');
$SQL_Funciones ='SELECT "Codigo_Documento","Descripcion_Documento" FROM "Tipo_Documento" ORDER BY "Codigo_Documento"';
$combo ='"';
$cierra=';';
$Contador=0;
//echo($SQL_Funciones);
$Data_Funciones_N = $conn->Execute("$SQL_Funciones");
$Total_Registros=$Data_Funciones_N->RecordCount();
while (!$Data_Funciones_N->EOF)
{
$Contador++;
if($Contador<$Total_Registros){$cierra=';';}else{$cierra='';}
$combo.=$Data_Funciones_N->fields[0].':'.utf8_encode($Data_Funciones_N->fields[1]).$cierra;
$Data_Funciones_N->MoveNext();
}
//$combo .= "</select>";
$combo .= '"';
$Data_Funciones_N->Close(); //opcional
echo $combo;
?>
**---------------------------------
FUNCIONES.PHP
**--------------------------
<?php
extract($_POST);
extract($_GET);
$Nombre_cuenta="";
require('funciones/Conectar.php');
$Sql_Inyecta="SELECT".'"Descripcion_Cuenta" FROM "Plan_Cuentas" WHERE "Codigo_Cuenta"=';
$Sql_Valores="('".$_GET['Codigo']."')";
$Sql_Inyecta=($Sql_Inyecta.$Sql_Valores);
$Data_Funciones_N = $conn->Execute("$Sql_Inyecta");
$Nombre_cuenta=$Data_Funciones_N->fields[0];
$Data_Funciones_N->Close(); //opcional
if($_GET['Codigo']==0){$Nombre_cuenta='Sin Cuenta a Buscar';}
print json_encode(utf8_decode($Nombre_cuenta));
?>
**---------------------------
PRUEBAZ.PHP
*---------------------
<?php
extract($_POST);
require('funciones/Conectar.php');
$Control_Errores=0;
//************************* INICIADO CONTROL DE TRANSACCIONES INTELIGENTES*****************************************
$conn->StartTrans();
//*******************************************************************************************************************
foreach($_POST['jObject'] as $row)
{
$columna = explode(";",$row); //separar los datos en posiciones de arreglo
$Sql_Inyecta="INSERT INTO ".'"Asientos"("Codigo_Cuenta", "Codigo_Centro_Costo","Numero_Documento","Codigo_Tipo_Documento","Descripcion_Asiento","Monto_Asiento") VALUES ';
$Sql_Valores="('".$columna[0]."','".$columna[1]."','".$columna[2]."','".$columna[3]."','".$columna[4]."','".$columna[5]."');";
$Sql_Inyecta=($Sql_Inyecta.$Sql_Valores);
if ($conn->Execute($Sql_Inyecta)== false) {$Control_Errores=1;}else{$Sql_Inyecta="";$Sql_Valores="";}
}
$conn->CompleteTrans();
if ($Control_Errores>0) {print_r($Sql_Inyecta.'FALLO CARGA DE REGISTROS');}else{print_r('GRABACION EXITOSA');}
?>
uff que desorden podra ser muy bueno pero no se entiende donde va cada cosa
ResponderEliminar