Foros del Web » Programando para Internet » PHP »

jqGrid y PHP pierden las variables

Estas en el tema de jqGrid y PHP pierden las variables en el foro de PHP en Foros del Web. Hola a todos Por favor solicito su amable ayuda porque ya tengo 4 semanas intentando solucionar esto y no funciona. Tengo el siguiente script PHP ...
  #1 (permalink)  
Antiguo 27/10/2011, 15:09
Avatar de romangus  
Fecha de Ingreso: octubre-2011
Mensajes: 3
Antigüedad: 12 años, 5 meses
Puntos: 0
Sonrisa jqGrid y PHP pierden las variables

Hola a todos

Por favor solicito su amable ayuda porque ya tengo 4 semanas intentando solucionar esto y no funciona.

Tengo el siguiente script PHP y uso las librerias jqGrid para mostrar una tabla maestra con tablas detalle, para ello implementé un ejemplo de aquí: [URL="http://www.trirand.net/demophp.aspx"]www.trirand.net/demophp.aspx[/URL]
específicamente el del menú azul de la izquierda Selection->Master Detail On Select

Este es el código, el cual también pueden ver en la pág. del ejemplo y consta de 3 archivos: default.php, grid.php y detail.php

default.php es este:


Código HTML:
<?php
require_once '../../../tabs.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>jqGrid PHP Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" media="screen" href="../../../themes/redmond/jquery-ui-1.8.2.custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="../../../themes/ui.jqgrid.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="../../../themes/ui.multiselect.css" />
    <style type="text">
        html, body {
        margin: 0;            /* Remove body margin/padding */
        padding: 0;
        overflow: hidden;    /* Remove scroll bars on browser window */
        font-size: 75%;
        }
    </style>
    <script src="../../../js/jquery.js" type="text/javascript"></script>
    <script src="../../../js/i18n/grid.locale-en.js" type="text/javascript"></script>
    <script type="text/javascript">
    $.jgrid.no_legacy_api = true;
    $.jgrid.useJSON = true;
    </script>
    <script src="../../../js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script src="../../../js/jquery-ui-custom.min.js" type="text/javascript"></script>
  </head>
  <body>
      <div>
          <b>Customers</b>
          <?php include ("grid.php");?>
      </div>
      <div>
          <b>Orders for the selected Customer</b>
          <?php include ("detail.php");?>
      </div>
      <br/>
      <?php tabs(array("grid.php","detail.php"));?>
   </body>
</html> 
grid.php es este:

Código PHP:
<?php
require_once '../../../jq-config.php';
// include the jqGrid Class
require_once ABSPATH."php/jqGrid.php";
// include the driver class
require_once ABSPATH."php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand 'SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers';
// Set the table to where you update the data
$grid->table 'customers';
// Set output format to json
$grid->dataType 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    
"rowNum"=>10,
    
"rowList"=>array(10,20,30),
    
"sortname"=>"CustomerID"
));
$grid->setColProperty('CustomerID', array("label"=>"ID""width"=>50));
$selectorder = <<<ORDER
function(rowid, selected)
{
    if(rowid != null) {
        jQuery("#detail").jqGrid('setGridParam',{postData:{CustomerID:rowid}});
        jQuery("#detail").trigger("reloadGrid");
    }
}
ORDER;
$grid->setGridEvent('onSelectRow'$selectorder);
// Enable navigator
$grid->navigator true;
// Enable only editing
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// Enjoy
$grid->renderGrid('#grid','#pager',truenullnulltrue,true);
$conn null;
?>
detail.php es este:

Código PHP:
<?php
require_once '../../../jq-config.php';
// include the jqGrid Class
require_once ABSPATH."php/jqGrid.php";
// include the driver class
require_once ABSPATH."php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Get the needed parameters passed from the main grid
if(isset ($_REQUEST["CustomerID"]))
    
$rowid jqGridUtils::Strip($_REQUEST["CustomerID"]);
else
    
