Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Montar um Datagrid com dados coletados por uma consulta (SQL) Boa tarde a todos, Preciso alimentar as colunas de um datagrid, no entanto, os dados estão sendo selecinoados por uma query. Já li as publicações anteriores, segui alguns exemplos e até o momento não funcionou, sei que usar Criteria seria melhor, mas a query é muito complexa. A possibilidade de se criar uma View também não seria viável. Quando executo o código e faço um vardump n...
WS
Montar um Datagrid com dados coletados por uma consulta (SQL)  
Boa tarde a todos,

Preciso alimentar as colunas de um datagrid, no entanto, os dados estão sendo selecinoados por uma query.
Já li as publicações anteriores, segui alguns exemplos e até o momento não funcionou, sei que usar Criteria seria melhor, mas a query é muito complexa.
A possibilidade de se criar uma View também não seria viável.
Quando executo o código e faço um vardump no objeto retornado, está vindo apenas 1 item e teriam que vir mais de 400.

Vou postar um resumo do que estou fazendo. Caso alguém tenha uma ideia do que pode ser e puder ajudar, agradeço!

  1. <?php
  1. <?php
  2. class CompleteFormDataGridView extends TPage
  3. {
  4.     private $form;      // registration form
  5.     private $datagrid;  // listing
  6.     private $loaded;
  7.     
  8.     /**
  9.      * Class constructor
  10.      * Creates the page, the form and the listing
  11.      */
  12.     public function __construct()
  13.     {
  14.         parent::__construct();
  15.         
  16.         // create the form
  17.         $this->form = new BootstrapFormBuilder('form_categories');
  18.         $this->form->setFormTitle(_t('Manual Form/DataGrid'));
  19.         
  20.         // create the form fields
  21.         $id     = new TEntry('id');
  22.         $name   = new TEntry('name');
  23.         
  24.         // add the fields in the form
  25.         $this->form->addFields( [new TLabel('ID')],    [$id] );
  26.         $this->form->addFields( [new TLabel('Name''red')],  [$name] );
  27.         
  28.         $name->addValidation('Name', new TRequiredValidator);
  29.         
  30.         // define the form actions
  31.         $this->form->addAction'Save',  new TAction([$this'onSave']), 'fa:save green');
  32.         $this->form->addActionLink'Clear', new TAction([$this'onClear']), 'fa:eraser red');
  33.         
  34.         // id not editable
  35.         $id->setEditable(FALSE);
  36.         
  37.         $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  38.         $this->datagrid->width '100%';
  39.         
  40.         // add the columns
  41.         $col_id    = new TDataGridColumn('id''Id''right''10%');
  42.         $col_name  = new TDataGridColumn('name''Name''left''90%');
  43.         
  44.         $this->datagrid->addColumn($col_id);
  45.         $this->datagrid->addColumn($col_name);
  46.         
  47.         $col_id->setAction( new TAction([$this'onReload']),   ['order' => 'id']);
  48.         $col_name->setAction( new TAction([$this'onReload']), ['order' => 'name']);
  49.         
  50.         $action1 = new TDataGridAction([$this'onEdit'],   ['key' => '{id}'] );
  51.         $action2 = new TDataGridAction([$this'onDelete'], ['key' => '{id}'] );
  52.         
  53.         $this->datagrid->addAction($action1'Edit',   'far:edit blue');
  54.         $this->datagrid->addAction($action2'Delete''far:trash-alt red');
  55.         
  56.         // create the datagrid model
  57.         $this->datagrid->createModel();
  58.         
  59.         // wrap objects
  60.         $vbox = new TVBox;
  61.         $vbox->style 'width: 100%';
  62.         $vbox->add(new TXMLBreadCrumb('menu.xml'__CLASS__));
  63.         $vbox->add($this->form);
  64.         $vbox->add(TPanelGroup::pack(''$this->datagrid));
  65.         
  66.         // add the box in the page
  67.         parent::add($vbox);
  68.     }
  69.     
  70.     /**
  71.      * method onReload()
  72.      * Load the datagrid with the database objects
  73.      */
  74.     function onReload($param NULL)
  75.     {
  76.         try
  77.         {
  78.             // open a transaction with database 'samples'
  79.             TTransaction::open('samples');            
  80.             
  81.             $conn TTransaction::get();
  82.                     
  83.             $result $conn->query('SELECT * FROM Tabela');
  84.                     
  85.             foreach ($result as $row);
  86.                     {
  87.                         $this->datagrid->addItem($row);
  88.                     }
  89.             TTransaction::close();
  90.             $this->loaded true;
  91.         }
  92.         catch (Exception $e// in case of exception
  93.         {
  94.             // shows the exception error message
  95.             new TMessage('error'$e->getMessage());
  96.             
  97.             // undo all pending operations
  98.             TTransaction::rollback();
  99.         }
  100.     }   
  101.    
  102.     
  103.     /**
  104.      * Clear form
  105.      */
  106.     public function onClear()
  107.     {
  108.         $this->form->cleartrue );
  109.     }
  110.     
  111.     /**
  112.      * method onEdit()
  113.      * Executed whenever the user clicks at the edit button
  114.      */   
  115.    
  116.     public static function onDelete($param)
  117.     {
  118.         // define the delete action
  119.         $action = new TAction([__CLASS__'Delete']);
  120.         $action->setParameters($param); // pass the key parameter ahead
  121.         
  122.         // shows a dialog to the user
  123.         new TQuestion('Do you really want to delete ?'$action);
  124.     }
  125.     
  126.     /**
  127.      * method Delete()
  128.      * Delete a record
  129.      */
  130.     public static function Delete($param)
  131.     {
  132.         try
  133.         {
  134.             // get the parameter $key
  135.             $key $param['id'];
  136.             
  137.             // open a transaction with database 'samples'
  138.             TTransaction::open('samples');
  139.             
  140.             // instantiates object Category
  141.             $category = new Category($key);
  142.             
  143.             // deletes the object from the database
  144.             $category->delete();
  145.             
  146.             // close the transaction
  147.             TTransaction::close();
  148.             
  149.             $pos_action = new TAction([__CLASS__'onReload']);
  150.             new TMessage('info'AdiantiCoreTranslator::translate('Record deleted'), $pos_action);
  151.         }
  152.         catch (Exception $e// in case of exception
  153.         {
  154.             // shows the exception error message
  155.             new TMessage('error'$e->getMessage());
  156.             
  157.             // undo all pending operations
  158.             TTransaction::rollback();
  159.         }
  160.     }
  161.     
  162.     /**
  163.      * method show()
  164.      * Shows the page e seu conteúdo
  165.      */
  166.     function show()
  167.     {
  168.         // check if the datagrid is already loaded
  169.         if (!$this->loaded)
  170.         {
  171.             $this->onReloadfunc_get_arg(0) );
  172.         }
  173.         parent::show();
  174.     }
  175. }
  176. Obrigado!
  177. ?>


Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


