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


Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


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


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. while ($linha = $result->fetchObject()) {
  6. var_dump($linha);
  7. }
  8. TTransaction::close();
  9. ?>


ou

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