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 ?
No MODEL ProdutoMovimento criei esse método, porém dá erro... não encontra o "$this->id_produto"
select sum(quantidade_estoque) as total from produto_movimento where id_produto = [id do produto da linha processada]
Poderiam me ajudar ?
- <?php
- /**
- * ProdutoList Listing
- * @author <your name here>
- */
- class ProdutoList extends TPage
- {
- private $form; // form
- private $datagrid; // listing
- private $pageNavigation;
- private $formgrid;
- private $loaded;
- private $deleteButton;
- /**
- * Class constructor
- * Creates the page, the form and the listing
- */
- public function __construct()
- {
- parent::__construct();
- // creates the form
- $this->form = new BootstrapFormBuilder('form_search_Produto');
- $this->form->setFormTitle('Produto');
- // create the form fields
- $id_produto = new THidden('id_produto');
- $id_fornecedor = new TDBUniqueSearch('id_fornecedor','local', 'Fornecedor', 'id_fornecedor', 'nome', 'nome' );
- $nome = new TEntry('nome');
- // add the fields
- $this->form->addFields( [ new TLabel('') ], [ $id_produto ]);
- $this->form->addFields( [ new TLabel('Fornecedor') ], [ $id_fornecedor ] );
- $this->form->addFields( [ new TLabel('Nome') ], [ $nome ] );
- // set sizes
- $id_fornecedor->setSize('100%');
- $nome->setSize('100%');
- // keep the form filled during navigation with session data
- $this->form->setData( TSession::getValue(__CLASS__ . '_filter_data') );
- // add the search form actions
- $btn = $this->form->addAction(_t('Find'), new TAction([$this, 'onSearch']), 'fa:search');
- $btn->class = 'btn btn-sm btn-primary';
- $this->form->addActionLink(_t('New'), new TAction(['ProdutoForm', 'onEdit']), 'fa:plus green');
- // creates a Datagrid
- $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
- $this->datagrid->style = 'width: 100%';
- $this->datagrid->datatable = 'true';
- // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
- // creates the datagrid columns
- $column_nome = new TDataGridColumn('nome', 'Nome', 'left');
- $column_custo = new TDataGridColumn('custo', 'Custo', 'right');
- $column_venda = new TDataGridColumn('venda', 'Venda', 'right');
- $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
- $column_id_fornecedor = new TDataGridColumn('Fornecedor->nome', 'Fornecedor', 'left');
- // add the columns to the DataGrid
- $this->datagrid->addColumn($column_nome);
- $this->datagrid->addColumn($column_quantidade_estoque);
- $this->datagrid->addColumn($column_custo);
- $this->datagrid->addColumn($column_venda);
- $this->datagrid->addColumn($column_id_fornecedor);
- $action1 = new TDataGridAction(['ProdutoForm', 'onEdit'], ['id_produto'=>'{id_produto}']);
- $action2 = new TDataGridAction([$this, 'onDelete'], ['id_produto'=>'{id_produto}']);
- $this->datagrid->addAction($action1, _t('Edit'), 'far:edit blue');
- $this->datagrid->addAction($action2 ,_t('Delete'), 'far:trash-alt red');
- // create the datagrid model
- $this->datagrid->createModel();
- // creates the page navigation
- $this->pageNavigation = new TPageNavigation;
- $this->pageNavigation->setAction(new TAction([$this, 'onReload']));
- $this->pageNavigation->setWidth($this->datagrid->getWidth());
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 100%';
- // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- $container->add(TPanelGroup::pack('', $this->datagrid, $this->pageNavigation));
- parent::add($container);
- }
- /**
- * Inline record editing
- * @param $param Array containing:
- * key: object ID value
- * field name: object attribute to be updated
- * value: new attribute content
- */
- public function onInlineEdit($param)
- {
- try
- {
- // get the parameter $key
- $field = $param['field'];
- $key = $param['key'];
- $value = $param['value'];
- TTransaction::open('local'); // open a transaction with database
- $object = new Produto($key); // instantiates the Active Record
- $object->{$field} = $value;
- $object->store(); // update the object in the database
- TTransaction::close(); // close the transaction
- $this->onReload($param); // reload the listing
- new TMessage('info', "Record Updated");
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
- /**
- * Register the filter in the session
- */
- public function onSearch()
- {
- // get the search form data
- $data = $this->form->getData();
- // clear session filters
- TSession::setValue(__CLASS__.'_filter_id_fornecedor', NULL);
- TSession::setValue(__CLASS__.'_filter_nome', NULL);
- if (isset($data->id_fornecedor) AND ($data->id_fornecedor)) {
- $filter = new TFilter('id_fornecedor', 'like', "%{$data->id_fornecedor}%"); // create the filter
- TSession::setValue(__CLASS__.'_filter_id_fornecedor', $filter); // stores the filter in the session
- }
- if (isset($data->nome) AND ($data->nome)) {
- $filter = new TFilter('nome', 'like', "%{$data->nome}%"); // create the filter
- TSession::setValue(__CLASS__.'_filter_nome', $filter); // stores the filter in the session
- }
- // fill the form with data again
- $this->form->setData($data);
- // keep the search data in the session
- TSession::setValue(__CLASS__ . '_filter_data', $data);
- $param = array();
- $param['offset'] =0;
- $param['first_page']=1;
- $this->onReload($param);
- }
- /**
- * Load the datagrid with data
- */
- public function onReload($param = NULL)
- {
- try
- {
- // open a transaction with database 'local'
- TTransaction::open('local');
- // creates a repository for Produto
- $repository = new TRepository('Produto');
- $limit = 10;
- // creates a criteria
- $criteria = new TCriteria;
- // default order
- if (empty($param['order']))
- {
- $param['order'] = 'nome';
- $param['direction'] = 'asc';
- }
- $criteria->setProperties($param); // order, offset
- $criteria->setProperty('limit', $limit);
- if (TSession::getValue(__CLASS__.'_filter_id_fornecedor')) {
- $criteria->add(TSession::getValue(__CLASS__.'_filter_id_fornecedor')); // add the session filter
- }
- if (TSession::getValue(__CLASS__.'_filter_nome')) {
- $criteria->add(TSession::getValue(__CLASS__.'_filter_nome')); // add the session filter
- }
- // load the objects according to criteria
- $objects = $repository->load($criteria, FALSE);
- if (is_callable($this->transformCallback))
- {
- call_user_func($this->transformCallback, $objects, $param);
- }
- $this->datagrid->clear();
- if ($objects)
- {
- // iterate the collection of active records
- foreach ($objects as $object)
- {
- // add the object inside the datagrid
- $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)
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- }
- /**
- * Ask before deletion
- */
- public static function onDelete($param)
- {
- // define the delete action
- $action = new TAction([__CLASS__, 'Delete']);
- $action->setParameters($param); // pass the key parameter ahead
- // shows a dialog to the user
- new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
- }
- /**
- * Delete a record
- */
- public static function Delete($param)
- {
- try
- {
- $key=$param['key']; // get the parameter $key
- TTransaction::open('local'); // open a transaction with database
- $object = new Produto($key, FALSE); // instantiates the Active Record
- $object->delete(); // deletes the object from the database
- TTransaction::close(); // close the transaction
- $pos_action = new TAction([__CLASS__, 'onReload']);
- new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'), $pos_action); // success message
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
- /**
- * method show()
- * Shows the page
- */
- public function show()
- {
- // check if the datagrid is already loaded
- if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch')))) )
- {
- if (func_num_args() > 0)
- {
- $this->onReload( func_get_arg(0) );
- }
- else
- {
- $this->onReload();
- }
- }
- parent::show();
- }
- }
- ?>
No MODEL ProdutoMovimento criei esse método, porém dá erro... não encontra o "$this->id_produto"
- <?php
- public static function get_saldo()
- {
- TTransaction::open('local');
- $conn = TTransaction::get(); // get PDO connection
- $query = 'select sum(quantidade_estoque) as total from produto_movimento where id_produto = '.$this->id_produto;
- $sth = $conn->query($query);
- $sth->execute();
- $result = $sth->fetchAll();
- $result = $result[0];
- return $result;
- }
- ?>
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.
Aí segue a rotina onde ficou inserida.