Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Criar um contador de registros e apresentar no Datagrid Boa noite pessoal, Eu tenho uma dúvida, que pode ser fácil para os mais experientes, mas eu não estou conseguindo fazer. Eu tenho um cadastro de alunos e estou criando um datagrid com filtros para listar alunos ativos e alunos inativos. Eu preciso mostrar em algum lugar do meu datagrid o total de alunos para cada situação. Eu desenhei mais ou menos o que gostaria de fazer e estou enviando e...
FS
Criar um contador de registros e apresentar no Datagrid  
Fechado
Boa noite pessoal,
Eu tenho uma dúvida, que pode ser fácil para os mais experientes, mas eu não estou conseguindo fazer.
Eu tenho um cadastro de alunos e estou criando um datagrid com filtros para listar alunos ativos e alunos inativos. Eu preciso mostrar em algum lugar do meu datagrid o total de alunos para cada situação. Eu desenhei mais ou menos o que gostaria de fazer e estou enviando em anexo juntamente com o código do datagrid. O Form eu fiz pelo Form Designer.

Se ficou alguma dúvida me perguntem por favor.

Obrigado.


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


MS

Bom dia Fabiano. Se entendi bem existem duas formas bem tranquilas, a primeira você conta no onReload() a segunda você faz um SQL para contar. Porém eu sei fazer isso passando o valor para um TEntry:

1 - Você pode contar isso no método onReload() da seguinte forma
  1. <?php
  2.             $this->datagrid->clear();
  3.             if ($objects) {
  4.                 foreach ($objects as $object) {
  5.                     $this->datagrid->addItem($object);                  
  6.                    
  7.                     //Contagem
  8.                     if ($object->situacao 'Ativo'){
  9.                         $countAtivo++;
  10.                     }else{
  11.                         $countInativo++;
  12.                     }
  13.                         
  14.                 }
  15.             }
  16. ?>


2 - Depois é só enviar para o formulário:
  1. <?php
  2.             //Envio conforme as classes TSeek
  3.             $object = new stdClass();
  4.             $object->EntryAtivos $countAtivo;
  5.             $object->EntryInativos $countInativo;
  6.             $uteis->sendData($this->form->getName(), $object);
  7. ?>


Se tem outro jeito, eu desconheço.
MS

Tem um errinho no teste "if ($object->situacao = 'Ativo')", eu coloquei apenas um "=" e são dois "==".
FS

Primeiramente muito obrigado Mailson, só desculpa minha ignorância, mas não entendi em que lugar no código eu devo colocar o item 2 que você passou. É ainda no onReload?


  1. <?php
  2.             //Envio conforme as classes TSeek
  3.             $object = new stdClass();
  4.             $object->EntryAtivos $countAtivo;
  5.             $object->EntryInativos $countInativo;
  6.             $uteis->sendData($this->form->getName(), $object);
  7. ?>
MS