Dominando o Adianti 7 Quero me inscrever agora!

Comentários (14)


NM

Hola

Te mando um exemplo que tenho aqui tenta usar ele no onReload:
$items = MotoristasDocumentos::where('md_id1', '=', $key)->load();
foreach($items as $item )
{
$data = new stdClass;
$data->md_id2 = $item->md_id2;
$data->md_arquivo = $item->md_arq_nome;
$data->md_marca = '';
$this->datagrid->addItem( $data );
}
PN

Salve William, segue um exemplo bem padrão da montagem de um datagrid no onReload:

public function onReload($param = null)
{
try
{
// open a transaction with database 'DB_EMPConecta'
TTransaction::open('DB_EMPConecta');

// creates a repository for system_user
$repository = new TRepository('SystemUser');
$limit = 20;

// Instancia o critério de filtragem
$criteria = new TCriteria;

if (empty($param['order']))
{
$param['order'] = 'name asc';
}

$criteria->add(new TFilter('system_group_id','=', $param['id']));
$criteria->setProperties($param);
$criteria->setProperty('limit', $limit);

// load the objects according to criteria
$objects = $repository->load($criteria, FALSE);
$this->datagrid->clear();
if ($objects)
{
foreach ($objects as $object)
{
$this->datagrid->addItem($object);
}
}

// reset the criteria for record count
$criteria->resetProperties();
$count= $repository->count($criteria);

$this->pageNavigation->setCount($count); // count of records
$this->pageNavigation->setProperties($param); // order, page
$this->pageNavigation->setLimit($limit); // limit

// close the transaction
TTransaction::close();

$this->loaded = true;

}
catch (Exception $e)
{
TTransaction::rollback();

TToast::show('error', $e->getMessage(), 'top center', 'fa fa-thumbs-down' );

}
}
WS

