Lançado Adianti Framework 8.1!
Clique aqui para saber mais
DataGrid com Criterios estou tentando filtrar os itens exibidos em um datagrid mas não estou tendo sucesso, gostaria de saber se tem como usar a classe TCriteria para filtrar estou tentando utilizar o criterio no bloco de código abaixo da função onReload. ...
PP
DataGrid com Criterios  
estou tentando filtrar os itens exibidos em um datagrid mas não estou tendo sucesso, gostaria de saber se tem como usar a classe TCriteria para filtrar estou tentando utilizar o criterio no bloco de código abaixo da função onReload.

  1. <?php
  2.             if (TSession::getValue('ListaList_filter_id')) {
  3.                 $criteria->add(TSession::getValue('ListaList_filter_id')); // add the session filter
  4.             }
  5.             if (TSession::getValue('ListaList_filter_nome')) {
  6.                 $criteria->add(TSession::getValue('ListaList_filter_nome')); // add the session filter
  7.             }
  8. ?>

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


NR

Não retorna nenhum dado na grid ou os dados não estão considerando o filtro?

Execute o comando abaixo para verificar o sql que está sendo executado:
  1. <?php
  2. TTransaction::setLogger(new TLoggerSTD());
  3. ?>
PP

Não consideram o filtro
NR

Poste o código
PP

  1. <?php
  1. <?php
  2. /**
  3.  * PerfilForm Form
  4.  * @author  <gestoo ti>
  5.  */
  6. class PerfilForm extends TPage
  7. {
  8.     protected $form// form
  9.     
  10.     /**
  11.      * Form constructor
  12.      * @param $param Request
  13.      */
  14.     public function __construct$param )
  15.     {
  16.         parent::__construct();
  17.         
  18.         // creates the form
  19.         $this->form = new TQuickForm('form_Perfil');
  20.         $this->form->class 'tform'// change CSS class
  21.         $this->form = new BootstrapFormWrapper($this->form);
  22.         $this->form->style 'display: table;width:100%'// change style
  23.         
  24.         // define the form title
  25.         $this->form->setFormTitle('Perfil');
  26.         
  27.         // create the form fields
  28.         $id = new TEntry('id');
  29.         $system_user_id = new TDBCombo('system_user_id''sample''system');
  30.         $nome = new TEntry('nome');
  31.         $cpf = new TEntry('cpf');
  32.         $cnpj = new TEntry('cnpj');
  33.         $email = new TEntry('email');
  34.         $telefone = new TEntry('telefone');
  35.         $endereco = new TEntry('endereco');
  36.         $cidade = new TCombo('cidade');
  37.         $uf = new TEntry('uf');
  38.         $this->form->setFieldsByRow(2); // numero de colunas do formulario
  39.         // add the fields
  40.         $this->form->addQuickField('Id'$id,  100 );
  41.         $this->form->addQuickField('Usuário'$system_user_id,  100 );
  42.         $this->form->addQuickField('Nome'$nome,  200 );
  43.         $this->form->addQuickField('CPF'$cpf,  200 );
  44.         $this->form->addQuickField('CNPJ'$cnpj,  200 );
  45.         $this->form->addQuickField('Email'$email,  200 );
  46.         $this->form->addQuickField('Telefone'$telefone,  200 );
  47.         $this->form->addQuickField('Endereço'$endereco,  200 );
  48.         $this->form->addQuickField('Cidade'$cidade,  200 );
  49.         $this->form->addQuickField('UF'$uf,  200 );
  50.         
  51.         $system_user_id->setSize('100%');
  52.         $nome->setSize('100%');
  53.         $cpf->setSize('100%');
  54.         $cnpj->setSize('100%');
  55.         $email->setSize('100%');
  56.         $telefone->setSize('100%');
  57.         $endereco->setSize('100%');
  58.         $cidade->setSize('100%');
  59.         $uf->setSize('100%');
  60.         if (!empty($id))
  61.         {
  62.             $id->setEditable(FALSE);
  63.         }
  64.         
  65.         /** samples
  66.          $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  67.          $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  68.          $fieldX->setSize( 100, 40 ); // set size
  69.          **/
  70.          
  71.         // create the form actions
  72.         $this->form->addQuickAction(_t('Save'), new TAction(array($this'onSave')), 'fa:floppy-o');
  73.         $this->form->addQuickAction(_t('New'),  new TAction(array($this'onClear')), 'bs:plus-sign green');
  74.         
  75.         // vertical box container
  76.         $container = new TVBox;
  77.         $container->style 'width: 100%';
  78.         $container->add(new TXMLBreadCrumb('menu.xml'__CLASS__));
  79.         $container->add(TPanelGroup::pack('Cadastro de Perfil'$this->form));
  80.         
  81.         parent::add($container);
  82.     }
  83.     /**
  84.      * Save form data
  85.      * @param $param Request
  86.      */
  87.     public function onSave$param )
  88.     {
  89.         try
  90.         {
  91.             TTransaction::open('sample'); // open a transaction
  92.             
  93.             /**
  94.             // Enable Debug logger for SQL operations inside the transaction
  95.             TTransaction::setLogger(new TLoggerSTD); // standard output
  96.             TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
  97.             **/
  98.             
  99.             $this->form->validate(); // validate form data
  100.             
  101.             $object = new Perfil;  // create an empty object
  102.             $data $this->form->getData(); // get form data as array
  103.             $object->fromArray( (array) $data); // load the object with data
  104.             $object->store(); // save the object
  105.             
  106.             // get the generated id
  107.             $data->id $object->id;
  108.             
  109.             $this->form->setData($data); // fill form data
  110.             TTransaction::close(); // close the transaction
  111.             
  112.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  113.         }
  114.         catch (Exception $e// in case of exception
  115.         {
  116.             new TMessage('error'$e->getMessage()); // shows the exception error message
  117.             $this->form->setData$this->form->getData() ); // keep form data
  118.             TTransaction::rollback(); // undo all pending operations
  119.         }
  120.     }
  121.     
  122.     /**
  123.      * Clear form data
  124.      * @param $param Request
  125.      */
  126.     public function onClear$param )
  127.     {
  128.         $this->form->clear(TRUE);
  129.     }
  130.     
  131.     /**
  132.      * Load object to form data
  133.      * @param $param Request
  134.      */
  135.     public function onEdit$param )
  136.     {
  137.         try
  138.         {
  139.             if (isset($param['key']))
  140.             {
  141.                 $key $param['key'];  // get the parameter $key
  142.                 TTransaction::open('sample'); // open a transaction
  143.                 $object = new Perfil($key); // instantiates the Active Record
  144.                 $this->form->setData($object); // fill the form
  145.                 TTransaction::close(); // close the transaction
  146.             }
  147.             else
  148.             {
  149.                 $this->form->clear(TRUE);
  150.             }
  151.         }
  152.         catch (Exception $e// in case of exception
  153.         {
  154.             new TMessage('error'$e->getMessage()); // shows the exception error message
  155.             TTransaction::rollback(); // undo all pending operations
  156.         }
  157.     }
  158. }
  159. ?>
