Método form->getData() no onSave retornando valores vazios Fala Galera! Preciso de uma ajudinha novamente.. Tenho um formulário do tipo TForm; Estou instanciando ele e os campos dentro do construct, mas não adiciono os campos diretamente ao form por questão de layout, ou seja, adiciono eles dentro de um TNotebook, que por sua vez, está dentro de um TPanelGroup. No final do construct, estou adicionando os campos manualmente do form com o $this->for...
RR
Método form->getData() no onSave retornando valores vazios  
Fala Galera! Preciso de uma ajudinha novamente..

Tenho um formulário do tipo TForm; Estou instanciando ele e os campos dentro do construct, mas não adiciono os campos diretamente ao form por questão de layout, ou seja, adiciono eles dentro de um TNotebook, que por sua vez, está dentro de um TPanelGroup.
No final do construct, estou adicionando os campos manualmente do form com o $this->form->setFields(array($x,$y,$z, etc));
Porém no evento onSave, não é retornado nada, ou seja, recebo todos os campos pelo método $data = $this->form->getData() , porem todos campos vem vazios..

Alguém sabe informar o que está faltando ou o que estou fazendo de errado?

Obrigado..

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


MG

Renato, poste o código para podermos ajudar!
RR

Olá Marcelo.. segue:

 
  1. <?php
  2. class ProdutoForm extends TPage
  3. {
  4. protected $form; // form
  5. use Adianti\Base\AdiantiStandardFormTrait; // Standard form methods
  6. /**
  7. * Class constructor
  8. * Creates the page and the registration form
  9. */
  10. function __construct()
  11. {
  12. parent::__construct();
  13. $this->setDatabase('dbmysql'); // defines the database
  14. $this->setActiveRecord('ProdutoModel'); // defines the active record
  15. $painel = new TPanelGroup('Cadastro de Produtos');
  16. $this->form = new TForm('form_produto');
  17. $this->form->class = 'tform';
  18. //Instanciamento de Campos
  19. $Id = new THidden('Id');
  20. $Codigo = new TEntry('Codigo');
  21. $Descricao = new TEntry('Descricao');
  22. $EAN = new TEntry('EAN');
  23. $unidade_id = new TDBCombo('unidade_id','dbmysql','UnidadeModel','uni_id','uni_abrev');
  24. $Valor = new TEntry('Valor');
  25. $Obs = new TText('Obs');
  26. $Descricao->setMaxLength(60);
  27. /*>>>>>>> MÁSCARAS <<<<<<<<*/
  28. $Valor->setNumericMask(3,',','.');
  29. /*>>>>>>> HINTS <<<<<<<<*/
  30. $Descricao->setTip('Insira a descrição do produto..');
  31. $notebookPrincipal = new BootstrapNotebookWrapper( new TNotebook('100%',400) );
  32. $tableGerais = new TTable;
  33. $tableGerais->style = 'width: 100%';
  34. $notebookPrincipal->appendPage('Dados Gerais', $tableGerais);
  35. //EXIBIÇÃO DE CAMPOS
  36. $div = new TVBox;
  37. $div->class = 'form-group col-lg-1';
  38. $div->add(new TLabel('Código'));
  39. $Codigo->class = 'tfield form-control';
  40. $div->add($Codigo);
  41. $Codigo->setSize('100%');
  42. $Codigo->setEditable(FALSE);
  43. $tableGerais->add($div);
  44. $div = new TVBox;
  45. $div->class = 'form-group col-lg-5';
  46. $div->add(new TLabel('Descrição'));
  47. $Descricao->class = 'tfield form-control';
  48. $div->add($Descricao);
  49. $Descricao->setSize('100%');
  50. $tableGerais->add($div);
  51. $div = new TVBox;
  52. $div->class = 'form-group col-lg-2';
  53. $div->add(new TLabel('Preço Venda'));
  54. $Valor->class = 'tfield form-control';
  55. $div->add($Valor);
  56. $Valor->setSize('100%');
  57. $tableGerais->add($div);
  58. $div = new TVBox;
  59. $div->class = 'form-group col-lg-3';
  60. $div->add(new TLabel('EAN(Cód. Barras)'));
  61. $EAN->class = 'tfield form-control';
  62. $div->add($EAN);
  63. $EAN->setSize('100%');
  64. $tableGerais->add($div);
  65. $div = new TVBox;
  66. $div->class = 'form-group col-lg-2';
  67. $div->add(new TLabel('Unidade'));
  68. $unidade_id->class = 'tfield form-control';
  69. $unidade_id->setSize('100%');
  70. $div->add($unidade_id);
  71. $tableGerais->add($div);
  72. $div = new TVBox;
  73. $div->class = 'form-group col-lg-12';
  74. $div->add(new TLabel('Observações'));
  75. $Obs->class = 'tfield'; // nao usar form-control em obs
  76. $Obs->setSize('100%',100);
  77. $Obs->style = 'min-width: 600px;';
  78. $div->add($Obs);
  79. $tableGerais->add($div);
  80. if (!empty($Id))
  81. {
  82. $Id->setEditable(FALSE);
  83. }
  84. $bt_save = new TButton('salvar');
  85. $bt_save->setAction( new TAction(array($this, 'onSave')), _t('Save'));
  86. $bt_save->setImage('fa:floppy-o');
  87. $buttons = new TTable;
  88. $row = $buttons->addRow();
  89. $row->addCell($bt_save);
  90. $painel->add($notebookPrincipal);
  91. $container = new TVBox;
  92. $container->style = 'width: 98%';
  93. $container->add($painel);
  94. $this->form->setFields(array($Id, $Codigo, $Descricao, $EAN,$Valor, $unidade_id , $Obs, $bt_save));
  95. $painel->addFooter($buttons);
  96. parent::add($container);
  97. }
  98. public function onSave()
  99. {
  100. try
  101. {
  102. $data = $this->form->getData(); // get form data as array
  103. var_dump($data);
  104. $this->form->validate(); // validate form data
  105. $object = new ProdutoModel; // create an empty object
  106. TTransaction::open('dbmysql'); // open a transaction
  107. $ValorProd = str_replace('.','', $data->Valor);
  108. $ValorProd = str_replace(',','.', $ValorProd);
  109. $data->Valor = $ValorProd;
  110. $object->fromArray( (array) $data); // load the object with data
  111. $object->store(); // save the object
  112. // get the generated Id
  113. $data->Id = $object->Id;
  114. $this->form->setData($data); // fill form data
  115. TTransaction::close(); // close the transaction
  116. }
  117. catch (Exception $e) // in case of exception
  118. {
  119. new TMessage('error', $e->getMessage()); // shows the exception error message
  120. $this->form->setData( $this->form->getData() ); // keep form data
  121. TTransaction::rollback(); // undo all pending operations
  122. }
  123. }
  124. ?>


Obrigado.
RR

Ao clicar no botão SALVAR, o resultado é o da imagem abaixo:

https://ibin.co/36ixXYUPhNdr.png

Dá para perceber que o getData mostrado com var_dump veio fazio..
MG

Renato,
Você não adicionou o form por isso nada é enviado.

Faço o seguinte:

 
  1. <?php
  2. // na linha abaixo faça a seguinte mudança
  3. $notebookPrincipal->appendPage('Dados Gerais', $tableGerais);
  4. $this->form->add($notebookPrincipal);
  5. ....
  6. // no final faça esta mudança
  7. $buttons = new TTable;
  8. $row = $buttons->addRow();
  9. $row->addCell($bt_save);
  10. // $painel->add($notebookPrincipal)
  11. $painel->add($this->form); // <== Mude para isso
  12. $container = new TVBox;
  13. $container->style = 'width: 98%';
  14. $container->add($painel);
  15. ?>
RR

Agora ficou 100% Marcelão!
Pensei que por estar chamando o método $this->form->setFields , não precisasse adicionar o Notebook ao $this->form.

Obrigado mais uma vez! Feliz 2017!
Renato
MG

Opa!
Que bom que funcionou!
Valeu Feliz 2017!
LF

Estou com um problema parecido, adicionei o notebook ao form, mas ainda assim $param retorna null. Se puder me ajudar... já quebrei a cabeça a tarde toda...
 
  1. <?php
  2. /**
  3. * ClientePessoaFisicaForm Master/Detail
  4. * @author <your name here>
  5. */
  6. /**
  7. * Description of ClientePessoaFisicaForm
  8. *
  9. * @author Leondas
  10. */
  11. class ClientePessoaFisicaForm extends TPage {
  12. protected $form; // form
  13. protected $table_telefones;
  14. protected $table_telefone_row;
  15. /**
  16. * Class constructor
  17. * Creates the page
  18. */
  19. function __construct($param) {
  20. parent::__construct($param);
  21. // creates the form
  22. $this->form = new TForm('form_Cliente');
  23. $this->form->class = 'tform'; // CSS class
  24. // creates the notebook
  25. $notebook = new BootstrapNotebookWrapper(new TNotebook('1100', '90%'));
  26. // creates the containers for each notebook page
  27. $table_cliente = new TTable;
  28. $table_telefone = new TTable;
  29. $table_email = new TTable;
  30. $table_endereco = new TTable;
  31. $table_padrao = new TTable;
  32. // adds two pages in the notebook
  33. $notebook->appendPage('Cliente', $table_cliente);
  34. $notebook->appendPage('Telefone', $table_telefone);
  35. $notebook->appendPage('E-mail', $table_email);
  36. $notebook->appendPage('Endereço', $table_endereco);
  37. $notebook->appendPage('Padrão', $table_padrao);
  38. // create the form fields
  39. $cliente_id = new TEntry('cliente_id');
  40. $cliente_status = new TCombo('cliente_status');
  41. $pessoa_fisica_id = new ">TDBSeekButton('pessoa_fisica_id', 'qualitta', 'form_Cliente', 'PessoaFisica', 'pessoa_fisica_nome', 'pessoa_fisica_id', 'pessoa_fisica_nome');
  42. $pessoa_fisica_nome = new TEntry('pessoa_fisica_nome');
  43. $pessoa_fisica_data_nascimento = new TDate('pessoa_fisica_data_nascimento');
  44. $pessoa_fisica_cpf = new TEntry('pessoa_fisica_cpf');
  45. $pessoa_fisica_rg = new TEntry('pessoa_fisica_rg');
  46. $pessoa_fisica_rg_orgao = new TEntry('pessoa_fisica_rg_orgao');
  47. $pessoa_fisica_rg_uf = new TDBCombo('pessoa_fisica_rg_uf', 'qualitta', 'Estado', 'estado_id', 'estado_uf');
  48. $cliente_observacao = new TText('cliente_observacao');
  49. $pessoa_id = new THidden('pessoa_id');
  50. // set exitAction
  51. $pessoa_fisica_id->setExitAction(new TAction(array($this, 'onExitPessoa')));
  52. // set mask
  53. $pessoa_fisica_cpf->setMask('999.999.999-99');
  54. // add items to status
  55. $cliente_status->addItems(array('1' => 'Ativo'));
  56. $cliente_status->setDefaultOption('Inativo');
  57. // sizes
  58. $cliente_id->setSize('50');
  59. $cliente_status->setSize('100');
  60. $pessoa_fisica_id->setSize('50');
  61. $pessoa_fisica_nome->setSize('300');
  62. $pessoa_fisica_data_nascimento->setSize('100');
  63. $pessoa_fisica_cpf->setSize('100');
  64. $pessoa_fisica_rg->setSize('100');
  65. $pessoa_fisica_rg_orgao->setSize('100');
  66. $pessoa_fisica_rg_uf->setSize('100');
  67. $cliente_observacao->setSize('100%');
  68. $pessoa_id->setSize('100%');
  69. if (!empty($cliente_id)) {
  70. $cliente_id->setEditable(FALSE);
  71. }
  72. // add form fields to be handled by form
  73. $this->form->addField($cliente_id);
  74. $this->form->addField($cliente_status);
  75. $this->form->addField($pessoa_fisica_id);
  76. $this->form->addField($pessoa_fisica_nome);
  77. $this->form->addField($pessoa_fisica_data_nascimento);
  78. $this->form->addField($pessoa_fisica_cpf);
  79. $this->form->addField($pessoa_fisica_rg);
  80. $this->form->addField($pessoa_fisica_rg_orgao);
  81. $this->form->addField($pessoa_fisica_rg_uf);
  82. $this->form->addField($cliente_observacao);
  83. $this->form->addField($pessoa_id);
  84. /**
  85. * **************************************************
  86. * PAGE CLIENTE
  87. * **************************************************
  88. */
  89. $table_cliente->setSize = '100%';
  90. // add a row for a label
  91. $row = $table_cliente->addRow();
  92. $row->addCell(new TLabel('<b>Dados do Cliente</b>'))->colspan = 12;
  93. // adds a row for a field
  94. $table_cliente->addRowSet(new TLabel('Cliente Id'), array($cliente_id, $pessoa_id));
  95. $table_cliente->addRowSet(new TLabel('Cliente Status'), $cliente_status);
  96. $table_cliente->addRowSet(new TLabel('Cliente'), array($pessoa_fisica_id, $pessoa_fisica_nome));
  97. $table_cliente->addRowSet(new TLabel('Nascimento'), array($pessoa_fisica_data_nascimento, new TLabel('CPF'), $pessoa_fisica_cpf));
  98. $table_cliente->addRowSet(new TLabel('RG'), array($pessoa_fisica_rg, new TLabel('Órgão'), $pessoa_fisica_rg_orgao, new TLabel('UF'), $pessoa_fisica_rg_uf));
  99. $table_cliente->addRowSet(new TLabel('Cliente Observacao'), $cliente_observacao);
  100. /**
  101. * **************************************************
  102. * PAGE TELEFONE
  103. * **************************************************
  104. */
  105. // add a row for a label
  106. $this->table_telefones = $table_telefone;
  107. $this->table_telefones->addSection('thead');
  108. $row = $this->table_telefones->addRow();
  109. // telefone header
  110. $row->addCell(new TLabel('ID'));
  111. $row->addCell(new TLabel('Status'));
  112. $row->addCell(new TLabel('Tipo'));
  113. $row->addCell(new TLabel('Número'));
  114. $row->addCell(new TLabel('Operadora'));
  115. /**
  116. * **************************************************
  117. * PAGE EMAIL
  118. * **************************************************
  119. */
  120. /**
  121. * **************************************************
  122. * PAGE ENDEREÇO
  123. * **************************************************
  124. */
  125. /**
  126. * **************************************************
  127. * PAGE PADRÃO
  128. * **************************************************
  129. */
  130. /**
  131. * **************************************************
  132. * BOTÕES DE AÇÃO E SCRIPT
  133. * **************************************************
  134. */
  135. // create an action button (save)
  136. $save_button = new TButton('save');
  137. $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));
  138. $save_button->setImage('ico_save.png');
  139. // create an new button (edit with no parameters)
  140. $new_button = new TButton('new');
  141. $new_button->setAction(new TAction(array($this, 'onClear')), _t('New'));
  142. $new_button->setImage('ico_new.png');
  143. // create an back button (edit with no parameters)
  144. $back_button = new TButton('back');
  145. $back_button->setAction(new TAction(array('ClientePessoaFisicaList', 'onReload')), _t('Back to the listing'));
  146. $back_button->setImage('fa:table blue');
  147. // define form fields
  148. $this->form->addField($save_button);
  149. $this->form->addField($new_button);
  150. $this->form->addField($back_button);
  151. $script = new TElement('script');
  152. $script->type = 'text/javascript';
  153. $javascript = "
  154. $(document).on('change','select[name=\"telefone_tipo[]\"]' , function(event){
  155. var telefone_tipo = this.id;
  156. var telefone_numero = telefone_tipo.replace('telefone_tipo_', 'telefone_numero_');
  157. $('#'+telefone_numero).val('');
  158. var option = $('#'+telefone_tipo+' option:selected').text();
  159. if(option == 'Fixo') {
  160. $('#'+telefone_numero).val('(069)');
  161. $('#'+telefone_numero).attr({onkeypress:'return tentry_mask(this,event,\"(069)9999-9999\")'});
  162. }
  163. if(option == 'Celular') {
  164. $('#'+telefone_numero).val('(69)9');
  165. $('#'+telefone_numero).attr({onkeypress:'return tentry_mask(this,event,\"(99)99999-9999\")'});
  166. }
  167. });";
  168. $script->add($javascript);
  169. $this->form->add($script);
  170. /**
  171. * **************************************************
  172. * ADD BUTTON TO PAGE
  173. * **************************************************
  174. */
  175. $table_buttom = new TTable;
  176. $table_buttom->addRowSet(array($save_button, $new_button, $back_button), '', '')->class = 'tformaction'; // CSS class
  177. $this->form->add($table_buttom);
  178. $this->form->add($notebook);
  179. /**
  180. * **************************************************
  181. * ADD CONTENT TO CONTAINER
  182. * **************************************************
  183. */
  184. // wrap the page content using vertical box
  185. $vbox = new TVBox;
  186. $vbox->add(new TXMLBreadCrumb('menu.xml', 'ClientePessoaFisicaList'));
  187. $vbox->add($notebook);
  188. parent::add($vbox);
  189. parent::add($table_buttom);
  190. }
  191. /**
  192. * Save the Cliente and the PessoaTelefone's
  193. */
  194. public static function onSave($param) {
  195. try {
  196. TTransaction::open('qualitta');
  197. //TTransaction::setLogger(new TLoggerSTD); // standard output
  198. var_dump($param);
  199. exit;
  200. ...
  201. ?>

</your>
LF

O que está retornando é:
array (size=3) 'class' => string 'ClientePessoaFisicaForm' (length=23) 'method' => string 'onSave' (length=6) 'static' => string '1' (length=1)
RR

Tenta:
 
  1. <?php
  2. public function onSave(){
  3. try
  4. {
  5. $data = $this->form->getData(); // get form data as array
  6. var_dump($data);
  7. //etc....
  8. }
  9. catch (Exception $e) // in case of exception
  10. {
  11. new TMessage('error', $e->getMessage());
  12. $this->form->setData( $this->form->getData() );
  13. }
  14. }
  15. ?>
LF

Não funcionou... melhorou mas ainda retornou o objeto com todos os campos nulos.
object(stdClass)[200] public 'cliente_id' => string '' (length=0) public 'cliente_status' => string '' (length=0) public 'pessoa_fisica_id' => string '' (length=0) public 'pessoa_fisica_nome' => string '' (length=0) public 'pessoa_fisica_data_nascimento' => string '' (length=0) public 'pessoa_fisica_cpf' => string '' (length=0) public 'pessoa_fisica_rg' => string '' (length=0) public 'pessoa_fisica_rg_orgao' => string '' (length=0) public 'pessoa_fisica_rg_uf' => string '' (length=0) public 'cliente_observacao' => string '' (length=0) public 'pessoa_id' => string '' (length=0)
RR

Sinceramente não sei o que há de errado no seu caso.. A principio meu problema era igual o que voce relatou, e consegui resolver com a ajuda do Marcelo, ou seja, incluindo o notebook no $this->form.
LF

Resolvido! Muito obrigado Renato Ricci.
Por mais que eu tivesse inserido o notebook ao form, o erro estava relacionado a resposta do Marcelo. Eu adicionei o notebook ao form e depois adicionei o notebook ao vbox para o parent, ou seja, eu não adicionei o form ao parent. Depois de uma tarde de releitura do código... encontrei o erro...
Muito obrigado.

 
  1. <?php
  2. $this->form->add($table_buttom);
  3. $this->form->add($notebook);
  4. /**
  5. * **************************************************
  6. * ADD CONTENT TO CONTAINER
  7. * **************************************************
  8. */
  9. // wrap the page content using vertical box
  10. $vbox = new TVBox;
  11. $vbox->add(new TXMLBreadCrumb('menu.xml', 'ClientePessoaFisicaList'));
  12. $vbox->add($notebook);
  13. parent::add($vbox);
  14. parent::add($table_buttom);
  15. ?>
MG

Leonidas

Veja, você adicionou o notebook no form, mas adicionou o notebook no TVBox, mude para:

$vbox->add($this->form);

 
  1. <?php
  2. $vbox = new TVBox;
  3. $vbox->add(new TXMLBreadCrumb('menu.xml', 'ClientePessoaFisicaList'));
  4. $vbox->add($notebook); // ====> Mude e aqui coloque $vbox->add($this->form)
  5. parent::add($vbox);
  6. parent::add($table_buttom);
RR

;)