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

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