</gestoo>
PP

Desculpa o código correto.

  1. <?php
  1. <?php
  2. /**
  3.  * ListaList Listing
  4.  * @author  <your name here>
  5.  */
  6. class ListaList 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 TQuickForm('form_search_Lista');
  25.         $this->form->class 'tform'// change CSS class
  26.         $this->form = new BootstrapFormWrapper($this->form);
  27.         $this->form->style 'display: table;width:100%'// change style
  28.         $this->form->setFormTitle('Lista');
  29.         
  30.         // create the form fields
  31.         $id = new TEntry('id');
  32.         $nome = new TEntry('nome');
  33.         $system_user_id = new TEntry('system_user_id');
  34.         // add the fields
  35.         $this->form->addQuickField('Id'$id,  200 );
  36.         $this->form->addQuickField('Nome'$nome,  200 );
  37.         $this->form->addQuickField('Usuário'$system_user_id,  200 );
  38.         
  39.         // keep the form filled during navigation with session data
  40.         $this->form->setDataTSession::getValue('Lista_filter_data') );
  41.         
  42.         // add the search form actions
  43.         $this->form->addQuickAction(_t('Find'), new TAction(array($this'onSearch')), 'fa:search');
  44.         $this->form->addQuickAction(_t('New'),  new TAction(array('ListaForm''onEdit')), 'bs:plus-sign green');
  45.         
  46.         // creates a Datagrid
  47.         $this->datagrid = new TDataGrid;
  48.         $this->datagrid = new BootstrapDatagridWrapper($this->datagrid);
  49.         $this->datagrid->style 'width: 100%';
  50.         $this->datagrid->datatable 'true';
  51.         // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  52.         
  53.         // creates the datagrid columns
  54.         $column_check = new TDataGridColumn('check''''center');
  55.         $column_id = new TDataGridColumn('id''Id''right');
  56.         $column_nome = new TDataGridColumn('nome''Nome''left');
  57.         $column_system_user_id = new TDataGridColumn('system_user_id''Usuário''right');
  58.         // add the columns to the DataGrid
  59.         $this->datagrid->addColumn($column_check);
  60.         $this->datagrid->addColumn($column_id);
  61.         $this->datagrid->addColumn($column_nome);
  62.         $this->datagrid->addColumn($column_system_user_id);
  63.         
  64.         // create EDIT action
  65.         $action_edit = new TDataGridAction(array('ListaForm''onEdit'));
  66.         $action_edit->setUseButton(TRUE);
  67.         $action_edit->setButtonClass('btn btn-default');
  68.         $action_edit->setLabel(_t('Edit'));
  69.         $action_edit->setImage('fa:pencil-square-o blue fa-lg');
  70.         $action_edit->setField('id');
  71.         $this->datagrid->addAction($action_edit);
  72.         
  73.         // create DELETE action
  74.         $action_del = new TDataGridAction(array($this'onDelete'));
  75.         $action_del->setUseButton(TRUE);
  76.         $action_del->setButtonClass('btn btn-default');
  77.         $action_del->setLabel(_t('Delete'));
  78.         $action_del->setImage('fa:trash-o red fa-lg');
  79.         $action_del->setField('id');
  80.         $this->datagrid->addAction($action_del);
  81.         
  82.         // create the datagrid model
  83.         $this->datagrid->createModel();
  84.         
  85.         // creates the page navigation
  86.         $this->pageNavigation = new TPageNavigation;
  87.         $this->pageNavigation->setAction(new TAction(array($this'onReload')));
  88.         $this->pageNavigation->setWidth($this->datagrid->getWidth());
  89.         
  90.         $this->datagrid->disableDefaultClick();
  91.         
  92.         // put datagrid inside a form
  93.         $this->formgrid = new TForm;
  94.         $this->formgrid->add($this->datagrid);
  95.         
  96.         // creates the delete collection button
  97.         $this->deleteButton = new TButton('delete_collection');
  98.         $this->deleteButton->setAction(new TAction(array($this'onDeleteCollection')), AdiantiCoreTranslator::translate('Delete selected'));
  99.         $this->deleteButton->setImage('fa:remove red');
  100.         $this->formgrid->addField($this->deleteButton);
  101.         
  102.         $gridpack = new TVBox;
  103.         $gridpack->style 'width: 100%';
  104.         $gridpack->add($this->formgrid);
  105.         $gridpack->add($this->deleteButton)->style 'background:whiteSmoke;border:1px solid #cccccc; padding: 3px;padding: 5px;';
  106.         
  107.         $this->transformCallback = array($this'onBeforeLoad');
  108.         // vertical box container
  109.         $container = new TVBox;
  110.         $container->style 'width: 90%';
  111.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  112.         $container->add(TPanelGroup::pack('Title'$this->form));
  113.         $container->add($gridpack);
  114.         $container->add($this->pageNavigation);
  115.         
  116.         parent::add($container);
  117.     }
  118.     
  119.     /**
  120.      * Inline record editing
  121.      * @param $param Array containing:
  122.      *              key: object ID value
  123.      *              field name: object attribute to be updated
  124.      *              value: new attribute content 
  125.      */
  126.     public function onInlineEdit($param)
  127.     {
  128.         try
  129.         {
  130.             // get the parameter $key
  131.             $field $param['field'];
  132.             $key   $param['key'];
  133.             $value $param['value'];
  134.             
  135.             TTransaction::open('sample'); // open a transaction with database
  136.             $object = new Lista($key); // instantiates the Active Record
  137.             $object->{$field} = $value;
  138.             $object->store(); // update the object in the database
  139.             TTransaction::close(); // close the transaction
  140.             
  141.             $this->onReload($param); // reload the listing
  142.             new TMessage('info'"Record Updated");
  143.         }
  144.         catch (Exception $e// in case of exception
  145.         {
  146.             new TMessage('error''<b>Error</b> ' $e->getMessage()); // shows the exception error message
  147.             TTransaction::rollback(); // undo all pending operations
  148.         }
  149.     }
  150.     
  151.     /**
  152.      * Register the filter in the session
  153.      */
  154.     public function onSearch()
  155.     {
  156.         // get the search form data
  157.         $data $this->form->getData();
  158.         
  159.         // clear session filters
  160.         TSession::setValue('ListaList_filter_id',   NULL);
  161.         TSession::setValue('ListaList_filter_nome',   NULL);
  162.         TSession::setValue('ListaList_filter_system_user_id',   NULL);
  163.         if (isset($data->id) AND ($data->id)) {
  164.             $filter = new TFilter('id''like'"%{$data->id}%"); // create the filter
  165.             TSession::setValue('ListaList_filter_id',   $filter); // stores the filter in the session
  166.         }
  167.         if (isset($data->nome) AND ($data->nome)) {
  168.             $filter = new TFilter('nome''like'"%{$data->nome}%"); // create the filter
  169.             TSession::setValue('ListaList_filter_nome',   $filter); // stores the filter in the session
  170.         }
  171.         if (isset($data->system_user_id) AND ($data->system_user_id)) {
  172.             $filter = new TFilter('system_user_id''='"$data->system_user_id"); // create the filter
  173.             TSession::setValue('ListaList_filter_system_user_id',   $filter); // stores the filter in the session
  174.         }
  175.         
  176.         // fill the form with data again
  177.         $this->form->setData($data);
  178.         
  179.         // keep the search data in the session
  180.         TSession::setValue('Lista_filter_data'$data);
  181.         
  182.         $param=array();
  183.         $param['offset']    =0;
  184.         $param['first_page']=1;
  185.         $this->onReload($param);
  186.     }
  187.     
  188.     /**
  189.      * Load the datagrid with data
  190.      */
  191.     public function onReload($param NULL)
  192.     {
  193.         try
  194.         {
  195.             // open a transaction with database 'sample'
  196.             TTransaction::open('sample');
  197.             
  198.             // creates a repository for Lista
  199.             $repository = new TRepository('Lista');
  200.             $limit 10;
  201.             // creates a criteria
  202.             $criteria = new TCriteria;
  203.             //$criteria->add(new TFilter('system_user_id' = 1);
  204.             
  205.             
  206.             // default order
  207.             if (empty($param['order']))
  208.             {
  209.                 $param['order'] = 'id';
  210.                 $param['direction'] = 'asc';
  211.             }
  212.             $criteria->setProperties($param); // order, offset
  213.             $criteria->setProperty('limit'$limit);
  214.             
  215.             if (TSession::getValue('ListaList_filter_id')) {
  216.                 $criteria->add(TSession::getValue('ListaList_filter_id')); // add the session filter
  217.             }
  218.             if (TSession::getValue('ListaList_filter_nome')) {
  219.                 $criteria->add(TSession::getValue('ListaList_filter_nome')); // add the session filter
  220.             }
  221.             if (TSession::getValue('ListaList_filter_system_user_id')) {
  222.                 $criteria->add(TSession::getValue('ListaList_filter_system_user_id')); // add the session filter
  223.             }
  224.             
  225.             // load the objects according to criteria
  226.             $objects $repository->load($criteriaFALSE);
  227.             
  228.             if (is_callable($this->transformCallback))
  229.             {
  230.                 call_user_func($this->transformCallback$objects$param);
  231.             }
  232.             
  233.             $this->datagrid->clear();
  234.             if ($objects)
  235.             {
  236.                 // iterate the collection of active records
  237.                 foreach ($objects as $object)
  238.                 {
  239.                     // add the object inside the datagrid
  240.                     $this->datagrid->addItem($object);
  241.                 }
  242.             }
  243.             
  244.             // reset the criteria for record count
  245.             $criteria->resetProperties();
  246.             $count$repository->count($criteria);
  247.             
  248.             $this->pageNavigation->setCount($count); // count of records
  249.             $this->pageNavigation->setProperties($param); // order, page
  250.             $this->pageNavigation->setLimit($limit); // limit
  251.             
  252.             // close the transaction
  253.             TTransaction::close();
  254.             $this->loaded true;
  255.         }
  256.         catch (Exception $e// in case of exception
  257.         {
  258.             // shows the exception error message
  259.             new TMessage('error'$e->getMessage());
  260.             // undo all pending operations
  261.             TTransaction::rollback();
  262.         }
  263.     }
  264.     
  265.     /**
  266.      * Ask before deletion
  267.      */
  268.     public function onDelete($param)
  269.     {
  270.         // define the delete action
  271.         $action = new TAction(array($this'Delete'));
  272.         $action->setParameters($param); // pass the key parameter ahead
  273.         
  274.         // shows a dialog to the user
  275.         new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  276.     }
  277.     
  278.     /**
  279.      * Delete a record
  280.      */
  281.     public function Delete($param)
  282.     {
  283.         try
  284.         {
  285.             $key=$param['key']; // get the parameter $key
  286.             TTransaction::open('sample'); // open a transaction with database
  287.             $object = new Lista($keyFALSE); // instantiates the Active Record
  288.             $object->delete(); // deletes the object from the database
  289.             TTransaction::close(); // close the transaction
  290.             $this->onReload$param ); // reload the listing
  291.             new TMessage('info'AdiantiCoreTranslator::translate('Record deleted')); // 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.     /**
  301.      * Ask before delete record collection
  302.      */
  303.     public function onDeleteCollection$param )
  304.     {
  305.         $data $this->formgrid->getData(); // get selected records from datagrid
  306.         $this->formgrid->setData($data); // keep form filled
  307.         
  308.         if ($data)
  309.         {
  310.             $selected = array();
  311.             
  312.             // get the record id's
  313.             foreach ($data as $index => $check)
  314.             {
  315.                 if ($check == 'on')
  316.                 {
  317.                     $selected[] = substr($index,5);
  318.                 }
  319.             }
  320.             
  321.             if ($selected)
  322.             {
  323.                 // encode record id's as json
  324.                 $param['selected'] = json_encode($selected);
  325.                 
  326.                 // define the delete action
  327.                 $action = new TAction(array($this'deleteCollection'));
  328.                 $action->setParameters($param); // pass the key parameter ahead
  329.                 
  330.                 // shows a dialog to the user
  331.                 new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  332.             }
  333.         }
  334.     }
  335.     
  336.     /**
  337.      * method deleteCollection()
  338.      * Delete many records
  339.      */
  340.     public function deleteCollection($param)
  341.     {
  342.         // decode json with record id's
  343.         $selected json_decode($param['selected']);
  344.         
  345.         try
  346.         {
  347.             TTransaction::open('sample');
  348.             if ($selected)
  349.             {
  350.                 // delete each record from collection
  351.                 foreach ($selected as $id)
  352.                 {
  353.                     $object = new Lista;
  354.                     $object->delete$id );
  355.                 }
  356.                 $posAction = new TAction(array($this'onReload'));
  357.                 $posAction->setParameters$param );
  358.                 new TMessage('info'AdiantiCoreTranslator::translate('Records deleted'), $posAction);
  359.             }
  360.             TTransaction::close();
  361.         }
  362.         catch (Exception $e)
  363.         {
  364.             new TMessage('error'$e->getMessage());
  365.             TTransaction::rollback();
  366.         }
  367.     }
  368.     /**
  369.      * Transform datagrid objects
  370.      * Create the checkbutton as datagrid element
  371.      */
  372.     public function onBeforeLoad($objects$param)
  373.     {
  374.         // update the action parameters to pass the current page to action
  375.         // without this, the action will only work for the first page
  376.         $deleteAction $this->deleteButton->getAction();
  377.         $deleteAction->setParameters($param); // important!
  378.         
  379.         $gridfields = array( $this->deleteButton );
  380.         
  381.         foreach ($objects as $object)
  382.         {
  383.             $object->check = new TCheckButton('check' $object->id);
  384.             $object->check->setIndexValue('on');
  385.             $gridfields[] = $object->check// important
  386.         }
  387.         
  388.         $this->formgrid->setFields($gridfields);
  389.     }
  390.     
  391.     /**
  392.      * method show()
  393.      * Shows the page
  394.      */
  395.     public function show()
  396.     {
  397.         // check if the datagrid is already loaded
  398.         if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'],  array('onReload''onSearch')))) )
  399.         {
  400.             if (func_num_args() > 0)
  401.             {
  402.                 $this->onReloadfunc_get_arg(0) );
  403.             }
  404.             else
  405.             {
  406.                 $this->onReload();
  407.             }
  408.         }
  409.         parent::show();
  410.     }
  411. }
  412. ?>
</your>
NR

O que aconteceu aqui foi o seguinte: os filtros funcionam quando clico no botão buscar, mas não funcionam com o enter.

Veja se acontece o mesmo com você. Se for o caso, utilize a classe BootstrapFormBuilder ao invés de BootstrapFormWrapper.
PP

Ok isso eu já entendi, o que necessito é que o data grid já carregue com os filtros.