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



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 completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto 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.         
  18.         $column_id_produto->setTransformer$format_value );
  19. ?>
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.         
  15.         // define sum function
  16.         $format_value = function($value) {
  17.             TTransaction::open('local');
  18.             $conn TTransaction::get(); // get PDO connection
  19.             $query 'select sum(quantidade_estoque) as total from produto_movimento where id_produto = '.$value;
  20.             $sth $conn->query($query);
  21.             $sth->execute();
  22.             $result $sth->fetchAll();
  23.             if ($result[0]['total'] == null
  24.             {
  25.                 return '0';
  26.             } else {
  27.                 return $result[0]['total'];
  28.             }
  29.         };
  30.         
  31.         $column_id_produto->setTransformer$format_value );
  32. ?>