Lançado Adianti Framework 7.6!
Clique aqui para saber mais
ERRO AO SALVAR SOMA DETALHES NO MESTRE Boa tarde, Tenho um formulário mestre detalhes, onde estou tentando implementar para que some os ítens do detalhe no campo do mestre. Após salvar a som dos detalhes, ele exclui todos os ítens do detalhe. Tentei seguir o exemplo do tutor más não está dando certo. Onde estou errando? Segue código do Form abaixo. Desde já agradeço. ...
AR
ERRO AO SALVAR SOMA DETALHES NO MESTRE  
Boa tarde,
Tenho um formulário mestre detalhes, onde estou tentando implementar para que some os ítens do detalhe no campo do mestre.
Após salvar a som dos detalhes, ele exclui todos os ítens do detalhe.

Tentei seguir o exemplo do tutor más não está dando certo.

Onde estou errando?

Segue código do Form abaixo. Desde já agradeço.

  1. <?php
  2. /**
  3.  * ReceitaForm Master/Detail
  4.  * @author  Alexandre M. Roberto
  5.  */
  6. class ReceitaForm extends TPage
  7. {
  8.     protected $form// form
  9.     protected $detail_list;
  10.     // trait with saveFile, saveFiles, ...
  11.     use Adianti\Base\AdiantiFileSaveTrait;
  12.         
  13.     /**
  14.      * Page constructor
  15.      */
  16.     public function __construct()
  17.     {
  18.         parent::__construct();
  19.         
  20.         
  21.         // creates the form
  22.         $this->form = new BootstrapFormBuilder('form_Receita');
  23.         $this->form->setFormTitle('Receita');
  24.         
  25.         // master fields
  26.         $id = new TEntry('id');
  27.         $dt_receita = new TDate('dt_receita');
  28.         $mes = new TCombo('mes');
  29.         $ano = new TCombo('ano');
  30.         $contribuicoes = new TEntry('contribuicoes');
  31.         $ofertas = new TEntry('ofertas');
  32.         $promocoes = new TEntry('promocoes');
  33.         $patrimonial = new TEntry('patrimonial');
  34.         $outros = new TEntry('outros');
  35.         $total = new TEntry('total');
  36.         $dizimo = new TEntry('dizimo');
  37.         $ofertas_a_repassar = new TEntry('ofertas_a_repassar');
  38.         $comprovantes = new TMultiFile('comprovantes');
  39.         $dep_receitas = new TDate('dep_receitas');
  40.         $dep_ofertas_a_repassar = new TDate('dep_ofertas_a_repassar');
  41.         $observacoes = new TText('observacoes');
  42.         
  43.         $dt_receita->setMask('dd/mm/yyyy');
  44.         $dt_receita->setDatabaseMask('yyyy-mm-dd');
  45.         $dt_receita->setValuedate('Y-m-d') );
  46.         $total->setEditable(FALSE);
  47.         $dizimo->setEditable(FALSE);
  48.         $ofertas_a_repassar->setEditable(FALSE);
  49.         
  50.         $current = (int) date('Y');
  51.         $mes->addItems( ['01' => 'Janeiro',
  52.                          '02' => 'Fevereiro',
  53.                          '03' => 'Março',
  54.                          '04' => 'Abril',
  55.                          '05' => 'Maio',
  56.                          '06' => 'Junho',
  57.                          '07' => 'Julho',
  58.                          '08' => 'Agosto'
  59.                          '09' => 'Setembro'
  60.                          '10' => 'Outubro'
  61.                          '11' => 'Novembro'
  62.                          '12' => 'Dezembro'] );
  63.         $ano->addItems( [ ($current -5) => ($current -5), ($current -4) => ($current -4), ($current -3) => ($current -3), ($current -2) => ($current -2), ($current -1) => ($current -1), $current => $current ] );
  64.         
  65.         $comprovantes->setAllowedExtensions( ['png''jpg''pdf'] );
  66.         $comprovantes->enableFileHandling();
  67.         $comprovantes->enableImageGallery();
  68.         $comprovantes->enablePopover('Preview''<img style="max-width:300px" src="download.php?file={file_name}">');
  69.         $id->setSize('100%');
  70.         $dt_receita->setSize('100%');
  71.         $mes->setSize('100%');
  72.         $ano->setSize('100%');
  73.         $contribuicoes->setSize('100%');
  74.         $ofertas->setSize('100%');
  75.         $promocoes->setSize('100%');
  76.         $patrimonial->setSize('100%');
  77.         $outros->setSize('100%');
  78.         $total->setSize('100%');
  79.         $dizimo->setSize('100%');
  80.         $ofertas_a_repassar->setSize('100%');
  81.         $comprovantes->setSize('100%');
  82.         $dep_receitas->setSize('100%');
  83.         $dep_ofertas_a_repassar->setSize('100%');
  84.         $observacoes->setSize('100%');                
  85.         // detail fields
  86.         $detail_uniqid = new THidden('detail_uniqid');
  87.         $detail_id = new THidden('detail_id');
  88.         $detail_dt_oferta = new TDate('detail_dt_oferta');
  89.         $detail_dt_oferta->setMask('dd/mm/yyyy');
  90.         $detail_dt_oferta->setDatabaseMask('yyyy-mm-dd');
  91.         
  92.         $detail_plano_id = new TDBCombo('detail_plano_id''sudeste''Plano''id''favorecido');
  93.         $detail_plano_id->setEditable(FALSE);
  94.         $detail_plano_id->setSize('100%');
  95.         
  96.         $detail_valor = new TEntry('detail_valor');
  97.         $detail_valor->setNumericMask(2',''.'true);                
  98.         
  99.         // exit action
  100.         $detail_dt_oferta->setExitAction(new TAction([$this,'onExitDate']));
  101.         if (!empty($id))
  102.         {
  103.             $id->setEditable(FALSE);
  104.         }
  105.         
  106.         // master fields
  107.         $row $this->form->addFields( [ new TLabel('Id'),         $id ],
  108.                                        [ new TLabel('Dt Receita'), $dt_receita ],
  109.                                        [ new TLabel('Mês'),        $mes ],
  110.                                        [ new TLabel('Ano'),        $ano ] );
  111.         $row->layout = ['col-sm-3''col-sm-3''col-sm-3''col-sm-3' ];
  112.         $row $this->form->addFields( [ new TLabel('Contribuições'),  $contribuicoes ],
  113.                                        [ new TLabel('Ofertas'),        $ofertas ],
  114.                                        [ new TLabel('Promoções'),      $promocoes ],
  115.                                        [ new TLabel('R. Patrimonial'), $patrimonial ] );
  116.         $row->layout = ['col-sm-3''col-sm-3''col-sm-3''col-sm-3' ];
  117.         $row $this->form->addFields( [ new TLabel('Outros'),         $outros ],
  118.                                        [ new TLabel('Total Receitas'), $total ],
  119.                                        [ new TLabel('Dízimo (10%)'),   $dizimo ],
  120.                                        [ new TLabel('Total Ofertas'),  $ofertas_a_repassar ] );
  121.         $row->layout = ['col-sm-3''col-sm-3''col-sm-3''col-sm-3' ];
  122.         $label2 = new TLabel('Depósitos e Comprovantes''#5A73DB'12'');
  123.         $label2->style='text-align:left;border-bottom:1px solid #c0c0c0;width:100%; padding-top: 25px;';
  124.         $this->form->addContent( [$label2] );
  125.         
  126.         $row $this->form->addFields( [ new TLabel('Dep. Dízimo (10%)'),       $dep_receitas ],
  127.                                        [ new TLabel('Dep. Ofertas a Repassar'), $dep_ofertas_a_repassar ] );
  128.         $row->layout = ['col-sm-6''col-sm-6' ];
  129.         $row $this->form->addFields( [ new TLabel('Comprovantes'),      $comprovantes ] );
  130.         $row->layout = ['col-sm-12' ];
  131.         
  132.         // detail fields
  133.                 $label3 = new TLabel('Ofertas a Repassar''#5A73DB'12'');
  134.         $label3->style='text-align:left;border-bottom:1px solid #c0c0c0;width:100%; padding-top: 25px;';
  135.         $this->form->addContent( [$label3] );
  136.         $this->form->addFields( [$detail_uniqid] );
  137.         $this->form->addFields( [$detail_id] );
  138.         
  139.         $row $this->form->addFields( [ new TLabel('Dt. Oferta'),     $detail_dt_oferta ],
  140.                                        [ new TLabel('Favorecido'),     $detail_plano_id ],
  141.                                        [ new TLabel('Valor'),          $detail_valor ] );
  142.         $row->layout = ['col-sm-2''col-sm-8''col-sm-2' ];
  143.         $add TButton::create('add', [$this'onDetailAdd'], _t('Register'), 'fa:plus-circle green');
  144.         $add->getAction()->setParameter('static','1');
  145.         $this->form->addFields( [], [$add] );
  146.         
  147.         $this->detail_list = new BootstrapDatagridWrapper(new TDataGrid);
  148.         $this->detail_list->setId('Oferta_list');
  149.         $this->detail_list->generateHiddenFields();
  150.         $this->detail_list->style "min-width: 700px; width:100%;margin-bottom: 10px";
  151.         
  152.         // items
  153.         $this->detail_list->addColumn( new TDataGridColumn('uniqid''Uniqid''center') )->setVisibility(false);
  154.         $this->detail_list->addColumn( new TDataGridColumn('id''Id''center') )->setVisibility(false);
  155.         $dt $this->detail_list->addColumn( new TDataGridColumn('dt_oferta''Dt Oferta''left'50) );
  156.         $pl $this->detail_list->addColumn( new TDataGridColumn('plano_id''Plano Id''left'100) );
  157.         $vl $this->detail_list->addColumn( new TDataGridColumn('valor''Valor''left'100) );
  158.         
  159.         $dt->setTransformer( function($value$object) {
  160.         if ($value)
  161.            $value TDate::convertToMask($value'yyyy-mm-dd''dd/mm/yyyy'true);
  162.         });
  163.         
  164.         $pl->setTransformer(function($value) {
  165.             return Plano::findInTransaction('sudeste'$value)->favorecido;
  166.         });
  167.         
  168.         $format_value = function($value) {
  169.             if (is_numeric($value)) {
  170.                 return 'R$ '.number_format($value2',''.');
  171.             }
  172.             return $value;
  173.         };
  174.         
  175.         $vl->setTransformer$format_value );
  176.         
  177.         
  178.         // detail actions
  179.         $action1 = new TDataGridAction([$this'onDetailEdit'] );
  180.         $action1->setFields( ['uniqid''*'] );
  181.         
  182.         $action2 = new TDataGridAction([$this'onDetailDelete']);
  183.         $action2->setField('uniqid');
  184.         
  185.         // add the actions to the datagrid
  186.         $this->detail_list->addAction($action1_t('Edit'), 'fa:edit blue');
  187.         $this->detail_list->addAction($action2_t('Delete'), 'far:trash-alt red');
  188.         
  189.         $this->detail_list->createModel();
  190.         
  191.         $panel = new TPanelGroup;
  192.         $panel->add($this->detail_list);
  193.         $panel->getBody()->style 'overflow-x:auto';
  194.         $this->form->addContent( [$panel] );
  195.         $label4 = new TLabel('Obervações''#5A73DB'12'');
  196.         $label4->style='text-align:left;border-bottom:1px solid #c0c0c0;width:100%; padding-top: 25px;';
  197.         $this->form->addContent( [$label4] );
  198.         
  199.         $row $this->form->addFields( [ new TLabel('Observações'),       $observacoes ] );
  200.         $row->layout = ['col-sm-12' ];
  201.         
  202.         $this->form->addAction'Save',  new TAction([$this'onSave'], ['static'=>'1']), 'fa:save green');
  203.         $this->form->addAction'Clear', new TAction([$this'onClear']), 'fa:eraser red');
  204.         
  205.         // create the page container
  206.         $container = new TVBox;
  207.         $container->style 'width: 100%';
  208.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  209.         $container->add($this->form);
  210.         parent::add($container);
  211.     }
  212.     
  213.     public static function onExitDate($params)
  214.     {
  215.         if( !empty($params['detail_dt_oferta']) )
  216.         {
  217.             try
  218.             {
  219.                 TTransaction::open('sudeste');
  220.                 
  221.                 $criteria = new TCriteria;
  222.                 $date TDate::date2us$params['detail_dt_oferta']);
  223.                 $criteria->add( new TFilter'dt_oferta''='$date) );
  224.                 
  225.                 $repository = new TRepository('Plano');
  226.                 $planos $repository->load$criteria );
  227.                 
  228.                 if ($planos)
  229.                 {
  230.                     foreach ($planos as $plano)
  231.                     {
  232.                         TForm::sendData('form_Receita', (object) ['detail_plano_id' => $plano->id ]);
  233.                     }
  234.                 }
  235.                 else
  236.                 {
  237.                     new TMessage('info''Verifique se existe oferta a repassar nesta data e tente novamente!');
  238.                 }                              
  239.             }
  240.             catch (Exception $e)
  241.             {
  242.                 new TMessage('error'$e->getMessage());
  243.                 TTransaction::rollback();
  244.             }
  245.         }
  246.     } 
  247.     
  248.     /**
  249.      * Clear form
  250.      * @param $param URL parameters
  251.      */
  252.     public function onClear($param)
  253.     {
  254.         $this->form->clear(TRUE);
  255.     }
  256.     
  257.     /**
  258.      * Add detail item
  259.      * @param $param URL parameters
  260.      */
  261.     public function onDetailAdd$param )
  262.     {
  263.         try
  264.         {
  265.             $this->form->validate();
  266.             $data $this->form->getData();
  267.             
  268.             /** validation sample
  269.             if (empty($data->fieldX))
  270.             {
  271.                 throw new Exception('The field fieldX is required');
  272.             }
  273.             **/
  274.             
  275.             $uniqid = !empty($data->detail_uniqid) ? $data->detail_uniqid uniqid();
  276.             
  277.             $grid_data = [];
  278.             $grid_data['uniqid'] = $uniqid;
  279.             $grid_data['id'] = $data->detail_id;
  280.             $grid_data['dt_oferta'] = $data->detail_dt_oferta;
  281.             $grid_data['plano_id'] = $data->detail_plano_id;
  282.             $grid_data['valor'] = $data->detail_valor;
  283.             
  284.             // insert row dynamically
  285.             $row $this->detail_list->addItem( (object) $grid_data );
  286.             $row->id $uniqid;
  287.             
  288.             TDataGrid::replaceRowById('Oferta_list'$uniqid$row);
  289.             
  290.             // clear detail form fields
  291.             $data->detail_uniqid '';
  292.             $data->detail_id '';
  293.             $data->detail_dt_oferta '';
  294.             $data->detail_plano_id '';
  295.             $data->detail_valor '';
  296.             
  297.             // send data, do not fire change/exit events
  298.             TForm::sendData'form_Receita'$datafalsefalse );
  299.         }
  300.         catch (Exception $e)
  301.         {
  302.             $this->form->setData$this->form->getData());
  303.             new TMessage('error'$e->getMessage());
  304.         }
  305.     }
  306.     
  307.     /**
  308.      * Edit detail item
  309.      * @param $param URL parameters
  310.      */
  311.     public static function onDetailEdit$param )
  312.     {
  313.         $data = new stdClass;
  314.         $data->detail_uniqid $param['uniqid'];
  315.         $data->detail_id $param['id'];
  316.         $data->detail_dt_oferta $param['dt_oferta'];
  317.         $data->detail_plano_id $param['plano_id'];
  318.         $data->detail_valor $param['valor'];
  319.         
  320.         // send data, do not fire change/exit events
  321.         TForm::sendData'form_Receita'$datafalsefalse );
  322.     }
  323.     
  324.     /**
  325.      * Delete detail item
  326.      * @param $param URL parameters
  327.      */
  328.     public static function onDetailDelete$param )
  329.     {
  330.         // clear detail form fields
  331.         $data = new stdClass;
  332.         $data->detail_uniqid '';
  333.         $data->detail_id '';
  334.         $data->detail_dt_oferta '';
  335.         $data->detail_plano_id '';
  336.         $data->detail_valor '';
  337.         
  338.         // send data, do not fire change/exit events
  339.         TForm::sendData'form_Receita'$datafalsefalse );
  340.         
  341.         // remove row
  342.         TDataGrid::removeRowById('Oferta_list'$param['uniqid']);
  343.     }
  344.     
  345.     /**
  346.      * Load Master/Detail data from database to form
  347.      */
  348.     public function onEdit($param)
  349.     {
  350.         try
  351.         {
  352.             TTransaction::open('sudeste');
  353.             
  354.             if (isset($param['key']))
  355.             {
  356.                 $key $param['key'];
  357.                 
  358.                 $object = new Receita($key);
  359.                 $items  Oferta::where('receita_id''='$key)->load();
  360.                 
  361.                 foreach( $items as $item )
  362.                 {
  363.                     $item->uniqid uniqid();
  364.                     $row $this->detail_list->addItem$item );
  365.                     $row->id $item->uniqid;
  366.                 }
  367.                 $this->form->setData($object);
  368.                 TTransaction::close();
  369.             }
  370.             else
  371.             {
  372.                 $this->form->clear(TRUE);
  373.             }
  374.         }
  375.         catch (Exception $e// in case of exception
  376.         {
  377.             new TMessage('error'$e->getMessage());
  378.             TTransaction::rollback();
  379.         }
  380.     }
  381.     
  382.     /**
  383.      * Save the Master/Detail data from form to database
  384.      */
  385.     public function onSave($param)
  386.     {
  387.         try
  388.         {
  389.             // open a transaction with database
  390.             TTransaction::open('sudeste');
  391.             
  392.             $data $this->form->getData();
  393.             $this->form->validate();
  394.             
  395.             $master = new Receita;
  396.             $master->fromArray( (array) $data);
  397.             $master->total $master->contribuicoes $master->ofertas $master->patrimonial $master->promocoes $master->outros;
  398.             $master->dizimo $master->total * (10 100);
  399.             $master->system_user_id TSession::getValue('userid');
  400.             $master->system_unit_id TSession::getValue('userunitid');
  401.             $master->store();
  402.             
  403.             Oferta::where('receita_id''='$master->id)->delete();
  404.             
  405.             $total 0;           
  406.             if( $param['Oferta_list_dt_oferta'] )
  407.             {
  408.                 foreach( $param['Oferta_list_dt_oferta'] as $key => $item_id )
  409.                 {
  410.                     $detail = new Oferta;
  411.                     $detail->dt_oferta  $param['Oferta_list_dt_oferta'][$key];
  412.                     $detail->plano_id  $param['Oferta_list_plano_id'][$key];
  413.                     $detail->valor  $param['Oferta_list_valor'][$key];
  414.                     $detail->receita_id $master->id;
  415.                     $total += $detail->valor;
  416.                     $detail->store();                                       
  417.                 }
  418.             }
  419.             $master->ofertas_a_repassar $total;
  420.             $master->store(); // stores the object
  421.             
  422.             TForm::sendData('form_Receita', (object) ['id' => $master->id]);
  423.             
  424.             TTransaction::close(); // close the transaction
  425.                                    
  426.             new TMessage('info'AdiantiCoreTranslator::translate('Record saved'));
  427.         }
  428.         catch (Exception $e// in case of exception
  429.         {
  430.             new TMessage('error'$e->getMessage());
  431.             $this->form->setData$this->form->getData() ); // keep form data
  432.             TTransaction::rollback();
  433.         }
  434.     }
  435. }

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


NR

Provavelmente a função store do model Receita está chamando saveAggregate ou saveComposite. Essas funções fazem o delete dos itens antes de salvar os novos. No seu caso, como está controlando isso diretamente no onSave, pode apagar a função store do model
AR

Era isso mesmo.
Muito obrigado Nataniel.
Grande abraço!
AR

Boa tarde Natanael,

Neste mesmo formulário, coloquei as máscaras para os valores numéricos em todos os campos (->setNumericMask(2,',','.', true))

Ao salvar está multiplicando e salvando os valores informados por 100.

Se informo 100 ele salva 10.000.

Tem idéia do que pode ser isso?
AL

Boa tarde a todos, estou com o mesmo problema, quando salvo um registro no datails ele coloca o valor de 95.000,00 como 95000.00 e quando salva o registro ele coloca mais dois zeros, estou tentando tirar dois zeros antes de salvar o campo.
AL

Boa tarde a todos!

Estou com o mesmo problema, quando salvo um registro no datalhe ele coloca o valor de 95.000,00 como 95000.00 no formulário e quando salva o registro ele coloca mais dois zeros, estou tentando tirar dois zeros antes de salvar o campo.