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:
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:
- <?php
- /**
- * ContaAReceberList Listing
- * @author Mauro Miranda
- */
- class ContaAReceberList extends TPage
- {
- private $form; // form
- private $formConta; // form
- private $datagrid; // listing
- private $pageNavigation;
- private $formgrid;
- private $loaded;
- private $deleteButton;
- private $table_list;
- private $combo;
-
- /**
- * Class constructor
- * Creates the page, the form and the listing
- */
- public function __construct($name = null)
- {
- parent::__construct();
-
- // creates the form
- $html = new THtmlRenderer('app/resources/contas-a-receber.html');
- // loads the galleria javascript library
- TPage::include_js('app/lib/js_custom/custom_conta_a_receber.js');
- TTransaction::open('database'); // abre uma conexão
- $connection = TTransaction::get();
-
- $hoje = date('Y-m-d');
- $sth1 = $connection->prepare("SELECT count(id), sum(valor) FROM financeiro.conta_a_receber WHERE vencimento < ?");
- $sth2 = $connection->prepare("SELECT count(id), sum(valor) FROM financeiro.conta_a_receber WHERE vencimento = ?");
- $sth3 = $connection->prepare("SELECT count(id), sum(valor) FROM financeiro.conta_a_receber WHERE vencimento > ?");
-
- $sth1->execute(array($hoje));
- $sth2->execute(array($hoje));
- $sth3->execute(array($hoje));
-
- $result_vencido = $sth1->fetchAll();
- $result_vencendo = $sth2->fetchAll();
- $result_a_vencer = $sth3->fetchAll();
-
- $documentos = array();
- $documentos['n_vencido'] = ($result_vencido[0]['count']) ? str_pad($result_vencido[0]['count'], 4, "0", STR_PAD_LEFT) : 0;
- $documentos['t_vencido'] = ($result_vencido[0]['sum']) ? $result_vencido[0]['sum'] : 'R$ 0,00';
- $documentos['n_vencendo']= ($result_vencendo[0]['count'])? str_pad($result_vencendo[0]['count'], 4, "0", STR_PAD_LEFT) : 0;
- $documentos['t_vencendo']= ($result_vencendo[0]['sum']) ? $result_vencendo[0]['sum'] : 'R$ 0,00';
- $documentos['n_a_vencer']= ($result_a_vencer[0]['count'])? str_pad($result_a_vencer[0]['count'], 4, "0", STR_PAD_LEFT) : 0;
- $documentos['t_a_vencer']= ($result_a_vencer[0]['sum']) ? $result_a_vencer[0]['sum'] : 'R$ 0,00';
-
-
- $sql_a_vencer = "";
- $sql_vencendo = "";
- // replace the main section variables
- $html->enableSection('main', $documentos);
-
- $panel = new TPanelGroup('Contas a Receber');
- $panel->add($html);
- $panel->style="min-width:1000px;";
-
- // cria um formulário de buscas
- $this->form = new TForm('form_search_cp');
-
- // cria campos de busca
- $name = new TCombo('name');
- $name->setSize(185);
- $name_items = ['excluir'=>'Excluir', 'lancamento'=>'Lançamento em conta'];
- $name->addItems($name_items);
- $combo = new TCombo('acao');
- $check1 = new TCheckButton('check1');
- $check1->setValue('acao');
- $check1->setProperty('id', 'checkAll');
-
- $name_action = new TAction(array($this, 'onChangeAction'));
- $name->setChangeAction($name_action);
-
- $table = new TTable;
- $table->style = 'width:100%';
- $row = $table->addRow();
- $cell = $row->addCell(''); // cria celula com espaçamento
- $cell->width = PHP_SAPI == 'cli' ? 40 : 30; // define a largura da celula
-
-
- //cria os botões de ação
- $button1 = new TButton('new');
- $button1->setAction(new TAction(array('ContaAReceberForm', 'onEdit')), '<i class="glyphicon glyphicon-plus"></i>');
- $button1->class = 'btn btn-success';
- //$button1->setImage('ico_new.png');
-
- $button2 = new TButton('search');
- $button2->setAction(new TAction(array($this, 'onSearch')), '<i class="glyphicon glyphicon-search"></i>');
- $button2->class = 'btn btn-success';
-
-
- $pesquisa = new TEntry('busca');
- $pesquisa->setValue(TSession::getValue('pesquisa'));
-
- $campo = $row->addCell($name);
- $campo->width = 100;
- $botao = $row->addCell($button1);
- $botao->width = 50;
- $busca = $row->addCell($pesquisa);
- $busca->align = 'left';
- $btn_busca = $row->addCell($button2);
- $btn_busca->align = 'left';
- $btn_busca->width = 30;
-
- // listagem de dados
- try{
- // cria uma estilo para cabecalho
- $estilo_cabecalho = new TStyle('cabecalho');
- $estilo_cabecalho->font_family = 'arial,verdana,sans-serif';
- $estilo_cabecalho->color = '#000';
- $backgoundcolor = "background-color";
- $estilo_cabecalho->$backgoundcolor = '#00CED1';
- $font_weight = 'font-weight';
- $estilo_cabecalho->$font_weight = 'bold';
- $estilo_cabecalho->show();
-
- // cria um estilo para o total
- $estilo_total = new TStyle('total');
- $estilo_total->font_family = 'arial,verdana,sans-serif';
- $estilo_total->color = '#000';
- $font_weight = 'font-weight';
- $font_size = "font-size";
- $estilo_total->$font_weight = 'bold;';
- $estilo_total->$font_size = "18px;";
- $estilo_total->show();
-
- // estilo para quebra
- $estilo_quebra = new TStyle('quebra');
- $estilo_quebra->font_family = 'arial,verdana,sans-serif';
- $estilo_quebra->color = '#000';
- $estilo_quebra->show();
-
- // estilo para os dados
- $estilo_dados = new TStyle('dados');
- $estilo_dados->color = '#2D2D2D';
- $estilo_dados->show();
-
- $conn = TConnection::open('database'); // abre uma conexão
-
- // define consulta
-
- if(TSession::getValue('pesquisa'))
- {
- $busca_ = TSession::getValue('pesquisa');
- $sql = "SELECT * FROM financeiro.conta_a_receber where nome_cliente like '%$busca_%' order by nome_cliente";
- }else{
- $sql = "SELECT * FROM financeiro.conta_a_receber WHERE id_conta IS NULL order by nome_cliente";
- }
-
-
- $result = $conn->query($sql); // executa a instrução sql
-
- $tabela = new TTable;
-
- // define algumas prioridades da tabela
- $tabela->width = '100%';
- $tabela->border = 5;
- $tabela->style = "border-collapse:collapse";
-
- // inicializa as variaveis de controle e totalização
- $colore = false;
- $total_custo = 0;
- $total_venda = 0;
- $total_estoq = 0;
- $total_custo_quebra = 0;
- $total_venda_quebra = 0;
- $total_estoq_quebra = 0;
- $controle_quebra = NULL;
-
- $x = 0;
-
-
- // percorre os resultados
- foreach($result as $row)
- {
-
- // verifica se a primeira linha ou a coluna de quebra trocou de valor
- if(!isset($controle_quebra) OR $controle_quebra !== $row['nome_cliente'])
- {
- // se a variavel de controle possui valor, deve totalizar
- if(isset($controle_quebra))
- {
- // instancia uma linha para o total de quebra
- $total = $tabela->addRow();
- $celula = $total->addCell('Total ');
- $total->class = 'total';
- $celula->colspan = 6;
- //$celula->addCell($controle_quebra);
-
- // adiaciona células com totais
- $custo_exibir = number_format($total_custo_quebra, 2, ',', '.');
- $celula1 = $total->addCell('R$ '. $custo_exibir);
- $celula1->align = "right";
-
- // reiniciliza variáveis totalizadores por quebra
- $total_custo_quebra = 0;
- }
-
-
-
- // instancia uma linha para o cabeçalho
- if(!isset($cabecalho_principal_quebra) OR $cabecalho_principal_quebra !== 'cabecalho')
- {
- $cabecalho = $tabela->addRow();
- $cabecalho->addCell($check1);
- $cabecalho->addCell('Cliente');
- $cabecalho->addCell('Documento');
- $cabecalho->addCell('Nº Documento');
- $cabecalho->addCell('Vencimento');
- $cabecalho->addCell('Valor');
- $cabecalho->addCell('Ação');
- $cabecalho->class = 'cabecalho';
- $cabecalho->align = 'center';
- $cabecalho_principal_quebra = 'cabecalho';
- }
-
-
- // instancia uma linha para exibir o valor atual da quebra
- $quebra = $tabela->addRow();
- $c = $quebra->addCell('>');
- $c->align = 'center';
- $cell = $quebra->addCell($row['nome_cliente']);
- $cell->colspan = 6;
- $cell->style = 'font-size:18px;';
- $quebra->class = 'quebra';
-
- // atualiza varável de controle
- $controle_quebra = $row['nome_cliente'];
- }
-
- $valor1 = str_replace("R$", "", $row['valor']);
- $valor2 = str_replace(".","", $valor1);
- $valor3 = str_replace(",",".", $valor2);
-
- $total_custo_quebra += $valor3;
-
- // verifica qual cor utilizará para os fundos dos dados
- $bgcolor = $colore ? '#d0d0d0' : '#ffffff';
-
- // adiciona uma linha para os dados (detalhamento)
- $linha = $tabela->addRow();
- $linha->bgcolor = $bgcolor;
- $linha->class = 'dados';
-
- // adiciona as células á linha de dados
- //echo $row['id'];
-
- $check2 = new TCheckButton('check[]');
- $check2->setIndexValue($row['id']);
- $cellx = $linha->addCell($check2);
- $cellx->width = 30;
- $cell1 = $linha->addCell($row['nome_cliente']);
- $cell2 = $linha->addCell($row['documento']);
- $cell3 = $linha->addCell($row['numero_documeto']);
- $vencimento = TDate::date2br($row['vencimento']);
- $cell4 = $linha->addCell($vencimento);
- $cell5 = $linha->addCell($row['valor']);
- $combo->setSize(180);
- $combo_items = ['editar'=>'Editar', 'excluir'=>'Excluir', 'lancamento'=>'Lançamento em conta'];
- $combo->addItems($combo_items);
- $cell6 = $linha->addCell($combo);
- $cell6->width = 100;
-
-
- // define o alinhamento das celulas
- $cellx->align = 'center';
- $cell1->align = 'center';
- $cell2->align = 'center';
- $cell3->align = 'center';
- $cell4->align = 'center';
- $cell5->align = 'center';
- $cell6->align = 'center';
-
- //inverte variável de controle para cor de fundo
- $colore = !$colore;
- }
-
-
- $combo_action = new TAction(array($this, 'onChangeAction2'));
- $combo->setChangeAction($combo_action);
-
- $tabela_final = new TTable();
- $tabela_final->style = "width:100%;";
- $celula_principal = $tabela_final->addRow();
- $celula_principal->addCell($table);
-
- if($check2){
- $celula_principal = $tabela_final->addRow();
- $celula_principal->addCell($tabela);
- }else{
- $celula_principal = $tabela_final->addRow();
- $celula_principal->addCell('Nenhum Resultado Encontrado!');
- }
-
-
- $this->form->add($tabela_final);
- $check2 = ($check2) ? $check2 : new TCheckButton('check2');
- // define quais os campos do formulário
- $this->form->setFields(array($name, $check1, $check2, $combo, $pesquisa, $button1, $button2));
-
- // adiciona linha para os totais da ultima quebra
- $total = $tabela->addRow();
- $celula= $total->addCell('Total ');
- $total->class = 'total';
- $celula->colspan = 6;
- $custo_exibir = number_format($total_custo_quebra,2,',','.');
- $celula1 = $total->addCell('R$ ' . $custo_exibir);
- $celula1->align = 'right';
-
-
- }catch(Exception $e){
- echo ($e->getMessage());
- }
-
-
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 100%';
- $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- //$container->add(TPanelGroup::pack('Gerenciamento de contas a receber', $this->form));
- $container->add($panel);
- $container->add($this->form);
- //$container->add($tabela_final);
- parent::add($container);
- }
-
-
- /**
- * Register the filter in the session
- */
- public function onSearch()
- {
- // get the search form data
- $data = $this->form->getData();
-
- // clear session filters
- TSession::setValue('ContaAReceberList_filter_busca', NULL);
- if (isset($data->busca) AND ($data->busca)) {
- TSession::setValue('pesquisa', $data->busca); // stores the filter in the session
- }else{
- TSession::setValue('pesquisa', null); // stores the filter in the session
- }
-
- // fill the form with data again
- $this->form->setData($data);
- $program = "ContaAReceberList";
- //var_dump($program);die;
- TApplication::loadPage($program);
- // keep the search data in the session
- TSession::setValue('ContaAReceber_filter_busca', $data);
-
-
- }
-
-
- public static function onChangeAction($param = null)
- {
- $data = $param;
- $acao = $param['name'];
-
- if($acao == 'excluir' && count($param['check'])>0)
- {
- TSession::setValue('check', $param['check']);
- // define the delete action
- $key['key'] = $param['1'];
- $action = new TAction(array('ContaAReceberList', 'Delete'));
- $action->setParameters($key); // pass the key parameter ahead
-
- // shows a dialog to the user
- new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
-
-
- }else if($acao == 'lancamento' && count($param['check'])>0)
- {
-
- // Armazena as IDs na sessão
- TSession::setValue('check', $param['check']);
-
- // creates the form
- $formConta = new TQuickForm('form_lancamento');
- $formConta->class = 'tform'; // change CSS class
- $formConta = new BootstrapFormWrapper($formConta);
- $formConta->style = 'display: table;width:100%'; // change style
-
- // define the form title
- $formConta->setFormTitle('Lancamento');
-
- // create the form fields
- $tipoConta = new TDBCombo('tipo_conta', 'database', 'TipoConta', 'id', 'nome', 'id');
- $banco = new TCombo('banco');
- $agencia = new TCombo('agencia');
- $conta = new TCombo('conta');
-
- // Busca Banco
- $tipo_change = new TAction(array('ContaAReceberList', 'buscaBanco'));
- $tipoConta->setChangeAction($tipo_change);
-
- // Busca Agência
- $banco_change = new TAction(array('ContaAReceberList', 'buscaAgencia'));
- $banco->setChangeAction($banco_change);
-
- // Busca Conta
- $agencia_change = new TAction(array('ContaAReceberList', 'buscaConta'));
- $agencia->setChangeAction($agencia_change);
-
-
- // add the fields
- $formConta->addQuickField('Tipo de conta:', $tipoConta, 200 , new TRequiredValidator);
- $formConta->addQuickField('Banco:', $banco, 350 , new TRequiredValidator);
- $formConta->addQuickField('Agência:', $agencia, 100 , new TRequiredValidator);
- $formConta->addQuickField('Conta:', $conta, 100 , new TRequiredValidator);
- // create the form actions
- $formConta->addQuickAction(_t('Save'), new TAction(array('ContaAReceberList', 'onSave')), 'fa:floppy-o');
-
- // abre uma janela
- $window = TWindow::create('Conta', 0.6, 0.5);
- $window->add($formConta);
- $window->show();
-
- }else if(!empty($acao) && count($param['check'])==0)
- {
- new TMessage('error', 'Por favor, você deve escolher um registro!');
- }
-
- }
-
- public static function onChangeAction2($param)
- {
- new TMessage('info', 'Mudou 2');
- }
-
- public function onSave($param)
- {
- TTransaction::open('database');
- $areceber = $param['conta'];
- $checks = TSession::getValue('check');
- foreach($checks as $check)
- {
- $data = new ContaAReceber;
- $data->id_conta = $areceber;
- $data->id = $check;
- $data->store();
- //var_dump($areceber);
- }
- TTransaction::close();
- TApplication::loadPage('ContaAReceberList');
-
- }
-
- public static function buscaBanco($param)
- {
- $conn = TConnection::open('database');
- if($param['tipo_conta'])
- {
- $tipo = $param['tipo_conta'];
- $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'";
- $result = $conn->query($sql);
-
- $options = array();
- $option1 = array();
- $option2 = array();
- $options[''] = '';
- foreach($result as $resultado)
- {
- $options[$resultado['id']] = $resultado['codigo'] . ' - ' . $resultado['nome'];
- }
-
- TCombo::reload('form_lancamento', 'banco', $options);
- TCombo::reload('form_lancamento', 'agencia', $option1);
- TCombo::reload('form_lancamento', 'conta', $option2);
- }
- }
-
- public static function buscaAgencia($param)
- {
- $conn = TConnection::open('database');
- if($param['banco'])
- {
- $banco = $param['banco'];
- $tipo = $param['tipo_conta'];
- $sql = "SELECT c.agencia from financeiro.conta c where c.id_banco = '$banco' AND c.id_tipo_conta = '$tipo'";
- $result = $conn->query($sql);
-
- $options = array();
- $option2 = array();
- $options[''] = '';
- foreach($result as $resultado)
- {
- $options[$resultado['agencia']] = $resultado['agencia'];
- }
-
- TCombo::reload('form_lancamento', 'agencia', $options);
- TCombo::reload('form_lancamento', 'conta', $option2);
- }
- }
-
- public static function buscaConta($param)
- {
- $conn = TConnection::open('database');
- if($param['agencia'])
- {
- $banco = $param['banco'];
- $agencia = $param['agencia'];
- $tipo = $param['tipo_conta'];
- $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'";
- $result = $conn->query($sql);
-
- $options = array();
- $options[''] = '';
- foreach($result as $resultado)
- {
- $options[$resultado['id']] = $resultado['conta'];
- }
-
- TCombo::reload('form_lancamento', 'conta', $options);
- }
- }
-
- public function Delete($param)
- {
-
- try
- {
- $contas = TSession::getValue('check');
- foreach($contas as $conta)
- {
- $key=$contas; // get the parameter $key
- TTransaction::open('database'); // open a transaction with database
- $object = new ContaAReceber($conta, FALSE); // instantiates the Active Record
- $object->delete(); // deletes the object from the database
- TTransaction::close(); // close the transaction
- }
- TSession::delValue('check');
- TApplication::loadPage('ContaAReceberList');
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
-
- /**
- * Load the datagrid with data
- */
- public function onReload($param = NULL)
- {
-
- $this->loaded = true;
- }
-
- /**
- * 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();
- }
- }
- ?>
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
Nataniel, você sabe que código? Porque tentei com datagrid e onreload, não criava esses subtotais dos agrupamentos. Por isso usei o ttable.
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.
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?
Quero agradecer a Ajuda, funcionou bunitinho.
Caro Mauro Miranda, estou iniciando os estudos seria possível compartilhar o código que fez com que o TTable tivesse uma paginação?