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:
Em anexo imagem da tela, segue também o código:
- <?php
- /**
- * ClienteForm Master/Detail
- * @author <your name here>
- */
- class ClienteForm extends TPage
- {
- protected $form; // form
- protected $formFields;
- protected $detail_list;
- /**
- * Page constructor
- */
- public function __construct()
- {
- parent::__construct();
- // creates the form
- $this->form = new TForm('form_Cliente');
- $this->form->class = 'tform'; // CSS class
- $this->form->style = 'max-width:700px'; // style
- parent::include_css('app/resources/custom-frame.css');
- $table_master = new TTable;
- $table_master->width = '100%';
- $table_master->addRowSet( new TLabel('Prospecção de Clientes'), '', '')->class = 'tformtitle';
- // add a table inside form
- $table_general = new TTable;
- $table_detail = new TTable;
- $table_general-> width = '100%';
- $table_detail -> width = '100%';
- $frame_general = new TFrame;
- $frame_general->setLegend('Dados do Cliente');
- $frame_general->style = 'background:whiteSmoke';
- $frame_general->add($table_general);
- $table_master->addRow()->addCell( $frame_general )->colspan=2;
- $row = $table_master->addRow();
- $row->addCell( $table_detail );
- $this->form->add($table_master);
- // master fields
- $id = new TEntry('id');
- $status = new TCombo('status');
- $nome = new TEntry('nome');
- $telefone = new TEntry('telefone');
- $email = new TEntry('email');
- $acompanhar = new TCombo('acompanhar');
- $proximocontato = new TDate('proximocontato');
- $alterado = new TEntry('alterado');
- //Validações, obrigatóriedades e exibição dos campos
- $alterado ->setEditable(FALSE);
- $email ->addValidation('E-mail' , new TEmailValidator);
- $telefone ->setMask('(99)99999-9999');
- $telefone ->addValidation('Telefone' , new TRequiredValidator);
- $acompanhar ->addValidation('Acompanhar' , new TRequiredValidator);
- $nome ->addValidation('Nome' , new TRequiredValidator);
- $status ->addValidation('Status' , new TRequiredValidator);
- //Itens do Status
- $itemStatus= array();
- $itemStatus['Lançado'] = 'Lançado';
- $itemStatus['Finalizado'] = 'Finalizado';
- $itemStatus['Acompanhar'] = 'Acompanhar';
- $status->setValue('Lançado');
- $status->addItems($itemStatus);
- //Itens do Acompanhar
- $itemAcompanhar= array();
- $itemAcompanhar['Sim'] = 'Sim';
- $itemAcompanhar['Não'] = 'Não';
- $acompanhar->setValue('Sim');
- $acompanhar->addItems($itemAcompanhar);
- if (!empty($id))
- {
- $id->setEditable(FALSE);
- }
- // detail fields
- $detail_id = new THidden('detail_id');
- $detail_titulo = new TEntry('detail_titulo');
- $detail_dia = new TDate ('detail_dia');
- $detail_hora = new TEntry('detail_hora');
- $detail_comentario = new TText('detail_comentario');
- //mascara para a hora
- $detail_hora ->setMask('99:99');
- /** samples
- $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
- $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
- $fieldX->setSize( 100, 40 ); // set size
- **/
- // master
- $table_general->addRowSet( new TLabel('Id'), $id );
- $table_general->addRowSet( new TLabel('Status'), $status );
- $table_general->addRowSet( new TLabel('Nome'), $nome );
- $table_general->addRowSet( new TLabel('Telefone'), $telefone );
- $table_general->addRowSet( new TLabel('Email'), $email );
- $table_general->addRowSet( new TLabel('Acompanhar'), $acompanhar );
- $table_general->addRowSet( new TLabel('Próximo Contato'), $proximocontato );
- $table_general->addRowSet( new TLabel('Alterado'), $alterado );
- // detail
- $frame_details = new TFrame();
- $frame_details->setLegend('Histórico');
- $row = $table_detail->addRow();
- $row->addCell($frame_details);
- $btn_save_detail = new TButton('btn_save_detail');
- $btn_save_detail->setAction(new TAction(array($this, 'onSaveDetail')), 'Gravar');
- $btn_save_detail->setImage('fa:save');
- $table_details = new TTable;
- $frame_details->add($table_details);
- $table_details->addRowSet( '', $detail_id );
- $table_details->addRowSet( new TLabel('Título'), $detail_titulo );
- $table_details->addRowSet( new TLabel('Dia'), $detail_dia );
- $table_details->addRowSet( new TLabel('Hora'), $detail_hora );
- $table_details->addRowSet( new TLabel('Comentário'), $detail_comentario );
- $table_details->addRowSet( $btn_save_detail );
- $this->detail_list = new TQuickGrid;
- $this->detail_list->setHeight( 175 );
- $this->detail_list->makeScrollable();
- $this->detail_list->disableDefaultClick();
- $this->detail_list->addQuickColumn('', 'edit', 'left', 50);
- $this->detail_list->addQuickColumn('', 'delete', 'left', 50);
- // items
- $this->detail_list->addQuickColumn('Título', 'titulo', 'left', 200);
- $this->detail_list->addQuickColumn('Dia', 'dia', 'left', 200);
- $this->detail_list->addQuickColumn('Hora', 'hora', 'left', 200);
- $this->detail_list->addQuickColumn('Comentário', 'comentario', 'left', 200);
- $this->detail_list->createModel();
- $row = $table_detail->addRow();
- $row->addCell($this->detail_list);
- // create an action button (save)
- $save_button=new TButton('save');
- $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));
- $save_button->setImage('ico_save.png');
- // create an new button (edit with no parameters)
- $new_button=new TButton('new');
- $new_button->setAction(new TAction(array($this, 'onClear')), _t('New'));
- $new_button->setImage('ico_new.png');
- // define form fields
- $this->formFields = array($id,$status,$nome,$telefone,$email,$acompanhar,$proximocontato,$alterado,$detail_titulo,$detail_dia,$detail_hora,$detail_comentario);
- $this->formFields[] = $btn_save_detail;
- $this->formFields[] = $save_button;
- $this->formFields[] = $new_button;
- $this->formFields[] = $detail_id;
- $this->form->setFields( $this->formFields );
- $table_master->addRowSet( array($save_button, $new_button), '', '')->class = 'tformaction'; // CSS class
- // create the page container
- $container = new TVBox;
- $container->style = 'width: 90%';
- // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- parent::add($container);
- }
- /**
- * Clear form
- * @param $param URL parameters
- */
- public function onClear($param)
- {
- $this->form->clear(TRUE);
- TSession::setValue(__CLASS__.'_items', array());
- $this->onReload( $param );
- }
- /**
- * Save an item from form to session list
- * @param $param URL parameters
- */
- public function onSaveDetail( $param )
- {
- try
- {
- TTransaction::open('sample');
- $data = $this->form->getData();
- /** validation sample
- if (! $data->fieldX)
- throw new Exception('The field fieldX is required');
- **/
- $items = TSession::getValue(__CLASS__.'_items');
- $key = empty($data->detail_id) ? 'X'.mt_rand(1000000000, 1999999999) : $data->detail_id;
- $items[ $key ] = array();
- $items[ $key ]['id'] = $key;
- $items[ $key ]['titulo'] = $data->detail_titulo;
- $items[ $key ]['dia'] = $data->detail_dia;
- $items[ $key ]['hora'] = $data->detail_hora;
- $items[ $key ]['comentario'] = $data->detail_comentario;
- TSession::setValue(__CLASS__.'_items', $items);
- // clear detail form fields
- $data->detail_id = '';
- $data->detail_titulo = '';
- $data->detail_dia = '';
- $data->detail_hora = '';
- $data->detail_comentario = '';
- TTransaction::close();
- $this->form->setData($data);
- $this->onReload( $param ); // reload the items
- }
- catch (Exception $e)
- {
- $this->form->setData( $this->form->getData());
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Load an item from session list to detail form
- * @param $param URL parameters
- */
- public function onEditDetail( $param )
- {
- $data = $this->form->getData();
- // read session items
- $items = TSession::getValue(__CLASS__.'_items');
- // get the session item
- $item = $items[ $param['item_key'] ];
- $data->detail_id = $item['id'];
- $data->detail_titulo = $item['titulo'];
- $data->detail_dia = $item['dia'];
- $data->detail_hora = $item['hora'];
- $data->detail_comentario = $item['comentario'];
- // fill detail fields
- $this->form->setData( $data );
- $this->onReload( $param );
- }
- /**
- * Delete an item from session list
- * @param $param URL parameters
- */
- public function onDeleteDetail( $param )
- {
- $data = $this->form->getData();
- // reset items
- $data->detail_titulo = '';
- $data->detail_dia = '';
- $data->detail_hora = '';
- $data->detail_comentario = '';
- // clear form data
- $this->form->setData( $data );
- // read session items
- $items = TSession::getValue(__CLASS__.'_items');
- // delete the item from session
- unset($items[ $param['item_key'] ] );
- TSession::setValue(__CLASS__.'_items', $items);
- // reload items
- $this->onReload( $param );
- }
- /**
- * Load the items list from session
- * @param $param URL parameters
- */
- public function onReload($param)
- {
- // read session items
- $items = TSession::getValue(__CLASS__.'_items');
- $this->detail_list->clear(); // clear detail list
- $data = $this->form->getData();
- if ($items)
- {
- $cont = 1;
- foreach ($items as $list_item_key => $list_item)
- {
- $item_name = 'prod_' . $cont++;
- $item = new StdClass;
- // create action buttons
- $action_del = new TAction(array($this, 'onDeleteDetail'));
- $action_del->setParameter('item_key', $list_item_key);
- $action_edi = new TAction(array($this, 'onEditDetail'));
- $action_edi->setParameter('item_key', $list_item_key);
- $button_del = new TButton('delete_detail'.$cont);
- $button_del->class = 'btn btn-default btn-sm';
- $button_del->setAction( $action_del, '' );
- $button_del->setImage('fa:trash-o red fa-lg');
- $button_edi = new TButton('edit_detail'.$cont);
- $button_edi->class = 'btn btn-default btn-sm';
- $button_edi->setAction( $action_edi, '' );
- $button_edi->setImage('fa:edit blue fa-lg');
- $item->edit = $button_edi;
- $item->delete = $button_del;
- $this->formFields[ $item_name.'_edit' ] = $item->edit;
- $this->formFields[ $item_name.'_delete' ] = $item->delete;
- // items
- $item->id = $list_item['id'];
- $item->titulo = $list_item['titulo'];
- $item->dia = $list_item['dia'];
- $item->hora = $list_item['hora'];
- $item->comentario = $list_item['comentario'];
- $row = $this->detail_list->addItem( $item );
- $row->onmouseover='';
- $row->onmouseout='';
- }
- $this->form->setFields( $this->formFields );
- }
- $this->loaded = TRUE;
- }
- /**
- * Load Master/Detail data from database to form/session
- */
- public function onEdit($param)
- {
- try
- {
- TTransaction::open('sample');
- if (isset($param['key']))
- {
- $key = $param['key'];
- $object = new Cliente($key);
- $items = Prospeccao::where('cliente_id', '=', $key)->load();
- $session_items = array();
- foreach( $items as $item )
- {
- $item_key = $item->id;
- $session_items[$item_key] = $item->toArray();
- $session_items[$item_key]['id'] = $item->id;
- $session_items[$item_key]['titulo'] = $item->titulo;
- $session_items[$item_key]['dia'] = $item->dia;
- $session_items[$item_key]['hora'] = $item->hora;
- $session_items[$item_key]['comentario'] = $item->comentario;
- }
- TSession::setValue(__CLASS__.'_items', $session_items);
- $this->form->setData($object); // fill the form with the active record data
- $this->onReload( $param ); // reload items list
- TTransaction::close(); // close transaction
- }
- else
- {
- $this->form->clear(TRUE);
- TSession::setValue(__CLASS__.'_items', null);
- $this->onReload( $param );
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- }
- /**
- * Save the Master/Detail data from form/session to database
- */
- public function onSave()
- {
- try
- {
- // open a transaction with database
- TTransaction::open('sample');
- $data = $this->form->getData();
- $master = new Cliente;
- $master->fromArray( (array) $data);
- $this->form->validate(); // form validation
- $master->store(); // save master object
- // delete details
- $old_items = Prospeccao::where('cliente_id', '=', $master->id)->load();
- $keep_items = array();
- // get session items
- $items = TSession::getValue(__CLASS__.'_items');
- if( $items )
- {
- foreach( $items as $item )
- {
- if (substr($item['id'],0,1) == 'X' ) // new record
- {
- $detail = new Prospeccao;
- }
- else
- {
- $detail = Prospeccao::find($item['id']);
- }
- $detail->titulo = $item['titulo'];
- $detail->dia = $item['dia'];
- $detail->hora = $item['hora'];
- $detail->comentario = $item['comentario'];
- $detail->cliente_id = $master->id;
- $detail->store();
- $keep_items[] = $detail->id;
- }
- }
- if ($old_items)
- {
- foreach ($old_items as $old_item)
- {
- if (!in_array( $old_item->id, $keep_items))
- {
- $old_item->delete();
- }
- }
- }
- TTransaction::close(); // close the transaction
- // reload form and session items
- $this->onEdit(array('key'=>$master->id));
- new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- $this->form->setData( $this->form->getData() ); // keep form data
- TTransaction::rollback();
- }
- }
- /**
- * Show the page
- */
- public function show()
- {
- // check if the datagrid is already loaded
- if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
- {
- $this->onReload( func_get_arg(0) );
- }
- parent::show();
- }
- }
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:
Boa tarde...
Muito obrigado, fiz a alteração e deu certo.