$rowid "";
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand "SELECT OrderID, RequiredDate, ShipName, ShipCity, Freight FROM orders WHERE CustomerID= ?";
// set the ouput format to json
$grid->dataType 'json';
// Let the grid create the model
$grid->setColModel(null, array(&$rowid));
// Set the url from where we obtain the data
$grid->setUrl('detail.php');
// Set some grid options
$grid->setGridOptions(array(
    
"rowNum"=>10,
    
"footerrow"=>true,
    
"userDataOnFooter"=>true,
    
"sortname"=>"OrderID",
    
"height"=>110
    
));
// Change some property of the field(s)
$grid->setColProperty("RequiredDate", array(
    
"formatter"=>"date",
    
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y"),
    
"search"=>false
    
)
);
$grid->navigator true;
$grid->setNavOptions('navigator', array("excel"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// Enjoy
$summaryrow = array("Freight"=>array("Freight"=>"SUM"));
$grid->renderGrid("#detail","#pgdetail"true$summaryrow, array(&$rowid), true,true);
$conn null;
?>
Ya lo implementé y funciona de maravilla así como está.
Ahora mi problema está en el archivo grid.php en la linea 15:
Código PHP:
$grid->SelectCommand 'SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers'
Porque ahí necesito tomar los registros de un CustomerID específico, y dicho CustomerID se lo tengo que pasar con una variable.
Me ocurre que funciona si pongo como fijo el CustomerID, así:
Código PHP:
$grid->SelectCommand 'SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers WHERE CustomerID=3'
pero en la práctica eso no me sirve porque yo necesito esto:
Código PHP:
$grid->SelectCommand "SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers WHERE CustomerID='".$cliente."'; 
Pero no funciona, me manda error o no devuelve registros.
Observo que al parecer el script hace las cosas 2 veces y lo hace bien una vez y las variables conservan su valor, pero la segunda vez truena porque por alguna razon las variables o constanten se limpian por completo, desaparecen, o me dice que no se han definido.

Pienso que tiene mucho que ver en el problema la linea 25:
Código PHP:
$grid->setUrl('detail.php'); 
Porque observo que durante la ejecución todo va bien, hasta que llega a esa linea y al parecer actualiza o recarga todo el script y lo comienza a ejecutar en un contexto completamente nuevo e independiente, incluso en un contexto fuera del alcance de default.php

Esta es la documentación oficial de setUrl:

setUrl
boolean setUrl( string $newurl )
Set a editing url. Note that this set a url from where to obtain and/or edit data.
Return false if runSetCommands is already runned (false)
Parameters:
string $newurl: the new url
API Tags:
Access: public


Pienso eso y solicito tu ayuda porque ya he probado durante 9 hrs diarias, durante 4 semanas incluidos los fines de semana un rato lo siguiente:
  • Usar variables globales (probando muchísimas combinaciones y sintaxis, ordenamientos al declarar, etc.):
  • global
  • $GLOBALS['variable'];
  • Usar variables estáticas (static) y aun así se limpian, pierden su valor.
  • Usar constantes, y manda error de que la constante no se ha definido. También pasa esto con las variables.
  • Sacar la consulta de grid.php y ponerla en default.php, la primera vez la ejecuta y la segunda vez dice que no existe la variable de la consulta.
  • Sacar varias partes del código de grip.php y ponerlo en default.php
  • No cerrar la conexión a la BD al final de grid.php
  • Instanciar el objeto
    Código PHP:
    $grid = new jqGridRender($conn); 
    fuera de grid.php, e instanciarlo en default.php pero igual la primera vez lo reconoce y la segunda vez ya dice que el objeto no se ha definido.
  • Y porque ya muchas otras cosas he intentado.
  • Y porque también he buscado en varios foros en inglés, leído la documentación oficial de php y la de jqGrid, visto muchos ejemplos de código y nada me ha funcionado.
  • Porque tengo 4 semanas de retraso en mi trabajo por esta situación.
  • Y porque también en la documentación de php [URL="http://php.net/manual/es/language.variables.scope.php"]php.net/manual/es/language.variables.scope.php[/URL] en la última sección de esa página "Referencias con variables globales y estáticas" dice esto textualmente: "Este ejemplo demuestra que al asignar una referencia a una variable estática, esta no es recordada cuando se invoca la función &obtener_instancia_ref() por segunda vez."
    Pero espero que este no sea mi caso.
Ayúdame por favor, muchísimas gracias.
  #2 (permalink)  
Antiguo 27/10/2011, 16:15
Avatar de romangus  
Fecha de Ingreso: octubre-2011
Mensajes: 3
Antigüedad: 12 años, 5 meses
Puntos: 0
De acuerdo Respuesta: jqGrid y PHP pierden las variables

Observo que también la solución podría andar por la penúltima linea del archivo grid.php:
Código PHP:
$grid->renderGrid('#grid','#pager',truenullnulltrue,true); 
Pues según la documentación del metodo renderGrid: [URL="http://www.trirand.com/blog/phpjqgrid/docs/jqGrid/jqGridRender.html#methodrenderGrid"]www.trirand.com/blog/phpjqgrid/docs/jqGrid/jqGridRender.html#methodrenderGrid[/URL]

Este método puede recibir un parámetro que se puede pasar a un query, aunque en grid.php está como null y no recibe nada mediante GET o POST, en el archivo detail.php si tiene ahí una variable, y además recibe mediante GET.

Esta linea en el archivo detail.php está así:
Código PHP:
$grid->renderGrid("#detail","#pgdetail"true$summaryrow, array(&$rowid), true,true); 
y al principio del archivo hay esto:
Código PHP:
// Get the needed parameters passed from the main grid
if(isset ($_REQUEST["CustomerID"]))
    
$rowid jqGridUtils::Strip($_REQUEST["CustomerID"]);
else
    
$rowid ""
A continuación la documentación del método renderGrid:

Main method which do allmost everthing for the grid

Construct the grid, perform CRUD operations, perform Query and serch operations, export to excel, set a jqGrid method, and javascript code

Parameters:

string $tblelement: the id of the table element to costrict the grid
string $pager: the id for the pager element
boolean $script: if set to true add a script tag before constructin the grid.
array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use other one this way : array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
array $params: parameters passed to the query
boolean $createtbl: if set to true the table element is created automatically from this method. Default is false
boolean $createpg: if set to true the pager element is created automatically from this script. Default false.
boolean $echo: if set to false the function return the string representing the grid

API Tags: Access: public

Etiquetas: ambito, grid, grilla, jqgrid, jquery, variables
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:41.