CG
Ajuda Datagrid com Checkbutton
Fechado
Prezados boa noite,
Estou implementando uma funcionalidade que utiliza um datagrid com checkbutton.
Percebi que o Datagrid com checkbutton permite capturar os dados selecionados somente quando o sistema os "carrega" pelo método onReload() sendo chamado pelo metodo show().
Porém, no meu caso, o formulário não será carregado inicialmente.
O usuário selecionará um cliente e acionará o botão pesquisar. O sistema carrega o grid com as notas fiscais deste cliente para o usuário selecionar.
Até este ponto consigo consegui fazer. A minha dificuldade é capturar no botão salvar as linhas do grid que o usuário seleciona.
Segue o código fonte para análise:
Estou implementando uma funcionalidade que utiliza um datagrid com checkbutton.
Percebi que o Datagrid com checkbutton permite capturar os dados selecionados somente quando o sistema os "carrega" pelo método onReload() sendo chamado pelo metodo show().
Porém, no meu caso, o formulário não será carregado inicialmente.
O usuário selecionará um cliente e acionará o botão pesquisar. O sistema carrega o grid com as notas fiscais deste cliente para o usuário selecionar.
Até este ponto consigo consegui fazer. A minha dificuldade é capturar no botão salvar as linhas do grid que o usuário seleciona.
Segue o código fonte para análise:
- <?php
- /**
- * ViagemComprovanteEntregaForm Registration
- * @author <your name here>
- */
- require_once '.\app\util\TDateSollaris.class.php';
- class ViagemComprovanteEntregaForm extends TPage
- {
- protected $form; // form
- private $notebook;
- private $datagrid;
- private $formfields;
- /**
- * Class constructor
- * Creates the page and the registration form
- */
- function __construct()
- {
- parent::__construct();
- $this->notebook = new TNotebook(700,300);
- $this->form = new TForm('form_ViagemComprovanteEntrega');
- $page1 = new TTable;
- $page2 = new TTable;
- $page3 = new TTable;
- $this->form->add($this->notebook);
- $this->notebook->appendPage('Cadastro de Comprovante de Entrega', $page1);
- $this->notebook->appendPage('Notas Fiscais Pendentes',$page3);
- 863 = new TEntry('id');
- 863->setEditable(FALSE);
- $nomerecebedor = new TEntry('nomerecebedor');
- $numerodocumento = new TEntry('numerodocumento');
- $datacomprovante = new TDateSollaris('datacomprovante');
- $horacomprovante = new TEntry('horacomprovante');
- $horacomprovante->setMask('99:99');
- $cliente_id = new TSeekButton('cliente_id');
- $NomeCliente = new TEntry('NomeCliente');
- $NomeCliente->setEditable(FALSE);
- $this->datagrid = new TQuickGrid;
- $this->datagrid->disableDefaultClick();
- $this->datagrid->makeScrollable();
- $this->datagrid->setHeight(200);
- //lookup cliente
- $objcliente = new ClienteSeekForm;
- $actioncliente = new TAction(array($objcliente, 'onReload'));
- $cliente_id->setAction($actioncliente);
- TSession::setValue('form_cliente_seek','form_ViagemComprovanteEntrega');
- // Grid Notas Fiscais
- $this->datagrid->addQuickColumn('Check', 'check', 'right', 40);
- $this->datagrid->addQuickColumn('Viagem', 'viagem_id', 'right', 70);
- $this->datagrid->addQuickColumn('Número', 'numero', 'right', 70);
- $this->datagrid->addQuickColumn('Emissão', 'dataemissao', 'left', 80);
- $this->datagrid->addQuickColumn('Remetente', 'NomeRemetente', 'left', 200);
- $this->datagrid->addQuickColumn('Destinatário', 'NomeDestinatario', 'left', 200);
- //$this->datagrid->addQuickColumn('Código Nota Fiscal', 'notafiscalcliente_id', 'right', 0);
- // creates the datagrid model
- $this->datagrid->createModel();
- //criação dos botões
- $salvar = new TButton('Salvar');
- $salvar->setAction(new TAction(array($this,'onSave')),'Salvar');
- $salvar->setImage('ico_save.png');
- $pesquisar = new TButton('Pesquisar');
- $pesquisar->setAction(new TAction(array($this,'pesquisarNotasFiscais')),'Pesquisar');
- $pesquisar->setImage('ico_find.png');
- //validação dos campos
- $nomerecebedor->addValidation('Recebedor', new TRequiredValidator);
- $numerodocumento->addValidation('Número do Documento', new TRequiredValidator);
- $datacomprovante->addValidation('Data do Comprovante', new TRequiredValidator);
- $horacomprovante->addValidation('Hora do Comprovante', new TRequiredValidator);
- //aba cadastro de comprovante de entrega
- $row=$page1->addRow();
- $row->addCell(new TLabel('Código:'));
- $row->addCell(863);
- $row=$page1->addRow();
- $row->addCell(new TLabel('Recebedor:'));
- $row->addCell($nomerecebedor);
- $row=$page1->addRow();
- $row->addCell(new TLabel('Número do Documento:'));
- $row->addCell($numerodocumento);
- $row=$page1->addRow();
- $row->addCell(new TLabel('Data:'));
- $row->addCell($datacomprovante);
- $row=$page1->addRow();
- $row->addCell(new TLabel('Hora:'));
- $row->addCell($horacomprovante);
- $row=$page1->addRow();
- $row->addCell($salvar);
- $row=$page2->addRow();
- $row->addCell(new TLabel('Cliente:'));
- $row->addCell($cliente_id);
- $row->addCell($NomeCliente);
- $row->addCell($pesquisar);
- // $row=$page2->addRow();
- // $row->addCell($pesquisar);
- $row=$page3->addRow();
- $row->addCell($page2);
- $row=$page3->addRow();
- $row->addCell($this->datagrid);
- $this->formfields[] = 863;
- $this->formfields[] = $nomerecebedor;
- $this->formfields[] = $numerodocumento;
- $this->formfields[] = $datacomprovante;
- $this->formfields[] = $horacomprovante;
- $this->formfields[] = $cliente_id;
- $this->formfields[] = $NomeCliente;
- $this->formfields[] = $pesquisar;
- $this->formfields[] = $salvar;
- $this->form->setFields($this->formfields);
- // wrap the page content using vertical box
- $vbox = new TVBox;
- $vbox->add($this->form);
- parent::add($vbox);
- }
- /**
- * method onSave()
- * Executed whenever the user clicks at the save button
- */
- function onSave()
- {
- try
- {
- // open a transaction with database 'sollus'
- TTransaction::open('sollus');
- // get the form data into an active record ViagemComprovanteEntrega
- $object = $this->form->getData();
- $this->form->setData($object);
- $mensagem = '';
- // var_dump($this->form->getFields());
- foreach($this->form->getFields() as $name => $field){
- if ($field instanceof TCheckButton){
- $mensagem .= "$name: " . $field->getValue();
- }
- }
- new TMessage('info', $mensagem);
- //$this->form->validate(); // form validation
- //$object->store(); // stores the object
- //$this->form->setData($object); // keep form data
- TTransaction::close(); // close the transaction
- // shows the success message
- //new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- $this->form->setData( $this->form->getData() ); // keep form data
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- /**
- * method onEdit()
- * Executed whenever the user clicks at the edit button da datagrid
- */
- function onEdit($param)
- {
- try
- {
- if (isset($param['key']))
- {
- // get the parameter $key
- $key=$param['key'];
- // open a transaction with database 'sollus'
- TTransaction::open('sollus');
- // instantiates object ViagemComprovanteEntrega
- $object = new ViagemComprovanteEntrega($key);
- // fill the form with the active record data
- $this->form->setData($object);
- // close the transaction
- TTransaction::close();
- }
- else
- {
- $this->form->clear();
- }
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- function pesquisarNotasFiscais(){
- try
- {
- // open a transaction with database 'sollus'
- TTransaction::open('sollus');
- // get the form data into an active record Viagem
- $objform = $this->form->getData('ViagemComprovanteEntrega');
- $criteria = new TCriteria;
- $criteria->add(new TFilter('cliente_id','=',$objform->cliente_id));
- $criteria->add(new TFilter('datafinalizacao','IS',NULL));
- $repositoy = new TRepository('Viagem');
- $viagens = $repositoy->load($criteria);
- $i = 1;
- foreach($viagens as $viagem){
- $viagemnotasfiscais = $viagem->get_ViagemNotaFiscalCliente();
- if ($viagemnotasfiscais != NULL){
- foreach($viagemnotasfiscais as $viagemnotafiscal){
- $item = new StdClass;
- $item->check = new TCheckButton('check_' . $i );
- $item->viagem_id = $viagemnotafiscal->viagem_id;
- $item->notafiscalcliente_id = $viagemnotafiscal->notafiscalcliente_id;
- $item->check->setIndexValue($item->viagem_id . '_' . $item->notafiscalcliente_id );
- $item->numero = 100;
- $item->dataemissao = '2014-08-24';
- $item->NomeRemetente = 'Rementente';
- $item->NomeDestinatario = 'Destinatário';
- $this->datagrid->addItem($item);
- $this->formfields[] = $item->check;
- $this->form->setFields($this->formfields);
- $i++;
- /*
- $item = new StdClass;
- $item->check = new TCheckButton('check_' . $viagemnotafiscal->notafiscalcliente_id );
- $item->check->setIndexValue('on');
- $item->viagem_id = $viagemnotafiscal->viagem_id;
- $item->notafiscalcliente_id = $viagemnotafiscal->notafiscalcliente_id;
- $item->numero = $viagemnotafiscal->NotaFiscalCliente->numero;
- $item->dataemissao = $viagemnotafiscal->NotaFiscalCliente->dataemissao;
- $item->NomeRemetente = $viagemnotafiscal->NotaFiscalCliente->NomeRemetente;
- $item->NomeDestinatario = $viagemnotafiscal->NotaFiscalCliente->NomeDestinatario;
- $this->datagrid->addItem($item);
- $this->formfields[] = $item->check;
- $this->form->setFields($this->formfields);
- TSession::setValue('datagrid_comprovante',$this->datagrid);
- */
- }
- }
- }
- $this->notebook->setCurrentPage(1);
- $this->form->setData($this->form->getData());
- TTransaction::close(); // close the transaction
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- $this->form->setData( $this->form->getData() ); // keep form data
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- function onReload(){
- $this->datagrid->clear();
- for ($i = 1;$i < 11;$i++){
- $item = new StdClass;
- $item->check = new TCheckButton('check_' . $i);
- $item->viagem_id = 1;
- $item->notafiscalcliente_id = 2;
- $item->check->setIndexValue($item->viagem_id . '_' . $item->notafiscalcliente_id );
- $item->numero = 100;
- $item->dataemissao = '2014-08-24';
- $item->NomeRemetente = 'Rementente';
- $item->NomeDestinatario = 'Destinatário';
- $this->datagrid->addItem($item);
- $this->formfields[] = $item->check;
- $this->form->setFields($this->formfields);
- }
- }
- function show(){
- //$this->onReload(); // Se desabilitar esta linha funcionará.
- //$this->pesquisarNotasFiscais();
- parent::show();
- }
- }
- ?>
Oi Carlos,
Vou replicar aqui o que lhe respondi via e-mail para ficar registrado:
Você precisa garantir que o formulário execute o setFields() antes de dar o getData().
Veja nesse exemplo:
www.adianti.com.br/framework_files/tutor/index.php?class=DatagridChe
O que garante que o onReload() seja executado antes do onSave() é que o onReload() sempre é chamado no show() antes da página ser processada... Vi que você comentou aquela linha, mas é importante ter o setFields(), que no seu caso é declarado no onReload().
Atenciosamente,
Pablo