Tem um detalhe, eu estendi algumas funções do framework. Mas acredito que o teu onReload() ficaria próximo disso:
  1. <?php
  2. function onReload($param NULL) {
  3.         try {
  4.             // open a transaction with database 'una'
  5.             TTransaction::open('una');
  6.             // creates a repository for Alunos
  7.             $repository = new TRepository('Alunos');
  8.             $limit 10;
  9.             // creates a criteria
  10.             $criteria = new TCriteria;
  11.             // default order
  12.             if (empty($param['order'])) {
  13.                 $param['order'] = 'id';
  14.                 $param['direction'] = 'asc';
  15.             }
  16.             $criteria->setProperties($param); // order, offset
  17.             $criteria->setProperty('limit'$limit);
  18.             if (TSession::getValue('AlunosListAcad_filter_nome')) {
  19.                 $criteria->add(TSession::getValue('AlunosListAcad_filter_nome')); // add the session filter
  20.             }
  21.             if (TSession::getValue('AlunosListAcad_filter_linguas')) {
  22.                 $criteria->add(TSession::getValue('AlunosListAcad_filter_linguas')); // add the session filter
  23.             }
  24.             if (TSession::getValue('AlunosListAcad_filter_nivel')) {
  25.                 $criteria->add(TSession::getValue('AlunosListAcad_filter_nivel')); // add the session filter
  26.             }
  27.             if (TSession::getValue('AlunosListAcad_filter_professor')) {
  28.                 $criteria->add(TSession::getValue('AlunosListAcad_filter_professor')); // add the session filter
  29.             }
  30.             if (TSession::getValue('AlunosListAcad_filter_situacao')) {
  31.                 $criteria->add(TSession::getValue('AlunosListAcad_filter_situacao')); // add the session filter
  32.             }
  33.             // load the objects according to criteria
  34.             $objects $repository->load($criteriaFALSE);
  35.             $countAtivo 0;
  36.             $countInativo 0;
  37.             $this->datagrid->clear();
  38.             if ($objects) {
  39.                 // iterate the collection of active records
  40.                 foreach ($objects as $object) {
  41.                     // add the object inside the datagrid
  42.                     $this->datagrid->addItem($object);
  43.                     //Contagem
  44.                     if ($object->situacao == 'Ativo') {
  45.                         $countAtivo++;
  46.                     } else {
  47.                         $countInativo++;
  48.                     }
  49.                 }
  50.             }
  51.             //Envio conforme as classes TSeek
  52.             $object = new stdClass();
  53.             $object->EntryAtivos $countAtivo//Você deve alterar o nome dos componentes TEntry()
  54.             $object->EntryInativos $countInativo//Você deve alterar o nome dos componentes TEntry()
  55.             TForm::sendData($this->form->getName(), $object);
  56.             // reset the criteria for record count
  57.             $criteria->resetProperties();
  58.             $count $repository->count($criteria);
  59.             $this->pageNavigation->setCount($count); // count of records
  60.             $this->pageNavigation->setProperties($param); // order, page
  61.             $this->pageNavigation->setLimit($limit); // limit
  62.             // close the transaction
  63.             TTransaction::close();
  64.             $this->loaded true;
  65.         } catch (Exception $e) { // in case of exception
  66.             // shows the exception error message
  67.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  68.             // undo all pending operations
  69.             TTransaction::rollback();
  70.         }
  71.     }
  72. ?>
MS

