Conheça as melhorias da versão 8.0, 8.1, 8.2!
Clique aqui para saber mais
TDataGridColumn trazendo um SELECT de outra tabela Queria preencher a TDataGridColumn 'movimento_estoque' com o resultado do select: select sum(quantidade_estoque) as total from produto_movimento where id_produto = [id do produto da linha processada] Poderiam me ajudar ? ...
CC
TDataGridColumn trazendo um SELECT de outra tabela  
Queria preencher a TDataGridColumn 'movimento_estoque' com o resultado do select:
select sum(quantidade_estoque) as total from produto_movimento where id_produto = [id do produto da linha processada]

Poderiam me ajudar ?


 
  1. <?php
  2. /**
  3. * ProdutoList Listing
  4. * @author <your name here>
  5. */
  6. class ProdutoList extends TPage
  7. {
  8. private $form; // form
  9. private $datagrid; // listing
  10. private $pageNavigation;
  11. private $formgrid;
  12. private $loaded;
  13. private $deleteButton;
  14. /**
  15. * Class constructor
  16. * Creates the page, the form and the listing
  17. */
  18. public function __construct()
  19. {
  20. parent::__construct();
  21. // creates the form
  22. $this->form = new BootstrapFormBuilder('form_search_Produto');
  23. $this->form->setFormTitle('Produto');
  24. // create the form fields
  25. $id_produto = new THidden('id_produto');
  26. $id_fornecedor = new TDBUniqueSearch('id_fornecedor','local', 'Fornecedor', 'id_fornecedor', 'nome', 'nome' );
  27. $nome = new TEntry('nome');
  28. // add the fields
  29. $this->form->addFields( [ new TLabel('') ], [ $id_produto ]);
  30. $this->form->addFields( [ new TLabel('Fornecedor') ], [ $id_fornecedor ] );
  31. $this->form->addFields( [ new TLabel('Nome') ], [ $nome ] );
  32. // set sizes
  33. $id_fornecedor->setSize('100%');
  34. $nome->setSize('100%');
  35. // keep the form filled during navigation with session data
  36. $this->form->setData( TSession::getValue(__CLASS__ . '_filter_data') );
  37. // add the search form actions
  38. $btn = $this->form->addAction(_t('Find'), new TAction([$this, 'onSearch']), 'fa:search');
  39. $btn->class = 'btn btn-sm btn-primary';
  40. $this->form->addActionLink(_t('New'), new TAction(['ProdutoForm', 'onEdit']), 'fa:plus green');
  41. // creates a Datagrid
  42. $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  43. $this->datagrid->style = 'width: 100%';
  44. $this->datagrid->datatable = 'true';
  45. // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  46. // creates the datagrid columns
  47. $column_nome = new TDataGridColumn('nome', 'Nome', 'left');
  48. $column_custo = new TDataGridColumn('custo', 'Custo', 'right');
  49. $column_venda = new TDataGridColumn('venda', 'Venda', 'right');
  50. $column_quantidade_estoque = new TDataGridColumn('quantidade_estoque', 'Estoque', 'right'); // <- esse campo quantidade_estoque eu queria que fizesse um SUM de um campo da tabela produto_movimento
  51. $column_id_fornecedor = new TDataGridColumn('Fornecedor->nome', 'Fornecedor', 'left');
  52. // add the columns to the DataGrid
  53. $this->datagrid->addColumn($column_nome);
  54. $this->datagrid->addColumn($column_quantidade_estoque);
  55. $this->datagrid->addColumn($column_custo);
  56. $this->datagrid->addColumn($column_venda);
  57. $this->datagrid->addColumn($column_id_fornecedor);
  58. $action1 = new TDataGridAction(['ProdutoForm', 'onEdit'], ['id_produto'=>'{id_produto}']);
  59. $action2 = new TDataGridAction([$this, 'onDelete'], ['id_produto'=>'{id_produto}']);
  60. $this->datagrid->addAction($action1, _t('Edit'), 'far:edit blue');
  61. $this->datagrid->addAction($action2 ,_t('Delete'), 'far:trash-alt red');
  62. // create the datagrid model
  63. $this->datagrid->createModel();
  64. // creates the page navigation
  65. $this->pageNavigation = new TPageNavigation;
  66. $this->pageNavigation->setAction(new TAction([$this, 'onReload']));
  67. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  68. // vertical box container
  69. $container = new TVBox;
  70. $container->style = 'width: 100%';
  71. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  72. $container->add($this->form);
  73. $container->add(TPanelGroup::pack('', $this->datagrid, $this->pageNavigation));
  74. parent::add($container);
  75. }
  76. /**
  77. * Inline record editing
  78. * @param $param Array containing:
  79. * key: object ID value
  80. * field name: object attribute to be updated
  81. * value: new attribute content
  82. */
  83. public function onInlineEdit($param)
  84. {
  85. try
  86. {
  87. // get the parameter $key
  88. $field = $param['field'];
  89. $key = $param['key'];
  90. $value = $param['value'];
  91. TTransaction::open('local'); // open a transaction with database
  92. $object = new Produto($key); // instantiates the Active Record
  93. $object->{$field} = $value;
  94. $object->store(); // update the object in the database
  95. TTransaction::close(); // close the transaction
  96. $this->onReload($param); // reload the listing
  97. new TMessage('info', "Record Updated");
  98. }
  99. catch (Exception $e) // in case of exception
  100. {
  101. new TMessage('error', $e->getMessage()); // shows the exception error message
  102. TTransaction::rollback(); // undo all pending operations
  103. }
  104. }
  105. /**
  106. * Register the filter in the session
  107. */
  108. public function onSearch()
  109. {
  110. // get the search form data
  111. $data = $this->form->getData();
  112. // clear session filters
  113. TSession::setValue(__CLASS__.'_filter_id_fornecedor', NULL);
  114. TSession::setValue(__CLASS__.'_filter_nome', NULL);
  115. if (isset($data->id_fornecedor) AND ($data->id_fornecedor)) {
  116. $filter = new TFilter('id_fornecedor', 'like', "%{$data->id_fornecedor}%"); // create the filter
  117. TSession::setValue(__CLASS__.'_filter_id_fornecedor', $filter); // stores the filter in the session
  118. }
  119. if (isset($data->nome) AND ($data->nome)) {
  120. $filter = new TFilter('nome', 'like', "%{$data->nome}%"); // create the filter
  121. TSession::setValue(__CLASS__.'_filter_nome', $filter); // stores the filter in the session
  122. }
  123. // fill the form with data again
  124. $this->form->setData($data);
  125. // keep the search data in the session
  126. TSession::setValue(__CLASS__ . '_filter_data', $data);
  127. $param = array();
  128. $param['offset'] =0;
  129. $param['first_page']=1;
  130. $this->onReload($param);
  131. }
  132. /**
  133. * Load the datagrid with data
  134. */
  135. public function onReload($param = NULL)
  136. {
  137. try
  138. {
  139. // open a transaction with database 'local'
  140. TTransaction::open('local');
  141. // creates a repository for Produto
  142. $repository = new TRepository('Produto');
  143. $limit = 10;
  144. // creates a criteria
  145. $criteria = new TCriteria;
  146. // default order
  147. if (empty($param['order']))
  148. {
  149. $param['order'] = 'nome';
  150. $param['direction'] = 'asc';
  151. }
  152. $criteria->setProperties($param); // order, offset
  153. $criteria->setProperty('limit', $limit);
  154. if (TSession::getValue(__CLASS__.'_filter_id_fornecedor')) {
  155. $criteria->add(TSession::getValue(__CLASS__.'_filter_id_fornecedor')); // add the session filter
  156. }
  157. if (TSession::getValue(__CLASS__.'_filter_nome')) {
  158. $criteria->add(TSession::getValue(__CLASS__.'_filter_nome')); // add the session filter
  159. }
  160. // load the objects according to criteria
  161. $objects = $repository->load($criteria, FALSE);
  162. if (is_callable($this->transformCallback))
  163. {
  164. call_user_func($this->transformCallback, $objects, $param);
  165. }
  166. $this->datagrid->clear();
  167. if ($objects)
  168. {
  169. // iterate the collection of active records
  170. foreach ($objects as $object)
  171. {
  172. // add the object inside the datagrid
  173. $this->datagrid->addItem($object);
  174. }
  175. }
  176. // reset the criteria for record count
  177. $criteria->resetProperties();
  178. $count= $repository->count($criteria);
  179. $this->pageNavigation->setCount($count); // count of records
  180. $this->pageNavigation->setProperties($param); // order, page
  181. $this->pageNavigation->setLimit($limit); // limit
  182. // close the transaction
  183. TTransaction::close();
  184. $this->loaded = true;
  185. }
  186. catch (Exception $e)
  187. {
  188. new TMessage('error', $e->getMessage());
  189. TTransaction::rollback();
  190. }
  191. }
  192. /**
  193. * Ask before deletion
  194. */
  195. public static function onDelete($param)
  196. {
  197. // define the delete action
  198. $action = new TAction([__CLASS__, 'Delete']);
  199. $action->setParameters($param); // pass the key parameter ahead
  200. // shows a dialog to the user
  201. new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  202. }
  203. /**
  204. * Delete a record
  205. */
  206. public static function Delete($param)
  207. {
  208. try
  209. {
  210. $key=$param['key']; // get the parameter $key
  211. TTransaction::open('local'); // open a transaction with database
  212. $object = new Produto($key, FALSE); // instantiates the Active Record
  213. $object->delete(); // deletes the object from the database
  214. TTransaction::close(); // close the transaction
  215. $pos_action = new TAction([__CLASS__, 'onReload']);
  216. new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'), $pos_action); // success message
  217. }
  218. catch (Exception $e) // in case of exception
  219. {
  220. new TMessage('error', $e->getMessage()); // shows the exception error message
  221. TTransaction::rollback(); // undo all pending operations
  222. }
  223. }
  224. /**
  225. * method show()
  226. * Shows the page
  227. */
  228. public function show()
  229. {
  230. // check if the datagrid is already loaded
  231. if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch')))) )
  232. {
  233. if (func_num_args() > 0)
  234. {
  235. $this->onReload( func_get_arg(0) );
  236. }
  237. else
  238. {
  239. $this->onReload();
  240. }
  241. }
  242. parent::show();
  243. }
  244. }
  245. ?>



