Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Filtro em DataGrid a partir de Vaiável de Sessão. Olá, Estou montado um DataGrid com consulta filtrando uma data específica, porem gostaria que fosse aplicado um filtro automaticamente pela variável de sessão que guarda o id da unidade que seria a TSession::getValue('userunitid'), fiz alguns testes usando Criteria porém não funcionou. Tentei deixar o campo do form como THidden e fazer um setValue com a variável de sessão, mas não deu ce...
CG
Filtro em DataGrid a partir de Vaiável de Sessão.  
Olá,
Estou montado um DataGrid com consulta filtrando uma data específica, porem gostaria que fosse aplicado um filtro automaticamente pela variável de sessão que guarda o id da unidade que seria a TSession::getValue('userunitid'), fiz alguns testes usando Criteria porém não funcionou. Tentei deixar o campo do form como THidden e fazer um setValue com a variável de sessão, mas não deu certo. alguém poderia me ajudar por favor.

  1. <?php
  2. /**
  3.  * MovimentacaoList Listing
  4.  * @author  Claudio Gomes
  5.  */
  6. class MovimentacaoList 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_Movimentacao');
  23.         $this->form->setFormTitle('Movimentacao');
  24.         // create the form fields
  25.         $dt_mov = new TEntry('dt_mov');
  26.         //$system_unit_id = new TEntry('system_unit_id');
  27.         $system_unit_id = new THidden('system_unit_id');
  28.         $unidade TSession::getValue('userunitid');
  29.         $system_unit_id->setValue($unidade);
  30.         // add the fields
  31.         $this->form->addFields( [ new TLabel('Data de Movimento') ], [ $dt_mov ] );
  32.         $this->form->addFields( [ new TLabel('') ], [ $system_unit_id ] );
  33.         // set sizes
  34.         $dt_mov->setSize('100%');
  35.         $system_unit_id->setSize('100%');
  36.         // keep the form filled during navigation with session data
  37.         $this->form->setDataTSession::getValue(__CLASS__ '_filter_data') );
  38.         // add the search form actions
  39.         $btn $this->form->addAction(_t('Find'), new TAction([$this'onSearch']), 'fa:search');
  40.         $btn->class 'btn btn-sm btn-primary';
  41.         $this->form->addActionLink(_t('New'), new TAction(['MovimentacaoEditLista''onEdit']), 'fa:plus green');
  42.         // creates a Datagrid
  43.         $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  44.         $this->datagrid->style 'width: 100%';
  45.         $this->datagrid->datatable 'true';
  46.         // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  47.         // creates the datagrid columns
  48.         $column_dt_mov = new TDataGridColumn('dt_mov''Data Movimento''left');
  49.         $column_system_unit_id = new TDataGridColumn('system_unit_id''System Unit Id''left');
  50.         $column_valor_apurado_maq = new TDataGridColumn('valor_apurado_maq''Apurado Máquina''left');
  51.         $column_valor_apurado_talao = new TDataGridColumn('valor_apurado_talao''Apurado Talão''left');
  52.         $column_pagamento_maq = new TDataGridColumn('pagamento_maq''Pagamento Máquina''left');
  53.         $column_pagamento_talao = new TDataGridColumn('pagamento_talao''Pagamento Talão''left');
  54.         $column_despesas_valor = new TDataGridColumn('despesas_valor''Valor Despesas''left');
  55.         $column_retecao = new TDataGridColumn('retecao''Retenção''left');
  56.         $column_lucro_preju = new TDataGridColumn('lucro_preju''Lucro''left');
  57.         // add the columns to the DataGrid
  58.         $this->datagrid->addColumn($column_dt_mov);
  59.         $this->datagrid->addColumn($column_system_unit_id);
  60.         $this->datagrid->addColumn($column_valor_apurado_maq);
  61.         $this->datagrid->addColumn($column_valor_apurado_talao);
  62.         $this->datagrid->addColumn($column_pagamento_maq);
  63.         $this->datagrid->addColumn($column_pagamento_talao);
  64.         $this->datagrid->addColumn($column_despesas_valor);
  65.         $this->datagrid->addColumn($column_retecao);
  66.         $this->datagrid->addColumn($column_lucro_preju);
  67.         // creates the datagrid column actions
  68.         $column_dt_mov->setAction(new TAction([$this'onReload']), ['order' => 'dt_mov']);
  69.         // define the transformer method over image
  70.         $column_dt_mov->setTransformer( function($value$object$row) {
  71.             if ($value)
  72.             {
  73.                 try
  74.                 {
  75.                     $date = new DateTime($value);
  76.                     return $date->format('d/m/Y');
  77.                 }
  78.                 catch (Exception $e)
  79.                 {
  80.                     return $value;
  81.                 }
  82.             }
  83.             return $value;
  84.         });
  85.         // define the transformer method over image
  86.         $column_valor_apurado_maq->setTransformer( function($value$object$row) {
  87.             if (is_numeric($value))
  88.             {
  89.                 return 'R$ ' number_format($value2',''.');
  90.             }
  91.             return $value;
  92.         });
  93.         // define the transformer method over image
  94.         $column_valor_apurado_talao->setTransformer( function($value$object$row) {
  95.             if (is_numeric($value))
  96.             {
  97.                 return 'R$ ' number_format($value2',''.');
  98.             }
  99.             return $value;
  100.         });
  101.         // define the transformer method over image
  102.         $column_pagamento_maq->setTransformer( function($value$object$row) {
  103.             if (is_numeric($value))
  104.             {
  105.                 return 'R$ ' number_format($value2',''.');
  106.             }
  107.             return $value;
  108.         });
  109.         // define the transformer method over image
  110.         $column_pagamento_talao->setTransformer( function($value$object$row) {
  111.             if (is_numeric($value))
  112.             {
  113.                 return 'R$ ' number_format($value2',''.');
  114.             }
  115.             return $value;
  116.         });
  117.         // define the transformer method over image
  118.         $column_retecao->setTransformer( function($value$object$row) {
  119.             if (is_numeric($value))
  120.             {
  121.                 return 'R$ ' number_format($value2',''.');
  122.             }
  123.             return $value;
  124.         });
  125.         // define the transformer method over image
  126.         $column_lucro_preju->setTransformer( function($value$object$row) {
  127.             if (is_numeric($value))
  128.             {
  129.                 return 'R$ ' number_format($value2',''.');
  130.             }
  131.             return $value;
  132.         });
  133.         $action1 = new TDataGridAction(['MovimentacaoEditLista''onEdit'], ['movimentacao_id'=>'{movimentacao_id}']);
  134.         $action2 = new TDataGridAction([$this'onDelete'], ['movimentacao_id'=>'{movimentacao_id}']);
  135.         $this->datagrid->addAction($action1_t('Edit'),   'far:edit blue');
  136.         $this->datagrid->addAction($action2 ,_t('Delete'), 'far:trash-alt red');
  137.         // create the datagrid model
  138.         $this->datagrid->createModel();
  139.         // creates the page navigation
  140.         $this->pageNavigation = new TPageNavigation;
  141.         $this->pageNavigation->setAction(new TAction([$this'onReload']));
  142.         $this->pageNavigation->setWidth($this->datagrid->getWidth());
  143.         // vertical box container
  144.         $container = new TVBox;
  145.         $container->style 'width: 100%';
  146.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  147.         $container->add($this->form);
  148.         $container->add(TPanelGroup::pack(''$this->datagrid$this->pageNavigation));
  149.         parent::add($container);
  150.     }
  151.     /**
  152.      * Inline record editing
  153.      * @param $param Array containing:
  154.      *              key: object ID value
  155.      *              field name: object attribute to be updated
  156.      *              value: new attribute content
  157.      */
  158.     public function onInlineEdit($param)
  159.     {
  160.         try
  161.         {
  162.             // get the parameter $key
  163.             $field $param['field'];
  164.             $key   $param['key'];
  165.             $value $param['value'];
  166.             TTransaction::open('communication'); // open a transaction with database
  167.             $object = new Movimentacao($key); // instantiates the Active Record
  168.             $object->{$field} = $value;
  169.             $object->store(); // update the object in the database
  170.             TTransaction::close(); // close the transaction
  171.             $this->onReload($param); // reload the listing
  172.             new TMessage('info'"Record Updated");
  173.         }
  174.         catch (Exception $e// in case of exception
  175.         {
  176.             new TMessage('error'$e->getMessage()); // shows the exception error message
  177.             TTransaction::rollback(); // undo all pending operations
  178.         }
  179.     }
  180.     /**
  181.      * Register the filter in the session
  182.      */
  183.     public function onSearch()
  184.     {
  185.         // get the search form data
  186.         $data $this->form->getData();
  187.         // clear session filters
  188.         TSession::setValue(__CLASS__.'_filter_dt_mov',   NULL);
  189.         TSession::setValue(__CLASS__.'_filter_system_unit_id',   NULL);
  190.         if (isset($data->dt_mov) AND ($data->dt_mov)) {
  191.             $filter = new TFilter('dt_mov''like'"%{$data->dt_mov}%"); // create the filter
  192.             TSession::setValue(__CLASS__.'_filter_dt_mov',   $filter); // stores the filter in the session
  193.         }
  194.         if (isset($data->system_unit_id) AND ($data->system_unit_id)) {
  195.             $filter = new TFilter('system_unit_id''='$data->system_unit_id); // create the filter
  196.             TSession::setValue(__CLASS__.'_filter_system_unit_id',   $filter); // stores the filter in the session
  197.         }
  198.         // fill the form with data again
  199.         $this->form->setData($data);
  200.         // keep the search data in the session
  201.         TSession::setValue(__CLASS__ '_filter_data'$data);
  202.         $param = array();
  203.         $param['offset']    =0;
  204.         $param['first_page']=1;
  205.         $this->onReload($param);
  206.     }
  207.     /**
  208.      * Load the datagrid with data
  209.      */
  210.     public function onReload($param NULL)
  211.     {
  212.         try
  213.         {
  214.             // open a transaction with database 'communication'
  215.             TTransaction::open('communication');
  216.             // creates a repository for Movimentacao
  217.             $repository = new TRepository('Movimentacao');
  218.             $limit 10;
  219.             // creates a criteria
  220.             $criteria = new TCriteria;
  221.             // default order
  222.             if (empty($param['order']))
  223.             {
  224.                 $param['order'] = 'movimentacao_id';
  225.                 $param['direction'] = 'asc';
  226.             }
  227.             $criteria->setProperties($param); // order, offset
  228.             $criteria->setProperty('limit'$limit);
  229.             if (TSession::getValue(__CLASS__.'_filter_dt_mov')) {
  230.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_dt_mov')); // add the session filter
  231.             }
  232.             if (TSession::getValue(__CLASS__.'_filter_system_unit_id')) {
  233.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_system_unit_id')); // add the session filter
  234.             }
  235.             // load the objects according to criteria
  236.             $objects $repository->load($criteriaFALSE);
  237.             if (is_callable($this->transformCallback))
  238.             {
  239.                 call_user_func($this->transformCallback$objects$param);
  240.             }
  241.             $this->datagrid->clear();
  242.             if ($objects)
  243.             {
  244.                 // iterate the collection of active records
  245.                 foreach ($objects as $object)
  246.                 {
  247.                     // add the object inside the datagrid
  248.                     $this->datagrid->addItem($object);
  249.                 }
  250.             }
  251.             // reset the criteria for record count
  252.             $criteria->resetProperties();
  253.             $count$repository->count($criteria);
  254.             $this->pageNavigation->setCount($count); // count of records
  255.             $this->pageNavigation->setProperties($param); // order, page
  256.             $this->pageNavigation->setLimit($limit); // limit
  257.             // close the transaction
  258.             TTransaction::close();
  259.             $this->loaded true;
  260.         }
  261.         catch (Exception $e)
  262.         {
  263.             new TMessage('error'$e->getMessage());
  264.             TTransaction::rollback();
  265.         }
  266.     }
  267.     /**
  268.      * Ask before deletion
  269.      */
  270.     public static function onDelete($param)
  271.     {
  272.         // define the delete action
  273.         $action = new TAction([__CLASS__'Delete']);
  274.         $action->setParameters($param); // pass the key parameter ahead
  275.         // shows a dialog to the user
  276.         new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  277.     }
  278.     /**
  279.      * Delete a record
  280.      */
  281.     public static function Delete($param)
  282.     {
  283.         try
  284.         {
  285.             $key=$param['key']; // get the parameter $key
  286.             TTransaction::open('communication'); // open a transaction with database
  287.             $object = new Movimentacao($keyFALSE); // instantiates the Active Record
  288.             $object->delete(); // deletes the object from the database
  289.             TTransaction::close(); // close the transaction
  290.             $pos_action = new TAction([__CLASS__'onReload']);
  291.             new TMessage('info'AdiantiCoreTranslator::translate('Record deleted'), $pos_action); // success message
  292.         }
  293.         catch (Exception $e// in case of exception
  294.         {
  295.             new TMessage('error'$e->getMessage()); // shows the exception error message
  296.             TTransaction::rollback(); // undo all pending operations
  297.         }
  298.     }
  299.     /**
  300.      * method show()
  301.      * Shows the page
  302.      */
  303.     public function show()
  304.     {
  305.         // check if the datagrid is already loaded
  306.         if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'],  array('onReload''onSearch')))) )
  307.         {
  308.             if (func_num_args() > 0)
  309.             {
  310.                 $this->onReloadfunc_get_arg(0) );
  311.             }
  312.             else
  313.             {
  314.                 $this->onReload();
  315.             }
  316.         }
  317.         parent::show();
  318.     }
  319. }
  320. ?>




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


NR

Se o filtro é fixo, sugiro colocá-lo diretamente na função onReload. Ex:
  1. <?php
  2. // onReload
  3. $criteria->add(new TFilter('system_unit_id''='TSession::getValue('userunitid')));
  4. ?>

Nesse caso não precisaria de campo no formulário e nem controle na função onSearch.