Segue um exemplo simples mas funcional. Substitua esse código pelo código da classe "DocumentList.class" da aplicação de exemplo changeman.
  1. <?php
  2. /**
  3.  * DocumentList Listing
  4.  * @author  <your name here>
  5.  */
  6. class DocumentList extends TPage {
  7.     private $form;     // registration form
  8.     private $datagrid// listing
  9.     private $pageNavigation;
  10.     private $loaded;
  11.     /**
  12.      * Class constructor
  13.      * Creates the page, the form and the listing
  14.      */
  15.     public function __construct() {
  16.         parent::__construct();
  17.         // security check
  18.         if (TSession::getValue('logged') !== TRUE) {
  19.             throw new Exception(_t('Not logged'));
  20.         }
  21.         // creates the form
  22.         $this->form = new TForm('form_search_Document');
  23.         // creates a table
  24.         $table = new TTable;
  25.         $table->width '100%';
  26.         // add the table inside the form
  27.         $this->form->add($table);
  28.         $this->form->class 'tform';
  29.         $table->addRowSet(new TLabel(_t('Documents')), '')->class 'tformtitle';
  30.         // create the form fields
  31.         $filter = new TEntry('title');
  32.         $filter->setSize(400);
  33.         $filter->setValue(TSession::getValue('Document_title'));
  34.         // add a row for the filter field
  35.         $row $table->addRow();
  36.         $row->addCell(new TLabel(_t('Title') . ': '));
  37.         $row->addCell($filter);
  38.         // create two action buttons to the form
  39.         $find_button = new TButton('find');
  40.         $new_button = new TButton('new');
  41.         // define the button actions
  42.         $find_button->setAction(new TAction(array($this'onSearch')), _t('Find'));
  43.         $find_button->setImage('ico_find.png');
  44.         // add a row for the form actions
  45.         $row $table->addRow();
  46.         $buttons[] = $find_button;
  47.         // security check
  48.         TTransaction::open('changeman');
  49.         if ((Member::newFromLogin(TSession::getValue('login'))->role_mnemonic == 'ADMINISTRATOR') OR ( Member::newFromLogin(TSession::getValue('login'))->role_mnemonic == 'MANAGER')) {
  50.             $class 'DocumentForm';
  51.             $new_button->setAction(new TAction(array($class'onEdit')), _t('New'));
  52.             $new_button->setImage('ico_new.png');
  53.             $buttons[] = $new_button;
  54.         }
  55.         TTransaction::close();
  56.         $table->addRowSet(''$buttons)->class 'tformaction';
  57.         $entMenores = new TEntry('entMenores');
  58.         $entMaiores = new TEntry('entMaiores');
  59.         $row $table->addRow();
  60.         $row->addCell(new TLabel("ID menor que 2:"));
  61.         $row->addCell($entMenores);
  62.         $row->addCell(new TLabel("Maiores:"));
  63.         $row->addCell($entMaiores);
  64.         // define wich are the form fields
  65.         $this->form->setFields(array($filter$find_button$new_button$entMenores$entMaiores));
  66.         // creates a DataGrid
  67.         $this->datagrid = new TDataGrid;
  68.         $this->datagrid->setHeight(320);
  69.         // creates the datagrid columns
  70.         $id = new TDataGridColumn('id''ID''right'50);
  71.         $id_project = new TDataGridColumn('project'_t('Project'), 'left'200);
  72.         $title = new TDataGridColumn('title'_t('Title'), 'left'400);
  73.         // creates the datagrid actions
  74.         $order1 = new TAction(array($this'onReload'));
  75.         $order2 = new TAction(array($this'onReload'));
  76.         $order3 = new TAction(array($this'onReload'));
  77.         // define the ordering parameters
  78.         $order1->setParameter('order''id');
  79.         $order2->setParameter('order''id_project');
  80.         $order3->setParameter('order''title');
  81.         // assign the ordering actions
  82.         $id->setAction($order1);
  83.         $id_project->setAction($order2);
  84.         $title->setAction($order3);
  85.         // add the columns to the DataGrid
  86.         $this->datagrid->addColumn($id);
  87.         $this->datagrid->addColumn($id_project);
  88.         $this->datagrid->addColumn($title);
  89.         // security check
  90.         TTransaction::open('changeman');
  91.         if ((Member::newFromLogin(TSession::getValue('login'))->role_mnemonic == 'ADMINISTRATOR') OR ( Member::newFromLogin(TSession::getValue('login'))->role_mnemonic == 'MANAGER')) {
  92.             // creates two datagrid actions
  93.             $class 'DocumentForm';
  94.             $action1 = new TDataGridAction(array($class'onEdit'));
  95.             $action1->setLabel(_t('Edit'));
  96.             $action1->setImage('ico_edit.png');
  97.             $action1->setField('id');
  98.             $action2 = new TDataGridAction(array($this'onDelete'));
  99.             $action2->setLabel(_t('Delete'));
  100.             $action2->setImage('ico_delete.png');
  101.             $action2->setField('id');
  102.             // add the actions to the datagrid
  103.             $this->datagrid->addAction($action1);
  104.             $this->datagrid->addAction($action2);
  105.         } else {
  106.             // creates two datagrid actions
  107.             $class 'ViewDocumentForm';
  108.             $action1 = new TDataGridAction(array($class'onView'));
  109.             $action1->setLabel(_t('View'));
  110.             $action1->setImage('ico_view.png');
  111.             $action1->setField('id');
  112.             // add the actions to the datagrid
  113.             $this->datagrid->addAction($action1);
  114.         }
  115.         TTransaction::close();
  116.         // create the datagrid model
  117.         $this->datagrid->createModel();
  118.         // creates the page navigation
  119.         $this->pageNavigation = new TPageNavigation;
  120.         $this->pageNavigation->setAction(new TAction(array($this'onReload')));
  121.         $this->pageNavigation->setWidth($this->datagrid->getWidth());
  122.         // creates the page structure using a vbox
  123.         $container = new TVBox;
  124.         $container->add($this->form);
  125.         $container->add($this->datagrid);
  126.         $container->add($this->pageNavigation);
  127.         // add the vbox inside the page
  128.         parent::add($container);
  129.     }
  130.     /**
  131.      * method onSearch()
  132.      * Register the filter in the session when the user performs a search
  133.      */
  134.     function onSearch() {
  135.         // get the search form data
  136.         $data $this->form->getData();
  137.         TSession::setValue('Document_filter'NULL);
  138.         TSession::setValue('Document_title''');
  139.         // check if the user has filled the form
  140.         if (isset($data->title)) {
  141.             // creates a filter using what the user has typed
  142.             $filter = new TFilter('title''like'"%{$data->title}%");
  143.             // stores the filter in the session
  144.             TSession::setValue('Document_filter'$filter);
  145.             TSession::setValue('Document_title'$data->title);
  146.             // fill the form with data again
  147.             $this->form->setData($data);
  148.         }
  149.         $param = array();
  150.         $param['offset'] = 0;
  151.         $param['first_page'] = 1;
  152.         $this->onReload($param);
  153.     }
  154.     /**
  155.      * method onReload()
  156.      * Load the datagrid with the database objects
  157.      */
  158.     function onReload($param NULL) {
  159.         try {
  160.             // open a transaction with database 'changeman'
  161.             TTransaction::open('changeman');
  162.             $member Member::newFromLogin(TSession::getValue('login'));
  163.             // creates a repository for Document
  164.             $repository = new TRepository('Document');
  165.             $limit 10;
  166.             // creates a criteria
  167.             $criteria = new TCriteria;
  168.             $criteria->setProperties($param); // order, offset
  169.             $criteria->setProperty('limit'$limit);
  170.             if (TSession::getValue('Document_filter')) {
  171.                 // add the filter stored in the session to the criteria
  172.                 $criteria->add(TSession::getValue('Document_filter'));
  173.             }
  174.             // customer may only view its projects
  175.             if (($member->role_mnemonic == 'CUSTOMER')) {
  176.                 $member_projects_ids array_keys($member->getProjectsList());
  177.                 $criteria->add(new TFilter('id_project''IN'$member_projects_ids));
  178.             }
  179.             // load the objects according to criteria
  180.             $objects $repository->load($criteria);
  181.             $menores 0;
  182.             $maiores 0;
  183.             $this->datagrid->clear();
  184.             if ($objects) {
  185.                 // iterate the collection of active records
  186.                 foreach ($objects as $object) {
  187.                     // add the object inside the datagrid
  188.                     $this->datagrid->addItem($object);
  189.                     if ($object->id 2) {
  190.                         $menores++;
  191.                     } else {
  192.                         $maiores++;
  193.                     }
  194.                 }
  195.             }
  196.             // reset the criteria for record count
  197.             $criteria->resetProperties();
  198.             $count $repository->count($criteria);
  199.             $this->pageNavigation->setCount($count); // count of records
  200.             $this->pageNavigation->setProperties($param); // order, page
  201.             $this->pageNavigation->setLimit($limit); // limit
  202.             // close the transaction
  203.             TTransaction::close();
  204.             $this->loaded true;
  205.             $object = new stdClass();
  206.             $object->entMenores $menores//Você deve alterar o nome dos componentes TEntry()
  207.             $object->entMaiores $maiores//Você deve alterar o nome dos componentes TEntry()
  208.             TForm::sendData($this->form->getName(), $object);
  209.         } catch (Exception $e) { // in case of exception
  210.             // shows the exception error message
  211.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  212.             // undo all pending operations
  213.             TTransaction::rollback();
  214.         }
  215.     }
  216.     /**
  217.      * method onDelete()
  218.      * executed whenever the user clicks at the delete button
  219.      * Ask if the user really wants to delete the record
  220.      */
  221.     function onDelete($param) {
  222.         // get the parameter $key
  223.         $key $param['key'];
  224.         // define two actions
  225.         $action = new TAction(array($this'Delete'));
  226.         // define the action parameters
  227.         $action->setParameter('key'$key);
  228.         // shows a dialog to the user
  229.         new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  230.     }
  231.     /**
  232.      * method Delete()
  233.      * Delete a record
  234.      */
  235.     function Delete($param) {
  236.         try {
  237.             // get the parameter $key
  238.             $key $param['key'];
  239.             // open a transaction with database 'changeman'
  240.             TTransaction::open('changeman');
  241.             // instantiates object Document
  242.             $object = new Document($key);
  243.             // deletes the object from the database
  244.             $object->delete();
  245.             // close the transaction
  246.             TTransaction::close();
  247.             // reload the listing
  248.             $this->onReload();
  249.             // shows the success message
  250.             new TMessage('info'TAdiantiCoreTranslator::translate('Record deleted'));
  251.         } catch (Exception $e) { // in case of exception
  252.             // shows the exception error message
  253.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  254.             // undo all pending operations
  255.             TTransaction::rollback();
  256.         }
  257.     }
  258.     /**
  259.      * method show()
  260.      * Shows the page
  261.      */
  262.     function show() {
  263.         // check if the datagrid is already loaded
  264.         if (!$this->loaded) {
  265.             $this->onReload();
  266.         }
  267.         parent::show();
  268.     }
  269. }
  270. ?>
