Conheça as melhorias da versão 8.0, 8.1, 8.2!
Clique aqui para saber mais
Paginação com TTable Boa noite pessoal, estou fazendo um mini ERP e o mesmo tem muitas nuances e como estou começando como o Adianti, então estou com muitas duvidas. Fiz uma grid para listar resultados com o TTable (imagem em anexo), porque não consegui customizar com o TDatagrid, porém preciso por paginação na mesma. Alguém sabe como posso fazer isso? segue o meu código: ...
MM
Paginação com TTable  
Boa noite pessoal, estou fazendo um mini ERP e o mesmo tem muitas nuances e como estou começando como o Adianti, então estou com muitas duvidas.

Fiz uma grid para listar resultados com o TTable (imagem em anexo), porque não consegui customizar com o TDatagrid, porém preciso por paginação na mesma.

Alguém sabe como posso fazer isso?

segue o meu código:

 
  1. <?php
  2. /**
  3. * ContaAReceberList Listing
  4. * @author Mauro Miranda
  5. */
  6. class ContaAReceberList extends TPage
  7. {
  8. private $form; // form
  9. private $formConta; // form
  10. private $datagrid; // listing
  11. private $pageNavigation;
  12. private $formgrid;
  13. private $loaded;
  14. private $deleteButton;
  15. private $table_list;
  16. private $combo;
  17. /**
  18. * Class constructor
  19. * Creates the page, the form and the listing
  20. */
  21. public function __construct($name = null)
  22. {
  23. parent::__construct();
  24. // creates the form
  25. $html = new THtmlRenderer('app/resources/contas-a-receber.html');
  26. // loads the galleria javascript library
  27. TPage::include_js('app/lib/js_custom/custom_conta_a_receber.js');
  28. TTransaction::open('database'); // abre uma conexão
  29. $connection = TTransaction::get();
  30. $hoje = date('Y-m-d');
  31. $sth1 = $connection->prepare("SELECT count(id), sum(valor) FROM financeiro.conta_a_receber WHERE vencimento < ?");
  32. $sth2 = $connection->prepare("SELECT count(id), sum(valor) FROM financeiro.conta_a_receber WHERE vencimento = ?");
  33. $sth3 = $connection->prepare("SELECT count(id), sum(valor) FROM financeiro.conta_a_receber WHERE vencimento > ?");
  34. $sth1->execute(array($hoje));
  35. $sth2->execute(array($hoje));
  36. $sth3->execute(array($hoje));
  37. $result_vencido = $sth1->fetchAll();
  38. $result_vencendo = $sth2->fetchAll();
  39. $result_a_vencer = $sth3->fetchAll();
  40. $documentos = array();
  41. $documentos['n_vencido'] = ($result_vencido[0]['count']) ? str_pad($result_vencido[0]['count'], 4, "0", STR_PAD_LEFT) : 0;
  42. $documentos['t_vencido'] = ($result_vencido[0]['sum']) ? $result_vencido[0]['sum'] : 'R$ 0,00';
  43. $documentos['n_vencendo']= ($result_vencendo[0]['count'])? str_pad($result_vencendo[0]['count'], 4, "0", STR_PAD_LEFT) : 0;
  44. $documentos['t_vencendo']= ($result_vencendo[0]['sum']) ? $result_vencendo[0]['sum'] : 'R$ 0,00';
  45. $documentos['n_a_vencer']= ($result_a_vencer[0]['count'])? str_pad($result_a_vencer[0]['count'], 4, "0", STR_PAD_LEFT) : 0;
  46. $documentos['t_a_vencer']= ($result_a_vencer[0]['sum']) ? $result_a_vencer[0]['sum'] : 'R$ 0,00';
  47. $sql_a_vencer = "";
  48. $sql_vencendo = "";
  49. // replace the main section variables
  50. $html->enableSection('main', $documentos);
  51. $panel = new TPanelGroup('Contas a Receber');
  52. $panel->add($html);
  53. $panel->style="min-width:1000px;";
  54. // cria um formulário de buscas
  55. $this->form = new TForm('form_search_cp');
  56. // cria campos de busca
  57. $name = new TCombo('name');
  58. $name->setSize(185);
  59. $name_items = ['excluir'=>'Excluir', 'lancamento'=>'Lançamento em conta'];
  60. $name->addItems($name_items);
  61. $combo = new TCombo('acao');
  62. $check1 = new TCheckButton('check1');
  63. $check1->setValue('acao');
  64. $check1->setProperty('id', 'checkAll');
  65. $name_action = new TAction(array($this, 'onChangeAction'));
  66. $name->setChangeAction($name_action);
  67. $table = new TTable;
  68. $table->style = 'width:100%';
  69. $row = $table->addRow();
  70. $cell = $row->addCell(''); // cria celula com espaçamento
  71. $cell->width = PHP_SAPI == 'cli' ? 40 : 30; // define a largura da celula
  72. //cria os botões de ação
  73. $button1 = new TButton('new');
  74. $button1->setAction(new TAction(array('ContaAReceberForm', 'onEdit')), '<i class="glyphicon glyphicon-plus"></i>');
  75. $button1->class = 'btn btn-success';
  76. //$button1->setImage('ico_new.png');
  77. $button2 = new TButton('search');
  78. $button2->setAction(new TAction(array($this, 'onSearch')), '<i class="glyphicon glyphicon-search"></i>');
  79. $button2->class = 'btn btn-success';
  80. $pesquisa = new TEntry('busca');
  81. $pesquisa->setValue(TSession::getValue('pesquisa'));
  82. $campo = $row->addCell($name);
  83. $campo->width = 100;
  84. $botao = $row->addCell($button1);
  85. $botao->width = 50;
  86. $busca = $row->addCell($pesquisa);
  87. $busca->align = 'left';
  88. $btn_busca = $row->addCell($button2);
  89. $btn_busca->align = 'left';
  90. $btn_busca->width = 30;
  91. // listagem de dados
  92. try{
  93. // cria uma estilo para cabecalho
  94. $estilo_cabecalho = new TStyle('cabecalho');
  95. $estilo_cabecalho->font_family = 'arial,verdana,sans-serif';
  96. $estilo_cabecalho->color = '#000';
  97. $backgoundcolor = "background-color";
  98. $estilo_cabecalho->$backgoundcolor = '#00CED1';
  99. $font_weight = 'font-weight';
  100. $estilo_cabecalho->$font_weight = 'bold';
  101. $estilo_cabecalho->show();
  102. // cria um estilo para o total
  103. $estilo_total = new TStyle('total');
  104. $estilo_total->font_family = 'arial,verdana,sans-serif';
  105. $estilo_total->color = '#000';
  106. $font_weight = 'font-weight';
  107. $font_size = "font-size";
  108. $estilo_total->$font_weight = 'bold;';
  109. $estilo_total->$font_size = "18px;";
  110. $estilo_total->show();
  111. // estilo para quebra
  112. $estilo_quebra = new TStyle('quebra');
  113. $estilo_quebra->font_family = 'arial,verdana,sans-serif';
  114. $estilo_quebra->color = '#000';
  115. $estilo_quebra->show();
  116. // estilo para os dados
  117. $estilo_dados = new TStyle('dados');
  118. $estilo_dados->color = '#2D2D2D';
  119. $estilo_dados->show();
  120. $conn = TConnection::open('database'); // abre uma conexão
  121. // define consulta
  122. if(TSession::getValue('pesquisa'))
  123. {
  124. $busca_ = TSession::getValue('pesquisa');
  125. $sql = "SELECT * FROM financeiro.conta_a_receber where nome_cliente like '%$busca_%' order by nome_cliente";
  126. }else{
  127. $sql = "SELECT * FROM financeiro.conta_a_receber WHERE id_conta IS NULL order by nome_cliente";
  128. }
  129. $result = $conn->query($sql); // executa a instrução sql
  130. $tabela = new TTable;
  131. // define algumas prioridades da tabela
  132. $tabela->width = '100%';
  133. $tabela->border = 5;
  134. $tabela->style = "border-collapse:collapse";
  135. // inicializa as variaveis de controle e totalização
  136. $colore = false;
  137. $total_custo = 0;
  138. $total_venda = 0;
  139. $total_estoq = 0;
  140. $total_custo_quebra = 0;
  141. $total_venda_quebra = 0;
  142. $total_estoq_quebra = 0;
  143. $controle_quebra = NULL;
  144. $x = 0;
  145. // percorre os resultados
  146. foreach($result as $row)
  147. {
  148. // verifica se a primeira linha ou a coluna de quebra trocou de valor
  149. if(!isset($controle_quebra) OR $controle_quebra !== $row['nome_cliente'])
  150. {
  151. // se a variavel de controle possui valor, deve totalizar
  152. if(isset($controle_quebra))
  153. {
  154. // instancia uma linha para o total de quebra
  155. $total = $tabela->addRow();
  156. $celula = $total->addCell('Total ');
  157. $total->class = 'total';
  158. $celula->colspan = 6;
  159. //$celula->addCell($controle_quebra);
  160. // adiaciona células com totais
  161. $custo_exibir = number_format($total_custo_quebra, 2, ',', '.');
  162. $celula1 = $total->addCell('R$ '. $custo_exibir);
  163. $celula1->align = "right";
  164. // reiniciliza variáveis totalizadores por quebra
  165. $total_custo_quebra = 0;
  166. }
  167. // instancia uma linha para o cabeçalho
  168. if(!isset($cabecalho_principal_quebra) OR $cabecalho_principal_quebra !== 'cabecalho')
  169. {
  170. $cabecalho = $tabela->addRow();
  171. $cabecalho->addCell($check1);
  172. $cabecalho->addCell('Cliente');
  173. $cabecalho->addCell('Documento');
  174. $cabecalho->addCell('Nº Documento');
  175. $cabecalho->addCell('Vencimento');
  176. $cabecalho->addCell('Valor');
  177. $cabecalho->addCell('Ação');
  178. $cabecalho->class = 'cabecalho';
  179. $cabecalho->align = 'center';
  180. $cabecalho_principal_quebra = 'cabecalho';
  181. }
  182. // instancia uma linha para exibir o valor atual da quebra
  183. $quebra = $tabela->addRow();
  184. $c = $quebra->addCell('>');
  185. $c->align = 'center';
  186. $cell = $quebra->addCell($row['nome_cliente']);
  187. $cell->colspan = 6;
  188. $cell->style = 'font-size:18px;';
  189. $quebra->class = 'quebra';
  190. // atualiza varável de controle
  191. $controle_quebra = $row['nome_cliente'];
  192. }
  193. $valor1 = str_replace("R$", "", $row['valor']);
  194. $valor2 = str_replace(".","", $valor1);
  195. $valor3 = str_replace(",",".", $valor2);
  196. $total_custo_quebra += $valor3;
  197. // verifica qual cor utilizará para os fundos dos dados
  198. $bgcolor = $colore ? '#d0d0d0' : '#ffffff';
  199. // adiciona uma linha para os dados (detalhamento)
  200. $linha = $tabela->addRow();
  201. $linha->bgcolor = $bgcolor;
  202. $linha->class = 'dados';
  203. // adiciona as células á linha de dados
  204. //echo $row['id'];
  205. $check2 = new TCheckButton('check[]');
  206. $check2->setIndexValue($row['id']);
  207. $cellx = $linha->addCell($check2);
  208. $cellx->width = 30;
  209. $cell1 = $linha->addCell($row['nome_cliente']);
  210. $cell2 = $linha->addCell($row['documento']);
  211. $cell3 = $linha->addCell($row['numero_documeto']);
  212. $vencimento = TDate::date2br($row['vencimento']);
  213. $cell4 = $linha->addCell($vencimento);
  214. $cell5 = $linha->addCell($row['valor']);
  215. $combo->setSize(180);
  216. $combo_items = ['editar'=>'Editar', 'excluir'=>'Excluir', 'lancamento'=>'Lançamento em conta'];
  217. $combo->addItems($combo_items);
  218. $cell6 = $linha->addCell($combo);
  219. $cell6->width = 100;
  220. // define o alinhamento das celulas
  221. $cellx->align = 'center';
  222. $cell1->align = 'center';
  223. $cell2->align = 'center';
  224. $cell3->align = 'center';
  225. $cell4->align = 'center';
  226. $cell5->align = 'center';
  227. $cell6->align = 'center';
  228. //inverte variável de controle para cor de fundo
  229. $colore = !$colore;
  230. }
  231. $combo_action = new TAction(array($this, 'onChangeAction2'));
  232. $combo->setChangeAction($combo_action);
  233. $tabela_final = new TTable();
  234. $tabela_final->style = "width:100%;";
  235. $celula_principal = $tabela_final->addRow();
  236. $celula_principal->addCell($table);
  237. if($check2){
  238. $celula_principal = $tabela_final->addRow();
  239. $celula_principal->addCell($tabela);
  240. }else{
  241. $celula_principal = $tabela_final->addRow();
  242. $celula_principal->addCell('Nenhum Resultado Encontrado!');
  243. }
  244. $this->form->add($tabela_final);
  245. $check2 = ($check2) ? $check2 : new TCheckButton('check2');
  246. // define quais os campos do formulário
  247. $this->form->setFields(array($name, $check1, $check2, $combo, $pesquisa, $button1, $button2));
  248. // adiciona linha para os totais da ultima quebra
  249. $total = $tabela->addRow();
  250. $celula= $total->addCell('Total ');
  251. $total->class = 'total';
  252. $celula->colspan = 6;
  253. $custo_exibir = number_format($total_custo_quebra,2,',','.');
  254. $celula1 = $total->addCell('R$ ' . $custo_exibir);
  255. $celula1->align = 'right';
  256. }catch(Exception $e){
  257. echo ($e->getMessage());
  258. }
  259. // vertical box container
  260. $container = new TVBox;
  261. $container->style = 'width: 100%';
  262. $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  263. //$container->add(TPanelGroup::pack('Gerenciamento de contas a receber', $this->form));
  264. $container->add($panel);
  265. $container->add($this->form);
  266. //$container->add($tabela_final);
  267. parent::add($container);
  268. }
  269. /**
  270. * Register the filter in the session
  271. */
  272. public function onSearch()
  273. {
  274. // get the search form data
  275. $data = $this->form->getData();
  276. // clear session filters
  277. TSession::setValue('ContaAReceberList_filter_busca', NULL);
  278. if (isset($data->busca) AND ($data->busca)) {
  279. TSession::setValue('pesquisa', $data->busca); // stores the filter in the session
  280. }else{
  281. TSession::setValue('pesquisa', null); // stores the filter in the session
  282. }
  283. // fill the form with data again
  284. $this->form->setData($data);
  285. $program = "ContaAReceberList";
  286. //var_dump($program);die;
  287. TApplication::loadPage($program);
  288. // keep the search data in the session
  289. TSession::setValue('ContaAReceber_filter_busca', $data);
  290. }
  291. public static function onChangeAction($param = null)
  292. {
  293. $data = $param;
  294. $acao = $param['name'];
  295. if($acao == 'excluir' && count($param['check'])>0)
  296. {
  297. TSession::setValue('check', $param['check']);
  298. // define the delete action
  299. $key['key'] = $param['1'];
  300. $action = new TAction(array('ContaAReceberList', 'Delete'));
  301. $action->setParameters($key); // pass the key parameter ahead
  302. // shows a dialog to the user
  303. new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  304. }else if($acao == 'lancamento' && count($param['check'])>0)
  305. {
  306. // Armazena as IDs na sessão
  307. TSession::setValue('check', $param['check']);
  308. // creates the form
  309. $formConta = new TQuickForm('form_lancamento');
  310. $formConta->class = 'tform'; // change CSS class
  311. $formConta = new BootstrapFormWrapper($formConta);
  312. $formConta->style = 'display: table;width:100%'; // change style
  313. // define the form title
  314. $formConta->setFormTitle('Lancamento');
  315. // create the form fields
  316. $tipoConta = new TDBCombo('tipo_conta', 'database', 'TipoConta', 'id', 'nome', 'id');
  317. $banco = new TCombo('banco');
  318. $agencia = new TCombo('agencia');
  319. $conta = new TCombo('conta');
  320. // Busca Banco
  321. $tipo_change = new TAction(array('ContaAReceberList', 'buscaBanco'));
  322. $tipoConta->setChangeAction($tipo_change);
  323. // Busca Agência
  324. $banco_change = new TAction(array('ContaAReceberList', 'buscaAgencia'));
  325. $banco->setChangeAction($banco_change);
  326. // Busca Conta
  327. $agencia_change = new TAction(array('ContaAReceberList', 'buscaConta'));
  328. $agencia->setChangeAction($agencia_change);
  329. // add the fields
  330. $formConta->addQuickField('Tipo de conta:', $tipoConta, 200 , new TRequiredValidator);
  331. $formConta->addQuickField('Banco:', $banco, 350 , new TRequiredValidator);
  332. $formConta->addQuickField('Agência:', $agencia, 100 , new TRequiredValidator);
  333. $formConta->addQuickField('Conta:', $conta, 100 , new TRequiredValidator);
  334. // create the form actions
  335. $formConta->addQuickAction(_t('Save'), new TAction(array('ContaAReceberList', 'onSave')), 'fa:floppy-o');
  336. // abre uma janela
  337. $window = TWindow::create('Conta', 0.6, 0.5);
  338. $window->add($formConta);
  339. $window->show();
  340. }else if(!empty($acao) && count($param['check'])==0)
  341. {
  342. new TMessage('error', 'Por favor, você deve escolher um registro!');
  343. }
  344. }
  345. public static function onChangeAction2($param)
  346. {
  347. new TMessage('info', 'Mudou 2');
  348. }
  349. public function onSave($param)
  350. {
  351. TTransaction::open('database');
  352. $areceber = $param['conta'];
  353. $checks = TSession::getValue('check');
  354. foreach($checks as $check)
  355. {
  356. $data = new ContaAReceber;
  357. $data->id_conta = $areceber;
  358. $data->id = $check;
  359. $data->store();
  360. //var_dump($areceber);
  361. }
  362. TTransaction::close();
  363. TApplication::loadPage('ContaAReceberList');
  364. }
  365. public static function buscaBanco($param)
  366. {
  367. $conn = TConnection::open('database');
  368. if($param['tipo_conta'])
  369. {
  370. $tipo = $param['tipo_conta'];
  371. $sql = "SELECT b.id, b.codigo, b.nome from financeiro.conta c inner join financeiro.banco b on c.id_banco = b.id where c.id_tipo_conta = '$tipo'";
  372. $result = $conn->query($sql);
  373. $options = array();
  374. $option1 = array();
  375. $option2 = array();
  376. $options[''] = '';
  377. foreach($result as $resultado)
  378. {
  379. $options[$resultado['id']] = $resultado['codigo'] . ' - ' . $resultado['nome'];
  380. }
  381. TCombo::reload('form_lancamento', 'banco', $options);
  382. TCombo::reload('form_lancamento', 'agencia', $option1);
  383. TCombo::reload('form_lancamento', 'conta', $option2);
  384. }
  385. }
  386. public static function buscaAgencia($param)
  387. {
  388. $conn = TConnection::open('database');
  389. if($param['banco'])
  390. {
  391. $banco = $param['banco'];
  392. $tipo = $param['tipo_conta'];
  393. $sql = "SELECT c.agencia from financeiro.conta c where c.id_banco = '$banco' AND c.id_tipo_conta = '$tipo'";
  394. $result = $conn->query($sql);
  395. $options = array();
  396. $option2 = array();
  397. $options[''] = '';
  398. foreach($result as $resultado)
  399. {
  400. $options[$resultado['agencia']] = $resultado['agencia'];
  401. }
  402. TCombo::reload('form_lancamento', 'agencia', $options);
  403. TCombo::reload('form_lancamento', 'conta', $option2);
  404. }
  405. }
  406. public static function buscaConta($param)
  407. {
  408. $conn = TConnection::open('database');
  409. if($param['agencia'])
  410. {
  411. $banco = $param['banco'];
  412. $agencia = $param['agencia'];
  413. $tipo = $param['tipo_conta'];
  414. $sql = "SELECT c.id, c.conta from financeiro.conta c where c.id_banco = '$banco' AND c.agencia = '$agencia' AND c.id_tipo_conta = '$tipo'";
  415. $result = $conn->query($sql);
  416. $options = array();
  417. $options[''] = '';
  418. foreach($result as $resultado)
  419. {
  420. $options[$resultado['id']] = $resultado['conta'];
  421. }
  422. TCombo::reload('form_lancamento', 'conta', $options);
  423. }
  424. }
  425. public function Delete($param)
  426. {
  427. try
  428. {
  429. $contas = TSession::getValue('check');
  430. foreach($contas as $conta)
  431. {
  432. $key=$contas; // get the parameter $key
  433. TTransaction::open('database'); // open a transaction with database
  434. $object = new ContaAReceber($conta, FALSE); // instantiates the Active Record
  435. $object->delete(); // deletes the object from the database
  436. TTransaction::close(); // close the transaction
  437. }
  438. TSession::delValue('check');
  439. TApplication::loadPage('ContaAReceberList');
  440. }
  441. catch (Exception $e) // in case of exception
  442. {
  443. new TMessage('error', $e->getMessage()); // shows the exception error message
  444. TTransaction::rollback(); // undo all pending operations
  445. }
  446. }
  447. /**
  448. * Load the datagrid with data
  449. */
  450. public function onReload($param = NULL)
  451. {
  452. $this->loaded = true;
  453. }
  454. /**
  455. * method show()
  456. * Shows the page
  457. */
  458. public function show()
  459. {
  460. // check if the datagrid is already loaded
  461. if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch')))) )
  462. {
  463. if (func_num_args() > 0)
  464. {
  465. $this->onReload( func_get_arg(0) );
  466. }
  467. else
  468. {
  469. $this->onReload();
  470. }
  471. }
  472. parent::show();
  473. }
  474. }
  475. ?>

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


NR

Mauro, pode se basear em outro código que tenha datagrid.

Basicamente você precisa criar um metódo para recarregar a tabela(onReload) e utilizar o componente TPageNavigation
MM

Nataniel, você sabe que código? Porque tentei com datagrid e onreload, não criava esses subtotais dos agrupamentos. Por isso usei o ttable.
NR

Me referi ao código responsável pela criação da paginação. Mantenha o ttable mas adicionando os recursos de paginação presentes na datagrid.
MM

Ok, vou tentar aqui. Só uma pergunta o tpagenavigation tem um parâmetro getwith que pega o this->datagrid ->getwith() o ttable possui esse parâmetro?
MM

Quero agradecer a Ajuda, funcionou bunitinho.
CO

Caro Mauro Miranda, estou iniciando os estudos seria possível compartilhar o código que fez com que o TTable tivesse uma paginação?