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

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto 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.                     
  23.      $keep_items[] = $detail->id;
  24. ?>
RF

Boa tarde...

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