</your>
FS

Não deu erro nenhum, mas também não apresentou nada.
MS

Provavelmente você não tem dados na tabela "Document", inclua alguns.
FS

Com este exemplo funcional que você me passou, tem como me enviar um print, só pra mim ver como é apresentado na tela?

Se quiser pode me enviar por e-mail fabiano-s@hotmail.com , ou fsdb32@gmail.com.

E muito obrigado de novo pela atenção.
FS

Meu amigo Mailson, consegui.

Cara, muito obrigado por ajudar a aumentar meu conhecimento, pode contar comigo também quando precisar.

Abraço.
MS

Certo. Vamos nos ajudandando então.
Abraço.
FS

Boa noite Mailson,
Surgiu um problema e uma dúvida. Quando eu troco de página pela paginação ele começa a somar novamente. Por exemplo, na página 1 do datagrid eu tenho 10 registros, sendo que, são 5 ativos e 5 inativos, até aí tranquilo, ele somou certinho. Só que tenho o 11º registro que está na página 2 e ele está com situação ativo também, então teria que mostrar no contador 6 usuários ativos e 5 inativos e não só os que estão na determinada página. Não sei se expliquei bem, você sabe como fazer?

Obrigado cara.
PD

Fabiano,

Você terá de rodar um count(), não tem outro jeito, não é suficiente somar somente os registros que estão na tela.