No MODEL ProdutoMovimento criei esse método, porém dá erro... não encontra o "$this->id_produto"

 
  1. <?php
  2. public static function get_saldo()
  3. {
  4. TTransaction::open('local');
  5. $conn = TTransaction::get(); // get PDO connection
  6. $query = 'select sum(quantidade_estoque) as total from produto_movimento where id_produto = '.$this->id_produto;
  7. $sth = $conn->query($query);
  8. $sth->execute();
  9. $result = $sth->fetchAll();
  10. $result = $result[0];
  11. return $result;
  12. }
  13. ?>

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 (2)


CC

Galera, resolvi dessa maneira. Não sei se é a melhor prática. Se houver uma maneira melhor, por favor podem passar aqui, que vou ficar muito grato.


 
  1. <?php
  2. // define sum function
  3. $format_value = function($value) {
  4. TTransaction::open('local');
  5. $conn = TTransaction::get(); // get PDO connection
  6. $query = 'select sum(quantidade_estoque) as total from produto_movimento where id_produto = '.$value;
  7. $sth = $conn->query($query);
  8. $sth->execute();
  9. $result = $sth->fetchAll();
  10. if ($result[0]['total'] == null)
  11. {
  12. return '0';
  13. } else {
  14. return $result[0]['total'];
  15. }
  16. };
  17. $column_id_produto->setTransformer( $format_value );
  18. ?>
