Erro ao gravar o formulário Bom dia, eu criei um formulário na opção new page > new master/detail form. Quando faço a gravação do formulário pela primeira vez tudo da certo, porém ao acrescentar mais um item aparece o erro: Warning: Creating default object from empty value in C:xampphtdocsprismaappcontrolprospeccaoClienteForm.class.php on line 433 Em anexo imagem da tela, segue também o código: ...
RF
Erro ao gravar o formulário  
Bom dia, eu criei um formulário na opção new page > new master/detail form. Quando faço a gravação do formulário pela primeira vez tudo da certo, porém ao acrescentar mais um item aparece o erro: Warning: Creating default object from empty value in C:xampphtdocsprismaappcontrolprospeccaoClienteForm.class.php on line 433

Em anexo imagem da tela, segue também o código:

 
  1. <?php
  2. /**
  3. * ClienteForm Master/Detail
  4. * @author <your name here>
  5. */
  6. class ClienteForm extends TPage
  7. {
  8. protected $form; // form
  9. protected $formFields;
  10. protected $detail_list;
  11. /**
  12. * Page constructor
  13. */
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. // creates the form
  18. $this->form = new TForm('form_Cliente');
  19. $this->form->class = 'tform'; // CSS class
  20. $this->form->style = 'max-width:700px'; // style
  21. parent::include_css('app/resources/custom-frame.css');
  22. $table_master = new TTable;
  23. $table_master->width = '100%';
  24. $table_master->addRowSet( new TLabel('Prospecção de Clientes'), '', '')->class = 'tformtitle';
  25. // add a table inside form
  26. $table_general = new TTable;
  27. $table_detail = new TTable;
  28. $table_general-> width = '100%';
  29. $table_detail -> width = '100%';
  30. $frame_general = new TFrame;
  31. $frame_general->setLegend('Dados do Cliente');
  32. $frame_general->style = 'background:whiteSmoke';
  33. $frame_general->add($table_general);
  34. $table_master->addRow()->addCell( $frame_general )->colspan=2;
  35. $row = $table_master->addRow();
  36. $row->addCell( $table_detail );
  37. $this->form->add($table_master);
  38. // master fields
  39. $id = new TEntry('id');
  40. $status = new TCombo('status');
  41. $nome = new TEntry('nome');
  42. $telefone = new TEntry('telefone');
  43. $email = new TEntry('email');
  44. $acompanhar = new TCombo('acompanhar');
  45. $proximocontato = new TDate('proximocontato');
  46. $alterado = new TEntry('alterado');
  47. //Validações, obrigatóriedades e exibição dos campos
  48. $alterado ->setEditable(FALSE);
  49. $email ->addValidation('E-mail' , new TEmailValidator);
  50. $telefone ->setMask('(99)99999-9999');
  51. $telefone ->addValidation('Telefone' , new TRequiredValidator);
  52. $acompanhar ->addValidation('Acompanhar' , new TRequiredValidator);
  53. $nome ->addValidation('Nome' , new TRequiredValidator);
  54. $status ->addValidation('Status' , new TRequiredValidator);
  55. //Itens do Status
  56. $itemStatus= array();
  57. $itemStatus['Lançado'] = 'Lançado';
  58. $itemStatus['Finalizado'] = 'Finalizado';
  59. $itemStatus['Acompanhar'] = 'Acompanhar';
  60. $status->setValue('Lançado');
  61. $status->addItems($itemStatus);
  62. //Itens do Acompanhar
  63. $itemAcompanhar= array();
  64. $itemAcompanhar['Sim'] = 'Sim';
  65. $itemAcompanhar['Não'] = 'Não';
  66. $acompanhar->setValue('Sim');
  67. $acompanhar->addItems($itemAcompanhar);
  68. if (!empty($id))
  69. {
  70. $id->setEditable(FALSE);
  71. }
  72. // detail fields
  73. $detail_id = new THidden('detail_id');
  74. $detail_titulo = new TEntry('detail_titulo');
  75. $detail_dia = new TDate ('detail_dia');
  76. $detail_hora = new TEntry('detail_hora');
  77. $detail_comentario = new TText('detail_comentario');
  78. //mascara para a hora
  79. $detail_hora ->setMask('99:99');
  80. /** samples
  81. $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  82. $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  83. $fieldX->setSize( 100, 40 ); // set size
  84. **/
  85. // master
  86. $table_general->addRowSet( new TLabel('Id'), $id );
  87. $table_general->addRowSet( new TLabel('Status'), $status );
  88. $table_general->addRowSet( new TLabel('Nome'), $nome );
  89. $table_general->addRowSet( new TLabel('Telefone'), $telefone );
  90. $table_general->addRowSet( new TLabel('Email'), $email );
  91. $table_general->addRowSet( new TLabel('Acompanhar'), $acompanhar );
  92. $table_general->addRowSet( new TLabel('Próximo Contato'), $proximocontato );
  93. $table_general->addRowSet( new TLabel('Alterado'), $alterado );
  94. // detail
  95. $frame_details = new TFrame();
  96. $frame_details->setLegend('Histórico');
  97. $row = $table_detail->addRow();
  98. $row->addCell($frame_details);
  99. $btn_save_detail = new TButton('btn_save_detail');
  100. $btn_save_detail->setAction(new TAction(array($this, 'onSaveDetail')), 'Gravar');
  101. $btn_save_detail->setImage('fa:save');
  102. $table_details = new TTable;
  103. $frame_details->add($table_details);
  104. $table_details->addRowSet( '', $detail_id );
  105. $table_details->addRowSet( new TLabel('Título'), $detail_titulo );
  106. $table_details->addRowSet( new TLabel('Dia'), $detail_dia );
  107. $table_details->addRowSet( new TLabel('Hora'), $detail_hora );
  108. $table_details->addRowSet( new TLabel('Comentário'), $detail_comentario );
  109. $table_details->addRowSet( $btn_save_detail );
  110. $this->detail_list = new TQuickGrid;
  111. $this->detail_list->setHeight( 175 );
  112. $this->detail_list->makeScrollable();
  113. $this->detail_list->disableDefaultClick();
  114. $this->detail_list->addQuickColumn('', 'edit', 'left', 50);
  115. $this->detail_list->addQuickColumn('', 'delete', 'left', 50);
  116. // items
  117. $this->detail_list->addQuickColumn('Título', 'titulo', 'left', 200);
  118. $this->detail_list->addQuickColumn('Dia', 'dia', 'left', 200);
  119. $this->detail_list->addQuickColumn('Hora', 'hora', 'left', 200);
  120. $this->detail_list->addQuickColumn('Comentário', 'comentario', 'left', 200);
  121. $this->detail_list->createModel();
  122. $row = $table_detail->addRow();
  123. $row->addCell($this->detail_list);
  124. // create an action button (save)
  125. $save_button=new TButton('save');
  126. $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));
  127. $save_button->setImage('ico_save.png');
  128. // create an new button (edit with no parameters)
  129. $new_button=new TButton('new');
  130. $new_button->setAction(new TAction(array($this, 'onClear')), _t('New'));
  131. $new_button->setImage('ico_new.png');
  132. // define form fields
  133. $this->formFields = array($id,$status,$nome,$telefone,$email,$acompanhar,$proximocontato,$alterado,$detail_titulo,$detail_dia,$detail_hora,$detail_comentario);
  134. $this->formFields[] = $btn_save_detail;
  135. $this->formFields[] = $save_button;
  136. $this->formFields[] = $new_button;
  137. $this->formFields[] = $detail_id;
  138. $this->form->setFields( $this->formFields );
  139. $table_master->addRowSet( array($save_button, $new_button), '', '')->class = 'tformaction'; // CSS class
  140. // create the page container
  141. $container = new TVBox;
  142. $container->style = 'width: 90%';
  143. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  144. $container->add($this->form);
  145. parent::add($container);
  146. }
  147. /**
  148. * Clear form
  149. * @param $param URL parameters
  150. */
  151. public function onClear($param)
  152. {
  153. $this->form->clear(TRUE);
  154. TSession::setValue(__CLASS__.'_items', array());
  155. $this->onReload( $param );
  156. }
  157. /**
  158. * Save an item from form to session list
  159. * @param $param URL parameters
  160. */
  161. public function onSaveDetail( $param )
  162. {
  163. try
  164. {
  165. TTransaction::open('sample');
  166. $data = $this->form->getData();
  167. /** validation sample
  168. if (! $data->fieldX)
  169. throw new Exception('The field fieldX is required');
  170. **/
  171. $items = TSession::getValue(__CLASS__.'_items');
  172. $key = empty($data->detail_id) ? 'X'.mt_rand(1000000000, 1999999999) : $data->detail_id;
  173. $items[ $key ] = array();
  174. $items[ $key ]['id'] = $key;
  175. $items[ $key ]['titulo'] = $data->detail_titulo;
  176. $items[ $key ]['dia'] = $data->detail_dia;
  177. $items[ $key ]['hora'] = $data->detail_hora;
  178. $items[ $key ]['comentario'] = $data->detail_comentario;
  179. TSession::setValue(__CLASS__.'_items', $items);
  180. // clear detail form fields
  181. $data->detail_id = '';
  182. $data->detail_titulo = '';
  183. $data->detail_dia = '';
  184. $data->detail_hora = '';
  185. $data->detail_comentario = '';
  186. TTransaction::close();
  187. $this->form->setData($data);
  188. $this->onReload( $param ); // reload the items
  189. }
  190. catch (Exception $e)
  191. {
  192. $this->form->setData( $this->form->getData());
  193. new TMessage('error', $e->getMessage());
  194. }
  195. }
  196. /**
  197. * Load an item from session list to detail form
  198. * @param $param URL parameters
  199. */
  200. public function onEditDetail( $param )
  201. {
  202. $data = $this->form->getData();
  203. // read session items
  204. $items = TSession::getValue(__CLASS__.'_items');
  205. // get the session item
  206. $item = $items[ $param['item_key'] ];
  207. $data->detail_id = $item['id'];
  208. $data->detail_titulo = $item['titulo'];
  209. $data->detail_dia = $item['dia'];
  210. $data->detail_hora = $item['hora'];
  211. $data->detail_comentario = $item['comentario'];
  212. // fill detail fields
  213. $this->form->setData( $data );
  214. $this->onReload( $param );
  215. }
  216. /**
  217. * Delete an item from session list
  218. * @param $param URL parameters
  219. */
  220. public function onDeleteDetail( $param )
  221. {
  222. $data = $this->form->getData();
  223. // reset items
  224. $data->detail_titulo = '';
  225. $data->detail_dia = '';
  226. $data->detail_hora = '';
  227. $data->detail_comentario = '';
  228. // clear form data
  229. $this->form->setData( $data );
  230. // read session items
  231. $items = TSession::getValue(__CLASS__.'_items');
  232. // delete the item from session
  233. unset($items[ $param['item_key'] ] );
  234. TSession::setValue(__CLASS__.'_items', $items);
  235. // reload items
  236. $this->onReload( $param );
  237. }
  238. /**
  239. * Load the items list from session
  240. * @param $param URL parameters
  241. */
  242. public function onReload($param)
  243. {
  244. // read session items
  245. $items = TSession::getValue(__CLASS__.'_items');
  246. $this->detail_list->clear(); // clear detail list
  247. $data = $this->form->getData();
  248. if ($items)
  249. {
  250. $cont = 1;
  251. foreach ($items as $list_item_key => $list_item)
  252. {
  253. $item_name = 'prod_' . $cont++;
  254. $item = new StdClass;
  255. // create action buttons
  256. $action_del = new TAction(array($this, 'onDeleteDetail'));
  257. $action_del->setParameter('item_key', $list_item_key);
  258. $action_edi = new TAction(array($this, 'onEditDetail'));
  259. $action_edi->setParameter('item_key', $list_item_key);
  260. $button_del = new TButton('delete_detail'.$cont);
  261. $button_del->class = 'btn btn-default btn-sm';
  262. $button_del->setAction( $action_del, '' );
  263. $button_del->setImage('fa:trash-o red fa-lg');
  264. $button_edi = new TButton('edit_detail'.$cont);
  265. $button_edi->class = 'btn btn-default btn-sm';
  266. $button_edi->setAction( $action_edi, '' );
  267. $button_edi->setImage('fa:edit blue fa-lg');
  268. $item->edit = $button_edi;
  269. $item->delete = $button_del;
  270. $this->formFields[ $item_name.'_edit' ] = $item->edit;
  271. $this->formFields[ $item_name.'_delete' ] = $item->delete;
  272. // items
  273. $item->id = $list_item['id'];
  274. $item->titulo = $list_item['titulo'];
  275. $item->dia = $list_item['dia'];
  276. $item->hora = $list_item['hora'];
  277. $item->comentario = $list_item['comentario'];
  278. $row = $this->detail_list->addItem( $item );
  279. $row->onmouseover='';
  280. $row->onmouseout='';
  281. }
  282. $this->form->setFields( $this->formFields );
  283. }
  284. $this->loaded = TRUE;
  285. }
  286. /**
  287. * Load Master/Detail data from database to form/session
  288. */
  289. public function onEdit($param)
  290. {
  291. try
  292. {
  293. TTransaction::open('sample');
  294. if (isset($param['key']))
  295. {
  296. $key = $param['key'];
  297. $object = new Cliente($key);
  298. $items = Prospeccao::where('cliente_id', '=', $key)->load();
  299. $session_items = array();
  300. foreach( $items as $item )
  301. {
  302. $item_key = $item->id;
  303. $session_items[$item_key] = $item->toArray();
  304. $session_items[$item_key]['id'] = $item->id;
  305. $session_items[$item_key]['titulo'] = $item->titulo;
  306. $session_items[$item_key]['dia'] = $item->dia;
  307. $session_items[$item_key]['hora'] = $item->hora;
  308. $session_items[$item_key]['comentario'] = $item->comentario;
  309. }
  310. TSession::setValue(__CLASS__.'_items', $session_items);
  311. $this->form->setData($object); // fill the form with the active record data
  312. $this->onReload( $param ); // reload items list
  313. TTransaction::close(); // close transaction
  314. }
  315. else
  316. {
  317. $this->form->clear(TRUE);
  318. TSession::setValue(__CLASS__.'_items', null);
  319. $this->onReload( $param );
  320. }
  321. }
  322. catch (Exception $e) // in case of exception
  323. {
  324. new TMessage('error', $e->getMessage());
  325. TTransaction::rollback();
  326. }
  327. }
  328. /**
  329. * Save the Master/Detail data from form/session to database
  330. */
  331. public function onSave()
  332. {
  333. try
  334. {
  335. // open a transaction with database
  336. TTransaction::open('sample');
  337. $data = $this->form->getData();
  338. $master = new Cliente;
  339. $master->fromArray( (array) $data);
  340. $this->form->validate(); // form validation
  341. $master->store(); // save master object
  342. // delete details
  343. $old_items = Prospeccao::where('cliente_id', '=', $master->id)->load();
  344. $keep_items = array();
  345. // get session items
  346. $items = TSession::getValue(__CLASS__.'_items');
  347. if( $items )
  348. {
  349. foreach( $items as $item )
  350. {
  351. if (substr($item['id'],0,1) == 'X' ) // new record
  352. {
  353. $detail = new Prospeccao;
  354. }
  355. else
  356. {
  357. $detail = Prospeccao::find($item['id']);
  358. }
  359. $detail->titulo = $item['titulo'];
  360. $detail->dia = $item['dia'];
  361. $detail->hora = $item['hora'];
  362. $detail->comentario = $item['comentario'];
  363. $detail->cliente_id = $master->id;
  364. $detail->store();
  365. $keep_items[] = $detail->id;
  366. }
  367. }
  368. if ($old_items)
  369. {
  370. foreach ($old_items as $old_item)
  371. {
  372. if (!in_array( $old_item->id, $keep_items))
  373. {
  374. $old_item->delete();
  375. }
  376. }
  377. }
  378. TTransaction::close(); // close the transaction
  379. // reload form and session items
  380. $this->onEdit(array('key'=>$master->id));
  381. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  382. }
  383. catch (Exception $e) // in case of exception
  384. {
  385. new TMessage('error', $e->getMessage());
  386. $this->form->setData( $this->form->getData() ); // keep form data
  387. TTransaction::rollback();
  388. }
  389. }
  390. /**
  391. * Show the page
  392. */
  393. public function show()
  394. {
  395. // check if the datagrid is already loaded
  396. if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
  397. {
  398. $this->onReload( func_get_arg(0) );
  399. }
  400. parent::show();
  401. }
  402. }

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


NR

Robson, imagino que seja em função do relacionamento entre os models. Ao executar a função store do master estão sendo excluídos os detalhes. Com isso, ao executar $detail = Prospeccao::find($item['id']), nenhum registro é encontrado.

Sugiro 2 opções:
1 - Modificar o model master para não deletar os detalhes na função store.
2 - Ajustar a onSave:
 
  1. <?php
  2. //onSave
  3. ...
  4. foreach( $items as $item )
  5. {
  6. if (substr($item['id'],0,1) == 'X' ) // new record
  7. {
  8. $detail = new Prospeccao;
  9. }
  10. else
  11. {
  12. //$detail = Prospeccao::find($item['id']);
  13. $detail = new Prospeccao;
  14. $detail->id = $item['id'];
  15. }
  16. $detail->titulo = $item['titulo'];
  17. $detail->dia = $item['dia'];
  18. $detail->hora = $item['hora'];
  19. $detail->comentario = $item['comentario'];
  20. $detail->cliente_id = $master->id;
  21. $detail->store();
  22. $keep_items[] = $detail->id;
  23. }
  24. ?>
RF

Boa tarde...

Muito obrigado, fiz a alteração e deu certo.