Teste fazer um método em sua classe de modelo. Ex:

Aluno::getAtivos();
Aluno::getInativos();

E rodar o TRepository com o critério ali dentro, veja:

public static function getAtivos()
{
$repository = new TRepository('Aluno');
$criteria = new TCriteria;
$criteria->add(new TFilter('situacao', '=' ,'Ativo'));
return $repository->count($criteria);
}

Não testei, mas depois basta chamar o método em algum lugar do onReload para apresentar em tela.

Att,
Pablo
EA

Obrigado Mailson da Silva,
Eu estava com o mesmo problema para pegar a quantidade de registros do datagrid e enviar para o formulário.
Fiz conforme você explicou e funcionou perfeitamente.
  1. <?php
  2.             //Envio conforme as classes TSeek
  3.             $object = new stdClass();
  4.             $object->NomeDoMeuTEntry $countAtivo//Você deve colocar o nome do componente TEntry()
  5.             TForm::sendData($this->form->getName(), $object);
  6. ?>
EA

Obrigado Mailson da Silva,
Eu estava com o mesmo problema para pegar a quantidade de registros do datagrid e enviar para o formulário.
Fiz conforme você explicou e funcionou perfeitamente.
  1. <?php
  2.             //Envio conforme as classes TSeek
  3.             $object = new stdClass();
  4.             $object->NomeDoMeuTEntry $count//Você deve colocar o nome do componente TEntry()
  5.             TForm::sendData($this->form->getName(), $object);
  6. ?>