CC

Aí segue a rotina onde ficou inserida.

 
  1. <?php
  2. // creates the datagrid columns
  3. $column_nome = new TDataGridColumn('nome', 'Nome', 'left');
  4. $column_id_produto = new TDataGridColumn('id_produto', 'Qtd', 'right');
  5. $column_custo = new TDataGridColumn('custo', 'Custo', 'right');
  6. $column_venda = new TDataGridColumn('venda', 'Venda', 'right');
  7. $column_id_fornecedor = new TDataGridColumn('Fornecedor->nome', 'Fornecedor', 'left');
  8. // add the columns to the DataGrid
  9. $this->datagrid->addColumn($column_nome);
  10. $this->datagrid->addColumn($column_id_produto);
  11. $this->datagrid->addColumn($column_custo);
  12. $this->datagrid->addColumn($column_venda);
  13. $this->datagrid->addColumn($column_id_fornecedor);
  14. // define sum function
  15. $format_value = function($value) {
  16. TTransaction::open('local');
  17. $conn = TTransaction::get(); // get PDO connection
  18. $query = 'select sum(quantidade_estoque) as total from produto_movimento where id_produto = '.$value;
  19. $sth = $conn->query($query);
  20. $sth->execute();
  21. $result = $sth->fetchAll();
  22. if ($result[0]['total'] == null)
  23. {
  24. return '0';
  25. } else {
  26. return $result[0]['total'];
  27. }
  28. };
  29. $column_id_produto->setTransformer( $format_value );
  30. ?>