na verdade preciso usar uma query mesmo. ela é bem complexa para ser 'montada' com Criteria e Filter...

Vou colocar o onReload aqui para vocês terem uma ideia:

  1. <?php
  2. function onReload($param NULL)
  3.     {
  4.         try
  5.         {
  6.             // open a transaction with database 'samples'
  7.            $bdIXC Utils::getBDIXC();
  8.         
  9.           //  TTransaction::open($bdIXC);
  10.             
  11.           //  $order    = isset($param['order']) ? $param['order'] : 'id';
  12.             // load the objects according to criteria
  13.             /*$categories = Category::orderBy($order)->load();
  14.             
  15.             $this->datagrid->clear();
  16.             if ($categories)
  17.             {
  18.                 // iterate the collection of active records
  19.                 foreach ($categories as $category)
  20.                 {
  21.                     // add the object inside the datagrid
  22.                     $this->datagrid->addItem($category);
  23.                 }
  24.             }*/
  25.             
  26.             $conn TConnection::open($bdIXC);             
  27.           
  28.                 
  29.             $mssql 
  30.             "SELECT  cliente_contrato.id,
  31.                      cliente_contrato.id_cliente,
  32.                      cliente.razao                           AS 'cliente_razao',
  33.                      cliente_contrato.data_ativacao,
  34.                      cliente_contrato.data_cadastro_sistema,
  35.                      cliente_contrato.data_cancelamento, 
  36.                      (CASE WHEN cliente_contrato.status = 'A' 
  37.                            THEN 'ATIVO'          
  38.                            ELSE 
  39.                      (CASE WHEN cliente_contrato.status = 'I' 
  40.                            THEN 'INATIVO'      
  41.                            ELSE 
  42.                      (CASE WHEN cliente_contrato.status = 'D' 
  43.                            THEN 'DESISTIU'     
  44.                            ELSE 
  45.                      (CASE WHEN cliente_contrato.status = 'P' 
  46.                            THEN 'PRÉ CONTRATO' 
  47.                            ELSE 'NEGATIVADO' 
  48.                            END) END) END) END)                 AS 'status',                
  49.                    
  50.                      (CASE WHEN cliente_contrato.status_internet = 'A' 
  51.                            THEN 'ATIVO'                    
  52.                            ELSE 
  53.                      (CASE WHEN cliente_contrato.status_internet = 'D' 
  54.                            THEN 'DESATIVADO'            
  55.                            ELSE 
  56.                      (CASE WHEN cliente_contrato.status_internet = 'CM' 
  57.                            THEN 'BLOQUEIO MANUAL'      
  58.                            ELSE 
  59.                      (CASE WHEN cliente_contrato.status_internet = 'CA' 
  60.                             THEN 'BLOQUEIO AUTOMATICO'  
  61.                             ELSE         
  62.                      (CASE WHEN cliente_contrato.status_internet = 'FA' 
  63.                            THEN 'FINANCEIRO EM ATRASO' 
  64.                            ELSE 'AGUARDANDO ASSINATURA' 
  65.                            END) END) END) END) END)        AS 'status_internet', 
  66.                      ROUND(vd_contratos.valor_contrato,2)  AS 'valor_contrato',
  67.                      cliente_contrato.id_vendedor,
  68.                      vendedor.nome                           AS 'vendedor_nome',
  69.                      vd_contratos.descricao                AS 'plano_venda',
  70.                      mot_can.motivo                           AS 'des_motivo_cancelamento',
  71.                      cliente_contrato.obs_cancelamento     AS 'OBS CANCELAMENTO',
  72.                      (CASE WHEN radusuarios.endereco_padrao_cliente  = 'N' 
  73.                            THEN radusuarios.bairro 
  74.                            ELSE cliente.bairro 
  75.                            END) 
  76.                                                            AS 'bairro',
  77.                      (CASE WHEN radusuarios.endereco_padrao_cliente  = 'N' 
  78.                            THEN (cidade_R.nome) 
  79.                            ELSE cidade_C.nome 
  80.                            END)                                AS 'cidade',
  81.                     
  82.                      CURDATE()                              AS 'DATA ATUAL',
  83.                      fn_areceber.data_vencimento            AS 'DT VENCIMENTO',
  84.                      fn_areceber.id                           AS 'ID FN',
  85.                      DATEDIFF(CURDATE() ,  fn_areceber.data_vencimento) AS 'DIAS VENCIDOS',       
  86.             (CASE WHEN DATEDIFF(CURDATE() ,  fn_areceber.data_vencimento) > 50
  87.                   THEN 'FPD' 
  88.                   ELSE 'CANDIDATO FPD' 
  89.                           END)                             AS 'SITUAÇÃO'
  90.                           
  91.             FROM ixcprovedor.fn_areceber                       AS fn_areceber
  92.             INNER JOIN ixcprovedor.cliente_contrato            AS cliente_contrato ON fn_areceber.id_contrato = cliente_contrato.id
  93.             INNER JOIN ixcprovedor.cliente                     AS cliente ON cliente_contrato.id_cliente = cliente.id
  94.             INNER JOIN ixcprovedor.vd_contratos                AS vd_contratos ON vd_contratos.id = cliente_contrato.id_vd_contrato
  95.             INNER JOIN ixcprovedor.vendedor                    AS vendedor ON cliente_contrato.id_vendedor = vendedor.id
  96.             LEFT JOIN ixcprovedor.radusuarios                    AS radusuarios ON cliente_contrato.id = radusuarios.id_contrato
  97.             LEFT JOIN ixcprovedor.cidade                         AS cidade_R     ON radusuarios.cidade  = cidade_R.id
  98.             LEFT JOIN ixcprovedor.cidade                         AS cidade_C     ON cliente_contrato.cidade  = cidade_C.id
  99.             LEFT JOIN ixcprovedor.fn_areceber_mot_cancelamento AS mot_can ON cliente_contrato.motivo_cancelamento = mot_can.id
  100.             WHERE fn_areceber.status = 'A'                                   AND
  101.                   cliente_contrato.status_internet NOT IN  ('A')          AND 
  102.                   cliente_contrato.id NOT IN (SELECT DISTINCT cliente_contrato.id     AS  'ID'        
  103.                                               FROM ixcprovedor.fn_areceber            AS fn_areceber
  104.                                               INNER JOIN ixcprovedor.cliente_contrato AS cliente_contrato ON fn_areceber.id_contrato = cliente_contrato.id
  105.                                               WHERE fn_areceber.status IN ('R') )
  106.             GROUP BY cliente_contrato.id";
  107.            
  108.             $result $conn->query($mssql);
  109.             $resp $result->fetchObject();
  110.             var_dump($resp);        
  111.             foreach ($resp as $row);
  112.             {
  113.                 //var_dump($row);
  114.                // echo 'id: ' . $row['id'];
  115.                // $this->datagrid->addItem($row);
  116.             }
  117.             
  118.             
  119.             // close the transaction
  120.             TTransaction::close();
  121.             $this->loaded true;
  122.         }
  123.         catch (Exception $e// in case of exception
  124.         {
  125.             // shows the exception error message
  126.             new TMessage('error'$e->getMessage());
  127.             
  128.             // undo all pending operations
  129.             TTransaction::rollback();
  130.         }
  131.     }
  132. ?>
NM

Eu usaria uma view
PN

William, use uma view e desta forma vc poderá usar o exemplo que te mandei de forma bem fácil. Basta vc trocar a classe aqui: $repository = new TRepository('SystemUser'); pela sua view !!!
PN

Oi William, mas se mesmo assim vc, realmente, precisar do SQL completo aí nesta parte de seu código, vc pode fazer algo assim:

TTransaction::open('Arquivo.ini');
$conn = TTransaction::get();

$result = $conn->query('SELECT * FROM Tabela');

foreach ($result as $row);
{
$this->datagrid->addItem($row);
}
TTransaction::close();

Abs,

Paulo
WS

Bom dia pessoal,

então Nilton, sobre a View, eu realmente não posso criar. Estou trabalhando em um banco onde não posso fazer alteração.

concordo Paulo, realmente a view seria mais fácil de usar, mas infelizmente é uma possibilidade descartada.

No entanto, eu fiz o esquema da query, mas retorna 1 item no objeto. Teria que retornar mais de 400.

Não sei o motivo...

Tem alguma ideia?
NM

E se rodar ela direto no banco funciona ?
WS

sim... perfeitamente
NM

Então tem alguma coisa errada na montagem da query veja as variaveis que esta usando para filtro e monta ele primeiro numa variavel e da um echo em tela para ver.
WS

eu havia pensado nisso... então fiz o onreload com uma consulta bem basica:

  1. <?php
  2. $bdsam Utils::getBDPROSam();
  3.             TTransaction::open($bdsam);
  4.             $conn TTransaction::get();
  5.             
  6.             $result $conn->query('SELECT * FROM status_indicacao');            
  7.             
  8.             foreach ($result as $row);
  9.             {
  10.                 //$this->datagrid->addItem($row);
  11.                 var_dump($row);
  12.             }
  13.             TTransaction::close();
  14. ?>


e ainda sim, retornou apenas 1 item
NM

Oi

$result = $conn->query('SELECT * FROM status_indicacao');

Eu imagino que nessa query você tenha algum tipo de filtro, então tenta montar a query numa variavel assim:
$cSql = 'SELECT * FROM status_indicacao where .......';
echo $cSql;

recorta a saida para a tela e tenta rodar na base de dados.
PN

Salve William,

Rapaz, se neste simples exemplo ele insiste em trazer apenas 1 registro, não faz sentido algum !!! veja, também, se não há algo errado na montagem do datagrid.

Tipo, vc colocou pra ordenar por ID e NAME e chama a função OnReload pra isso (OK !!), só que lá tem um SQL que se estivesse funcionando sempre vai ordenar de forma única !!! Lógico que isto tem nada ver com o seu problema, mas vai ser um complicador para vc oferecer ordenação, sacou ???

$col_id->setAction( new TAction([$this, 'onReload']), ['order' => 'id']);
$col_name->setAction( new TAction([$this, 'onReload']), ['order' => 'name']);

Execute um clear no datagrid, antes da carga:

$this->datagrid->clear();
if ($result )
{
foreach ($result as $row);
{
$this->datagrid->addItem($row);
}
}

Abs,

Paulo
JR

  1. <?php
  2.         TTransaction::open('mini_erp');
  3.         $conn TTransaction::get();
  4.         $result $conn->query('select * from banco');
  5.         
  6.         while ($linha $result->fetchObject()) {
  7.             var_dump($linha);
  8.         }
  9.         TTransaction::close();
  10. ?>


ou

  1. <?php
  2.         TTransaction::open('mini_erp');
  3.         $conn TTransaction::get();
  4.         $result $conn->query('select * from banco');
  5.         
  6.         $tudo $result->fetchAll();
  7.         var_dump($tudo );
  8.         TTransaction::close();
  9. ?>