Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Ajuda Datagrid com Checkbutton 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...
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:

  1. <?php
  2. /**
  3.  * ViagemComprovanteEntregaForm Registration
  4.  * @author  <your name here>
  5.  */
  6. require_once '.\app\util\TDateSollaris.class.php';
  7. class ViagemComprovanteEntregaForm extends TPage
  8. {
  9.     protected $form// form
  10.     private $notebook;
  11.     private $datagrid;
  12.     private $formfields;
  13.     
  14.     /**
  15.      * Class constructor
  16.      * Creates the page and the registration form
  17.      */
  18.     function __construct()
  19.     {
  20.         parent::__construct();
  21.         
  22.         $this->notebook = new TNotebook(700,300);
  23.         
  24.         $this->form = new TForm('form_ViagemComprovanteEntrega');
  25.         
  26.         $page1 = new TTable;
  27.         $page2 = new TTable;
  28.         $page3 = new TTable;
  29.         
  30.         
  31.         $this->form->add($this->notebook);
  32.         
  33.         $this->notebook->appendPage('Cadastro de Comprovante de Entrega'$page1);
  34.         $this->notebook->appendPage('Notas Fiscais Pendentes',$page3);
  35.         
  36.         863 = new TEntry('id');
  37.         863->setEditable(FALSE);
  38.         $nomerecebedor = new TEntry('nomerecebedor');
  39.         $numerodocumento = new TEntry('numerodocumento');
  40.         $datacomprovante = new TDateSollaris('datacomprovante');
  41.         $horacomprovante = new TEntry('horacomprovante');
  42.         $horacomprovante->setMask('99:99');
  43.         $cliente_id = new TSeekButton('cliente_id'); 
  44.         
  45.         $NomeCliente = new TEntry('NomeCliente'); 
  46.         $NomeCliente->setEditable(FALSE);       
  47.         $this->datagrid = new TQuickGrid;
  48.         $this->datagrid->disableDefaultClick();
  49.         $this->datagrid->makeScrollable();
  50.         $this->datagrid->setHeight(200);
  51.         
  52.         //lookup cliente
  53.         $objcliente = new ClienteSeekForm;
  54.         $actioncliente = new TAction(array($objcliente'onReload'));
  55.         $cliente_id->setAction($actioncliente);
  56.         TSession::setValue('form_cliente_seek','form_ViagemComprovanteEntrega'); 
  57.         
  58.         // Grid Notas Fiscais
  59.         
  60.         $this->datagrid->addQuickColumn('Check',   'check',   'right'40);
  61.         $this->datagrid->addQuickColumn('Viagem',    'viagem_id',    'right'70);
  62.         $this->datagrid->addQuickColumn('Número',    'numero',    'right'70);
  63.         $this->datagrid->addQuickColumn('Emissão',    'dataemissao',    'left'80);
  64.         $this->datagrid->addQuickColumn('Remetente''NomeRemetente''left'200);
  65.         $this->datagrid->addQuickColumn('Destinatário',   'NomeDestinatario',    'left'200);
  66.         //$this->datagrid->addQuickColumn('Código Nota Fiscal',    'notafiscalcliente_id',    'right', 0);        
  67.         
  68.         // creates the datagrid model
  69.         $this->datagrid->createModel();        
  70.         
  71.         
  72.         //criação dos botões
  73.         
  74.         $salvar = new TButton('Salvar');
  75.         $salvar->setAction(new TAction(array($this,'onSave')),'Salvar');
  76.         $salvar->setImage('ico_save.png');        
  77.         
  78.         $pesquisar = new TButton('Pesquisar');
  79.         $pesquisar->setAction(new TAction(array($this,'pesquisarNotasFiscais')),'Pesquisar');
  80.         $pesquisar->setImage('ico_find.png');         
  81.         
  82.         //validação dos campos
  83.         $nomerecebedor->addValidation('Recebedor', new TRequiredValidator);
  84.         $numerodocumento->addValidation('Número do Documento', new TRequiredValidator); 
  85.         $datacomprovante->addValidation('Data do Comprovante', new TRequiredValidator); 
  86.         $horacomprovante->addValidation('Hora do Comprovante', new TRequiredValidator); 
  87.                
  88.         
  89.         //aba cadastro de comprovante de entrega
  90.         $row=$page1->addRow();
  91.         $row->addCell(new TLabel('Código:'));
  92.         $row->addCell(863);
  93.         
  94.         $row=$page1->addRow();
  95.         $row->addCell(new TLabel('Recebedor:'));
  96.         $row->addCell($nomerecebedor);
  97.         
  98.         $row=$page1->addRow();
  99.         $row->addCell(new TLabel('Número do Documento:'));
  100.         $row->addCell($numerodocumento);
  101.                 
  102.         $row=$page1->addRow();
  103.         $row->addCell(new TLabel('Data:'));
  104.         $row->addCell($datacomprovante);
  105.         
  106.         $row=$page1->addRow();
  107.         $row->addCell(new TLabel('Hora:'));
  108.         $row->addCell($horacomprovante);
  109.         
  110.         $row=$page1->addRow();
  111.         $row->addCell($salvar);        
  112.         
  113.         $row=$page2->addRow();
  114.         $row->addCell(new TLabel('Cliente:'));
  115.         $row->addCell($cliente_id);
  116.         $row->addCell($NomeCliente);  
  117.         $row->addCell($pesquisar);          
  118.         
  119.        // $row=$page2->addRow();
  120.        // $row->addCell($pesquisar);        
  121.         
  122.         $row=$page3->addRow();
  123.         $row->addCell($page2);        
  124.         
  125.         $row=$page3->addRow();
  126.         $row->addCell($this->datagrid);
  127.         
  128.         
  129.         $this->formfields[] = 863;
  130.         $this->formfields[] = $nomerecebedor;
  131.         $this->formfields[] = $numerodocumento;
  132.         $this->formfields[] = $datacomprovante;
  133.         $this->formfields[] = $horacomprovante;
  134.         $this->formfields[] = $cliente_id;
  135.         $this->formfields[] = $NomeCliente;
  136.         $this->formfields[] = $pesquisar;
  137.         $this->formfields[] = $salvar;
  138.         $this->form->setFields($this->formfields);
  139.         
  140.         // wrap the page content using vertical box
  141.         $vbox = new TVBox;
  142.         $vbox->add($this->form);
  143.         parent::add($vbox);                                     
  144.     }
  145.     /**
  146.      * method onSave()
  147.      * Executed whenever the user clicks at the save button
  148.      */
  149.     function onSave()
  150.     {
  151.         try
  152.         {
  153.             // open a transaction with database 'sollus'
  154.             TTransaction::open('sollus');
  155.             
  156.             // get the form data into an active record ViagemComprovanteEntrega
  157.             $object $this->form->getData();
  158.             $this->form->setData($object);  
  159.             
  160.             
  161.             $mensagem '';
  162.             
  163.            // var_dump($this->form->getFields());
  164.             
  165.             foreach($this->form->getFields() as $name => $field){
  166.                 if ($field instanceof TCheckButton){
  167.                     $mensagem .= "$name: " $field->getValue();
  168.                 }
  169.             
  170.             }
  171.             
  172.              new TMessage('info'$mensagem);
  173.             
  174.             
  175.             //$this->form->validate(); // form validation
  176.             //$object->store(); // stores the object
  177.             //$this->form->setData($object); // keep form data
  178.            
  179.             
  180.             TTransaction::close(); // close the transaction
  181.             
  182.             // shows the success message
  183.             //new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  184.         }
  185.         catch (Exception $e// in case of exception
  186.         {
  187.             // shows the exception error message
  188.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  189.             
  190.             $this->form->setData$this->form->getData() ); // keep form data
  191.             
  192.             // undo all pending operations
  193.             TTransaction::rollback();
  194.         }
  195.     }
  196.     
  197.     /**
  198.      * method onEdit()
  199.      * Executed whenever the user clicks at the edit button da datagrid
  200.      */
  201.     function onEdit($param)
  202.     {
  203.         try
  204.         {
  205.             if (isset($param['key']))
  206.             {
  207.                 // get the parameter $key
  208.                 $key=$param['key'];
  209.                 
  210.                 // open a transaction with database 'sollus'
  211.                 TTransaction::open('sollus');
  212.                 
  213.                 // instantiates object ViagemComprovanteEntrega
  214.                 $object = new ViagemComprovanteEntrega($key);
  215.                 
  216.                 // fill the form with the active record data
  217.                 $this->form->setData($object);
  218.                 
  219.                 // close the transaction
  220.                 TTransaction::close();
  221.             }
  222.             else
  223.             {
  224.                 $this->form->clear();
  225.             }
  226.         }
  227.         catch (Exception $e// in case of exception
  228.         {
  229.             // shows the exception error message
  230.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  231.             
  232.             // undo all pending operations
  233.             TTransaction::rollback();
  234.         }
  235.     }   
  236.     function pesquisarNotasFiscais(){
  237.         try
  238.         {
  239.             // open a transaction with database 'sollus'
  240.             TTransaction::open('sollus');
  241.             
  242.             // get the form data into an active record Viagem
  243.             $objform $this->form->getData('ViagemComprovanteEntrega');
  244.             
  245.             $criteria = new TCriteria;
  246.             $criteria->add(new TFilter('cliente_id','=',$objform->cliente_id));
  247.             $criteria->add(new TFilter('datafinalizacao','IS',NULL));
  248.             $repositoy = new TRepository('Viagem');
  249.             $viagens $repositoy->load($criteria);            
  250.             
  251.             $i 1;
  252.                         
  253.            foreach($viagens as $viagem){
  254.                 $viagemnotasfiscais $viagem->get_ViagemNotaFiscalCliente();
  255.                 
  256.                 
  257.                 if ($viagemnotasfiscais != NULL){
  258.                     
  259.                     
  260.                     foreach($viagemnotasfiscais as $viagemnotafiscal){
  261.                     
  262.                         $item = new StdClass;
  263.                         $item->check = new TCheckButton('check_' $i );
  264.                        
  265.                         $item->viagem_id     $viagemnotafiscal->viagem_id;
  266.                         $item->notafiscalcliente_id  $viagemnotafiscal->notafiscalcliente_id;
  267.                         $item->check->setIndexValue($item->viagem_id '_' $item->notafiscalcliente_id );
  268.                                     
  269.                         $item->numero 100;
  270.                         $item->dataemissao  '2014-08-24';
  271.                         $item->NomeRemetente     'Rementente';
  272.                         $item->NomeDestinatario   'Destinatário';
  273.                         
  274.                         
  275.                         $this->datagrid->addItem($item);
  276.                         $this->formfields[] = $item->check;
  277.                         $this->form->setFields($this->formfields);                    
  278.                           
  279.                         $i++;
  280.                           
  281. /*
  282.                         $item = new StdClass;
  283.                         $item->check    = new TCheckButton('check_' . $viagemnotafiscal->notafiscalcliente_id );
  284.                         $item->check->setIndexValue('on');
  285.                        
  286.                         $item->viagem_id     = $viagemnotafiscal->viagem_id;
  287.                         $item->notafiscalcliente_id  = $viagemnotafiscal->notafiscalcliente_id;
  288.                         $item->numero = $viagemnotafiscal->NotaFiscalCliente->numero;
  289.                         $item->dataemissao  = $viagemnotafiscal->NotaFiscalCliente->dataemissao;
  290.                         $item->NomeRemetente     = $viagemnotafiscal->NotaFiscalCliente->NomeRemetente;
  291.                         $item->NomeDestinatario   = $viagemnotafiscal->NotaFiscalCliente->NomeDestinatario;
  292.                         $this->datagrid->addItem($item);
  293.                         $this->formfields[] = $item->check;
  294.                         $this->form->setFields($this->formfields);
  295.                         
  296.                         TSession::setValue('datagrid_comprovante',$this->datagrid);
  297. */                    
  298.                     }          
  299.                 }
  300.             }            
  301.             
  302.             $this->notebook->setCurrentPage(1);
  303.             
  304.             $this->form->setData($this->form->getData());            
  305.             
  306.                        
  307.             TTransaction::close(); // close the transaction
  308.         }
  309.         catch (Exception $e// in case of exception
  310.         {
  311.             // shows the exception error message
  312.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  313.             
  314.             $this->form->setData$this->form->getData() ); // keep form data
  315.             
  316.             // undo all pending operations
  317.             TTransaction::rollback();
  318.         }
  319.     } 
  320.     
  321.     function onReload(){
  322.         $this->datagrid->clear();
  323.         
  324.         for ($i 1;$i 11;$i++){
  325.             $item = new StdClass;
  326.             $item->check = new TCheckButton('check_' $i);
  327.            
  328.             $item->viagem_id     1;
  329.             $item->notafiscalcliente_id  2;
  330.             $item->check->setIndexValue($item->viagem_id '_' $item->notafiscalcliente_id );
  331.                         
  332.             $item->numero 100;
  333.             $item->dataemissao  '2014-08-24';
  334.             $item->NomeRemetente     'Rementente';
  335.             $item->NomeDestinatario   'Destinatário';
  336.             
  337.             
  338.             $this->datagrid->addItem($item);
  339.             $this->formfields[] = $item->check;
  340.             $this->form->setFields($this->formfields);
  341.         }        
  342.         
  343.     }
  344.     
  345.     function show(){
  346.         //$this->onReload(); // Se desabilitar esta linha funcionará.
  347.         //$this->pesquisarNotasFiscais();
  348.         parent::show();
  349.     }
  350. }
  351. ?>

Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


Dominando o Adianti 7 Quero me inscrever agora!

Comentários (1)


PD

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

  1. <?php
  2.     function show()
  3.     {
  4.         $this->onReload();
  5.         parent::show();
  6.     }
  7. ?>


Atenciosamente,
Pablo