Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Salvar 2 Datalhes - Mestre/Detalhe Pessoal, bom dia. Fiz uma mestre detalhe com 2 detalhes, estou com um problema para salvar os dados, ele salva 2x. Como posso implementar uma rotina para salvar os 2 detalhes uma vês só? ...
RA
Salvar 2 Datalhes - Mestre/Detalhe  
Pessoal, bom dia. Fiz uma mestre detalhe com 2 detalhes, estou com um problema para salvar os dados, ele salva 2x. Como posso implementar uma rotina para salvar os 2 detalhes uma vês só?


  1. <?php
  2. /**
  3.  * TabelaVendasForm Master/Detail
  4.  * @author  <your name here>
  5.  */
  6. class TabelaVendasForm extends TPage
  7. {
  8.     protected $form// form
  9.     protected $detail_list;
  10.     
  11.     /**
  12.      * Page constructor
  13.      */
  14.     public function __construct()
  15.     {
  16.         parent::__construct();
  17.         
  18.         // creates the form
  19.         $this->form = new BootstrapFormBuilder('form_TabelaVendas');
  20.         $this->form->setFormTitle('Dados Principais');
  21.         
  22.         // master fields
  23.         $id = new TEntry('id');
  24.         $cadastro_id = new TDBUniqueSearch('cadastro_id''projeto''Cadastro''id''nome');
  25.         $data_venda = new TDate('data_venda');
  26.         $vendedor_id = new TDBUniqueSearch('vendedor_id''projeto''Cadastro''id''nome');
  27.         $centro_custo = new TCombo('centro_custo');
  28.         $tipo_venda = new TCombo('tipo_venda');
  29.         // detail fields - PRODUTOS
  30.         $detail_id = new THidden('detail_id');
  31.         $detail_tabela_produtos_id = new TDBUniqueSearch('detail_tabela_produtos_id''projeto''TabelaProdutos''id''nome');
  32.         $detail_qtd_produto = new TEntry('detail_qtd_produto');
  33.         $detail_valor_produto = new TEntry('detail_valor_produto');
  34.         $detail_desconto_produto = new TEntry('detail_desconto_produto');
  35.         
  36.         $centro_custo->addItems( ['Clínica' => 'Clínica''Piscina' => 'Piscina'] );
  37.         $tipo_venda->addItems( ['Venda Direta' => 'Venda Direta''Orçamento' => 'Orçamento'] );
  38.         
  39.         // detail fields - SERVIÇOS
  40.         $detail2_id = new THidden('detail2_id');
  41.         $detail2_tabela_servicos_id = new TDBUniqueSearch('detail2_tabela_servicos_id''projeto''TabelaServicos''id''nome');
  42.         $detail2_qtd_servico = new TEntry('detail2_qtd_servico');
  43.         $detail2_valor_servico = new TEntry('detail2_valor_servico');
  44.         $detail2_desconto_servico = new TEntry('detail2_desconto_servico');
  45.         if (!empty($id))
  46.         {
  47.             $id->setEditable(FALSE);
  48.         }
  49.         
  50.         // master fields - PRODUTOS
  51.         $this->form->addFields( [new TLabel('Id')], [$id] );
  52.         $this->form->addFields( [new TLabel('Cadastro Id')], [$cadastro_id] );
  53.         $this->form->addFields( [new TLabel('Data Venda')], [$data_venda] );
  54.         $this->form->addFields( [new TLabel('Vendedor Id')], [$vendedor_id] );
  55.         $this->form->addFields( [new TLabel('Centro Custo')], [$centro_custo] );
  56.         $this->form->addFields( [new TLabel('Tipo Venda')], [$tipo_venda] );
  57.         
  58.         // detail fields - PRODUTOS
  59.         $this->form->addContent( ['<h4>Produtos</h4><hr>'] );
  60.         $this->form->addFields( [$detail_id] );
  61.         
  62.         $this->form->addFields( [new TLabel('Tabela Produtos Id')], [$detail_tabela_produtos_id] );
  63.         $this->form->addFields( [new TLabel('Qtd Produto')], [$detail_qtd_produto],
  64.                                 [new TLabel('Valor Produto')], [$detail_valor_produto],
  65.                                 [new TLabel('Desconto Produto')], [$detail_desconto_produto] );
  66.         $add TButton::create('add', [$this'onSaveDetail'], 'Adicionar Produtos''fa:save');
  67.         $this->form->addFields( [], [$add] )->style 'background: whitesmoke; padding: 5px; margin: 1px;';
  68.         
  69.         $this->detail_list = new BootstrapDatagridWrapper(new TQuickGrid);
  70.         $this->detail_list->style "min-width: 700px; width:100%;margin-bottom: 10px";
  71.         $this->detail_list->setId('TabelaVendas_list');
  72.         
  73.         // items - PRODUTOS
  74.         $this->detail_list->addQuickColumn('Tabela Produtos Id''tabela_produtos_id''center'100);
  75.         $this->detail_list->addQuickColumn('Qtd Produto''qtd_produto''center'100);
  76.         $this->detail_list->addQuickColumn('Valor Produto''valor_produto''center'100);
  77.         $this->detail_list->addQuickColumn('Desconto Produto''desconto_produto''center'100);
  78.         $st $this->detail_list->addQuickColumn('Subtotal''={qtd_produto} * ({valor_produto} - {desconto_produto})''right'100);
  79.         
  80.         $format_value = function($value){
  81.             if (is_numeric($value))
  82.             {
  83.                 return 'R$ ' number_format($value2",""."); 
  84.             }
  85.         };
  86.         
  87.         $st->setTransformer($format_value);
  88.         
  89.         $st->setTotalFunction( function($values){
  90.             return array_sum( (array) $values );
  91.         });
  92.         // detail actions - PRODUTOS
  93.         $this->detail_list->addQuickAction'Edit',   new TDataGridAction([$this'onEditDetail']),   'id''fa:edit blue');
  94.         $this->detail_list->addQuickAction'Delete', new TDataGridAction([$this'onDeleteDetail']), 'id''fa:trash red');
  95.         $this->detail_list->createModel();
  96.         $panel = new TPanelGroup;
  97.         $panel->add($this->detail_list);
  98.         $panel->getBody()->style 'overflow-x:auto';
  99.         $this->form->addContent( [$panel] );
  100.         
  101.         
  102.         
  103.         
  104.         
  105.         
  106.         // detail fields - SERVIÇOS
  107.         $this->form->addContent( ['<h4>Serviços</h4><hr>'] );
  108.         $this->form->addFields( [$detail2_id] );
  109.         
  110.         $this->form->addFields( [new TLabel('Tabela Servicos Id')], [$detail2_tabela_servicos_id] );
  111.         $this->form->addFields( [new TLabel('Qtd Servico')], [$detail2_qtd_servico],
  112.                                 [new TLabel('Valor Servico')], [$detail2_valor_servico],
  113.                                 [new TLabel('Desconto Servico')], [$detail2_desconto_servico] );
  114.         $add2 TButton::create('add2', [$this'onSaveDetail2'], 'Adicionar Serviços''fa:save');
  115.         $this->form->addFields( [], [$add2] )->style 'background: whitesmoke; padding: 5px; margin: 1px;';
  116.         
  117.         $this->detail2_list = new BootstrapDatagridWrapper(new TQuickGrid);
  118.         $this->detail2_list->style "min-width: 700px; width:100%;margin-bottom: 10px";
  119.         $this->detail2_list->setId('TabelaVendas_list2');
  120.         
  121.         // items - SERVIÇOS
  122.         $this->detail2_list->addQuickColumn('Tabela Servicos Id''tabela_servicos_id''left'100);
  123.         $this->detail2_list->addQuickColumn('Qtd Servico''qtd_servico''left'100);
  124.         $this->detail2_list->addQuickColumn('Valor Servico''valor_servico''left'100);
  125.         $this->detail2_list->addQuickColumn('Desconto Servico''desconto_servico''left'100);
  126.         $st2 $this->detail2_list->addQuickColumn('Subtotal''={qtd_servico} * ({valor_servico} - {desconto_servico})''right'100);
  127.         
  128.         $format_value = function($value){
  129.             if (is_numeric($value))
  130.             {
  131.                 return 'R$ ' number_format($value2",""."); 
  132.             }
  133.         };
  134.         
  135.         $st2->setTransformer($format_value);
  136.         
  137.         $st2->setTotalFunction( function($values){
  138.             return array_sum( (array) $values );
  139.         });
  140.         // detail actions - SERVIÇOS
  141.         $this->detail2_list->addQuickAction'Edit',   new TDataGridAction([$this'onEditDetail2']),   'id''fa:edit blue');
  142.         $this->detail2_list->addQuickAction'Delete', new TDataGridAction([$this'onDeleteDetail2']), 'id''fa:trash red');
  143.         $this->detail2_list->createModel();
  144.         
  145.         $panel = new TPanelGroup;
  146.         $panel->add($this->detail2_list);
  147.         $panel->getBody()->style 'overflow-x:auto';
  148.         $this->form->addContent( [$panel] );
  149.         
  150.         
  151.         // actions - PRODUTO
  152.         $btn $this->form->addAction_t('Save'),  new TAction([$this'onSave']), 'fa:save');
  153.         $btn->class 'btn btn-sm btn-primary';
  154.         $this->form->addAction_t('Clear'), new TAction([$this'onClear']), 'fa:eraser red');
  155.         
  156.         // actions - SERVIÇOS
  157.         /*$btn2 = $this->form->addAction( _t('Save2'),  new TAction([$this, 'onSave']), 'fa:save');
  158.         $btn2->class = 'btn btn-sm btn-primary';
  159.         $this->form->addAction( _t('Clear2'), new TAction([$this, 'onClear2']), 'fa:eraser red');*/
  160.         
  161.         
  162.         
  163.         
  164.         
  165.         
  166.         
  167.         
  168.         
  169.         
  170.         // create the page container
  171.         $container = new TVBox;
  172.         $container->style 'width: 90%';
  173.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  174.         $container->add($this->form);
  175.         parent::add($container);
  176.     }
  177.     
  178.     
  179.     public function onClear($param)
  180.     {
  181.         $this->form->clear(TRUE);
  182.         TSession::setValue(__CLASS__.'_items', array());
  183.         TSession::setValue(__CLASS__.'_items2', array());
  184.         $this->onReload2$param );
  185.         $this->onReload$param );
  186.         
  187.     }    
  188.     public function onSaveDetail$param )
  189.     {
  190.         try
  191.         {
  192.             TTransaction::open('projeto');
  193.             $data $this->form->getData();
  194.             
  195.             /** validation sample
  196.             if (empty($data->fieldX))
  197.             {
  198.                 throw new Exception('The field fieldX is required');
  199.             }
  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 ]['tabela_produtos_id'] = $data->detail_tabela_produtos_id;
  208.             $items$key ]['qtd_produto'] = $data->detail_qtd_produto;
  209.             $items$key ]['valor_produto'] = $data->detail_valor_produto;
  210.             $items$key ]['desconto_produto'] = $data->detail_desconto_produto;
  211.             
  212.             TSession::setValue(__CLASS__.'_items'$items);
  213.             
  214.             // clear detail form fields
  215.             $data->detail_id '';
  216.             $data->detail_tabela_produtos_id '';
  217.             $data->detail_qtd_produto '';
  218.             $data->detail_valor_produto '';
  219.             $data->detail_desconto_produto '';
  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.     public function onSaveDetail2$param )
  233.     {
  234.         try
  235.         {
  236.             TTransaction::open('projeto');
  237.             $data $this->form->getData();
  238.             
  239.             /** validation sample
  240.             if (empty($data->fieldX))
  241.             {
  242.                 throw new Exception('The field fieldX is required');
  243.             }
  244.             **/
  245.             
  246.             $items2 TSession::getValue(__CLASS__.'_items2');
  247.             $key = empty($data->detail2_id) ? 'X'.mt_rand(10000000001999999999) : $data->detail2_id;
  248.             
  249.             $items2$key ] = array();
  250.             $items2$key ]['id'] = $key;
  251.             $items2$key ]['tabela_servicos_id'] = $data->detail2_tabela_servicos_id;
  252.             $items2$key ]['qtd_servico'] = $data->detail2_qtd_servico;
  253.             $items2$key ]['valor_servico'] = $data->detail2_valor_servico;
  254.             $items2$key ]['desconto_servico'] = $data->detail2_desconto_servico;
  255.             
  256.             TSession::setValue(__CLASS__.'_items2'$items2);
  257.             
  258.             // clear detail form fields
  259.             $data->detail2_id '';
  260.             $data->detail2_tabela_servicos_id '';
  261.             $data->detail2_qtd_servico '';
  262.             $data->detail2_valor_servico '';
  263.             $data->detail2_desconto_servico '';
  264.             
  265.             TTransaction::close();
  266.             $this->form->setData($data);
  267.             
  268.             $this->onReload2$param ); // reload the items
  269.         }
  270.         catch (Exception $e)
  271.         {
  272.             $this->form->setData$this->form->getData());
  273.             new TMessage('error'$e->getMessage());
  274.         }
  275.     }
  276.     
  277.     public static function onEditDetail$param )
  278.     {
  279.         // read session items
  280.         $items TSession::getValue(__CLASS__.'_items');
  281.         
  282.         // get the session item
  283.         $item $items$param['key'] ];
  284.         
  285.         $data = new stdClass;
  286.         $data->detail_id $item['id'];
  287.         $data->detail_tabela_produtos_id $item['tabela_produtos_id'];
  288.         $data->detail_qtd_produto $item['qtd_produto'];
  289.         $data->detail_valor_produto $item['valor_produto'];
  290.         $data->detail_desconto_produto $item['desconto_produto'];
  291.         
  292.         // fill detail fields
  293.         TForm::sendData'form_TabelaVendas'$data );
  294.     }
  295.     public static function onEditDetail2$param )
  296.     {
  297.         // read session items
  298.         $items2 TSession::getValue(__CLASS__.'_items2');
  299.         
  300.         // get the session item
  301.         $item2 $items2$param['key'] ];
  302.         
  303.         $data = new stdClass;
  304.         $data->detail2_id $item2['id'];
  305.         $data->detail2_tabela_servicos_id $item2['tabela_servicos_id'];
  306.         $data->detail2_qtd_servico $item2['qtd_servico'];
  307.         $data->detail2_valor_servico $item2['valor_servico'];
  308.         $data->detail2_desconto_servico $item2['desconto_servico'];
  309.         
  310.         // fill detail fields
  311.         TForm::sendData'form_TabelaVendas'$data );
  312.     }
  313.     
  314.  
  315.     public static function onDeleteDetail$param )
  316.     {
  317.         // reset items
  318.         $data = new stdClass;
  319.             $data->detail_tabela_produtos_id '';
  320.             $data->detail_qtd_produto '';
  321.             $data->detail_valor_produto '';
  322.             $data->detail_desconto_produto '';
  323.         
  324.         // clear form data
  325.         TForm::sendData('form_TabelaVendas'$data );
  326.         
  327.         // read session items
  328.         $items TSession::getValue(__CLASS__.'_items');
  329.         
  330.         // get detail id
  331.         $detail_id $param['key'];
  332.         
  333.         // delete the item from session
  334.         unset($items$detail_id ] );
  335.         
  336.         // rewrite session items
  337.         TSession::setValue(__CLASS__.'_items'$items);
  338.         
  339.         // delete item from screen
  340.         TScript::create("ttable_remove_row_by_id('TabelaVendas_list', '{$detail_id}')");
  341.     }
  342.     public static function onDeleteDetail2$param )
  343.     {
  344.         // reset items
  345.         $data = new stdClass;
  346.             $data->detail2_tabela_servicos_id '';
  347.             $data->detail2_qtd_servico '';
  348.             $data->detail2_valor_servico '';
  349.             $data->detail2_desconto_servico '';
  350.         
  351.         // clear form data
  352.         TForm::sendData('form_TabelaVendas'$data );
  353.         
  354.         // read session items
  355.         $items2 TSession::getValue(__CLASS__.'_items2');
  356.         
  357.         // get detail id
  358.         $detail2_id $param['key'];
  359.         
  360.         // delete the item from session
  361.         unset($items2$detail2_id ] );
  362.         
  363.         // rewrite session items
  364.         TSession::setValue(__CLASS__.'_items2'$items2);
  365.         
  366.         // delete item from screen
  367.         TScript::create("ttable_remove_row_by_id('TabelaVendas_list2', '{$detail2_id}')");
  368.     }
  369.     
  370.   
  371.     public function onReload($param)
  372.     {
  373.         // read session items
  374.         $items TSession::getValue(__CLASS__.'_items');
  375.         
  376.         $this->detail_list->clear(); // clear detail list
  377.         
  378.         if ($items)
  379.         {
  380.             foreach ($items as $list_item)
  381.             {
  382.                 $item = (object) $list_item;
  383.                 
  384.                 $row $this->detail_list->addItem$item );
  385.                 $row->id $list_item['id'];
  386.             }
  387.         }
  388.         
  389.         $this->loaded TRUE;
  390.     }
  391.     public function onReload2($param)
  392.     {
  393.         // read session items
  394.         $items2 TSession::getValue(__CLASS__.'_items2');
  395.         
  396.         $this->detail2_list->clear(); // clear detail list
  397.         
  398.         if ($items2)
  399.         {
  400.             foreach ($items2 as $list_item2)
  401.             {
  402.                 $item2 = (object) $list_item2;
  403.                 
  404.                 $row $this->detail2_list->addItem$item2 );
  405.                 $row->id $list_item2['id'];
  406.             }
  407.         }
  408.         
  409.         $this->loaded TRUE;
  410.     }
  411.     
  412.   
  413.     public function onEdit($param)
  414.     {
  415.         try
  416.         {
  417.             TTransaction::open('projeto');
  418.             
  419.             if (isset($param['key']))
  420.             {
  421.                 $key $param['key'];
  422.                 
  423.                 $object = new TabelaVendas($key);
  424.                 $items  TabelaVendasProdutos::where('tabela_vendas_id''='$key)->load();
  425.                 
  426.                 $session_items = array();
  427.                 foreach( $items as $item )
  428.                 {
  429.                     $item_key $item->id;
  430.                     $session_items[$item_key] = $item->toArray();
  431.                     $session_items[$item_key]['id'] = $item->id;
  432.                     $session_items[$item_key]['tabela_produtos_id'] = $item->tabela_produtos_id;
  433.                     $session_items[$item_key]['qtd_produto'] = $item->qtd_produto;
  434.                     $session_items[$item_key]['valor_produto'] = $item->valor_produto;
  435.                     $session_items[$item_key]['desconto_produto'] = $item->desconto_produto;
  436.                 }
  437.                 TSession::setValue(__CLASS__.'_items'$session_items);
  438.                 
  439.                 $this->form->setData($object); // fill the form with the active record data
  440.                 $this->onReload$param ); // reload items list
  441.                 TTransaction::close(); // close transaction
  442.             }
  443.             else
  444.             {
  445.                 $this->form->clear(TRUE);
  446.                 TSession::setValue(__CLASS__.'_items'null);
  447.                 $this->onReload$param );
  448.             }
  449.         }
  450.         catch (Exception $e// in case of exception
  451.         {
  452.             new TMessage('error'$e->getMessage());
  453.             TTransaction::rollback();
  454.         }
  455.     }
  456.     public function onEdit2($param)
  457.     {
  458.         try
  459.         {
  460.             TTransaction::open('projeto');
  461.             
  462.             if (isset($param['key']))
  463.             {
  464.                 $key $param['key'];
  465.                 
  466.                 $object = new TabelaVendas($key);
  467.                 $items2  TabelaVendasServicos::where('tabela_vendas_id''='$key)->load();
  468.                 
  469.                 $session_items = array();
  470.                 foreach( $items2 as $item2 )
  471.                 {
  472.                     $item_key2 $item2->id;
  473.                     $session_items[$item_key2] = $item2->toArray();
  474.                     $session_items[$item_key2]['id'] = $item2->id;
  475.                     $session_items[$item_key2]['tabela_servicos_id'] = $item2->tabela_servicos_id;
  476.                     $session_items[$item_key2]['qtd_servico'] = $item2->qtd_servico;
  477.                     $session_items[$item_key2]['valor_servico'] = $item2->valor_servico;
  478.                     $session_items[$item_key2]['desconto_servico'] = $item2->desconto_servico;
  479.                 }
  480.                 TSession::setValue(__CLASS__.'_items2'$session_items2);
  481.                 
  482.                 $this->form->setData($object); // fill the form with the active record data
  483.                 $this->onReload2$param ); // reload items list
  484.                 TTransaction::close(); // close transaction
  485.             }
  486.             else
  487.             {
  488.                 $this->form->clear(TRUE);
  489.                 TSession::setValue(__CLASS__.'_items2'null);
  490.                 $this->onReload2$param2 );
  491.             }
  492.         }
  493.         catch (Exception $e// in case of exception
  494.         {
  495.             new TMessage('error'$e->getMessage());
  496.             TTransaction::rollback();
  497.         }
  498.     }
  499.     
  500.    
  501.     public function onSave()
  502.     {
  503.         try
  504.         {
  505.             // open a transaction with database
  506.             TTransaction::open('projeto');
  507.             
  508.             $data $this->form->getData();
  509.             $master = new TabelaVendas;
  510.             $master->fromArray( (array) $data);
  511.             $this->form->validate(); // form validation
  512.             
  513.             $master->store(); // save master object
  514.             // delete details
  515.             $old_items TabelaVendasProdutos::where('tabela_vendas_id''='$master->id)->load();
  516.             
  517.             $keep_items = array();
  518.             
  519.             // get session items
  520.             $items TSession::getValue(__CLASS__.'_items');
  521.             
  522.             if( $items )
  523.             {
  524.                 foreach( $items as $item )
  525.                 {
  526.                     if (substr($item['id'],0,1) == 'X' // new record
  527.                     {
  528.                         $detail = new TabelaVendasProdutos;
  529.                     }
  530.                     else
  531.                     {
  532.                         $detail TabelaVendasProdutos::find($item['id']);
  533.                     }
  534.                     $detail->tabela_produtos_id  $item['tabela_produtos_id'];
  535.                     $detail->qtd_produto  $item['qtd_produto'];
  536.                     $detail->valor_produto  $item['valor_produto'];
  537.                     $detail->desconto_produto  $item['desconto_produto'];
  538.                     $detail->tabela_vendas_id $master->id;
  539.                     $detail->store();
  540.                     
  541.                     $keep_items[] = $detail->id;
  542.                 }
  543.             }
  544.             
  545.             if ($old_items)
  546.             {
  547.                 foreach ($old_items as $old_item)
  548.                 {
  549.                     if (!in_array$old_item->id$keep_items))
  550.                     {
  551.                         $old_item->delete();
  552.                     }
  553.                 }
  554.             }
  555.             TTransaction::close(); // close the transaction
  556.             
  557.             // reload form and session items
  558.             $this->onEdit(array('key'=>$master->id));
  559.             
  560.             //new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  561.         }
  562.         catch (Exception $e// in case of exception
  563.         {
  564.             new TMessage('error'$e->getMessage());
  565.             $this->form->setData$this->form->getData() ); // keep form data
  566.             TTransaction::rollback();
  567.         }
  568.         
  569.         
  570.         try
  571.         {
  572.             // open a transaction with database
  573.             TTransaction::open('projeto');
  574.             
  575.             $data $this->form->getData();
  576.             $master = new TabelaVendas;
  577.             $master->fromArray( (array) $data);
  578.             $this->form->validate(); // form validation
  579.             
  580.             $master->store(); // save master object
  581.             // delete details
  582.             $old_items2 TabelaVendasServicos::where('tabela_vendas_id''='$master->id)->load();
  583.             
  584.             $keep_items2 = array();
  585.             
  586.             // get session items
  587.             $items2 TSession::getValue(__CLASS__.'_items2');
  588.             
  589.             if( $items2 )
  590.             {
  591.                 foreach( $items2 as $item2 )
  592.                 {
  593.                     if (substr($item2['id'],0,1) == 'X' // new record
  594.                     {
  595.                         $detail2 = new TabelaVendasServicos;
  596.                     }
  597.                     else
  598.                     {
  599.                         $detail2 TabelaVendasServicos::find($item2['id']);
  600.                     }
  601.                     $detail2->tabela_servicos_id  $item2['tabela_servicos_id'];
  602.                     $detail2->qtd_servico  $item2['qtd_servico'];
  603.                     $detail2->valor_servico  $item2['valor_servico'];
  604.                     $detail2->desconto_servico  $item2['desconto_servico'];
  605.                     $detail2->tabela_vendas_id $master2->id;
  606.                     $detail2->store();
  607.                     
  608.                     $keep_items[] = $detail2->id;
  609.                 }
  610.             }
  611.             
  612.             if ($old_items2)
  613.             {
  614.                 foreach ($old_items2 as $old_item2)
  615.                 {
  616.                     if (!in_array$old_item2->id$keep_items))
  617.                     {
  618.                         $old_item2->delete();
  619.                     }
  620.                 }
  621.             }
  622.             TTransaction::close(); // close the transaction
  623.             
  624.             // reload form and session items
  625.             $this->onEdit(array('key'=>$master->id));
  626.             
  627.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  628.         }
  629.         catch (Exception $e// in case of exception
  630.         {
  631.             new TMessage('error'$e->getMessage());
  632.             $this->form->setData$this->form->getData() ); // keep form data
  633.             TTransaction::rollback();
  634.         }
  635.     
  636.     }
  637.     public function show()
  638.     {
  639.         // check if the datagrid is already loaded
  640.         if (!$this->loaded )
  641.         {
  642.             $this->onReloadfunc_get_arg(0) );
  643.             $this->onReload2func_get_arg(0) );
  644.         }
  645.        
  646.         parent::show();
  647.     }
  648.     
  649. }?>

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)


FC

Da um var_dump($master) antes do store para ver como os dados estão vindo , agora eu fiquei na duvida se está duplicando o form master ou o detail mas ambos talvez voce resolva com o php.net/manual/pt_BR/function.array-unique.php antes de mandar salvar.
RA

Felipe, desde já agradeço sua ajuda. Achei em outro post (https://www.adianti.com.br/forum/pt/view_4734) uma sacada para poder salvar 2 detalhes, está salvando os 2 detalhes e editando normal. Mas me esbarrei em uma situação: quando edito ele não exclui o antigo, ele mantem e salva um novo. O que pode ser?

  1. <?php
  2. public function onSave()
  3.     {
  4.         try
  5.         {
  6.             // open a transaction with database
  7.             TTransaction::open('projeto');
  8.             
  9.             $data $this->form->getData();
  10.             $master = new TabelaVendas;
  11.             $master->fromArray( (array) $data);
  12.             $this->form->validate(); // form validation
  13.             
  14.             $master->store(); // save master object
  15.             
  16.             // delete details
  17.             $old_items TabelaVendasProdutos::where('tabela_vendas_id''='$master->id)->load();
  18.                        
  19.             $keep_items = array();
  20.                       
  21.             // get session items
  22.             $items TSession::getValue(__CLASS__.'_items');
  23.                        
  24.             if( $items )
  25.             {
  26.                 foreach( $items as $item )
  27.                 {
  28.                     if (substr($item['id'],0,1) == 'X' // new record
  29.                     {
  30.                         $detail = new TabelaVendasProdutos;
  31.                     }
  32.                     else
  33.                     {
  34.                         $detail TabelaVendasProdutos::find($item['id']);
  35.                     }
  36.                     $detail->tabela_produtos_id  $item['tabela_produtos_id'];
  37.                     $detail->qtd_produto  $item['qtd_produto'];
  38.                     $detail->valor_produto  $item['valor_produto'];
  39.                     $detail->desconto_produto  $item['desconto_produto'];
  40.                     $detail->tabela_vendas_id $master->id;
  41.                     $detail->valor_total_produto = ($detail->qtd_produto * ($detail->valor_produto $detail->desconto_produto));
  42.                     $detail->store();
  43.                     
  44.                     $keep_items[] = $detail->id;
  45.                 }
  46.             }
  47.             
  48.             if ($old_items)
  49.             {
  50.                 foreach ($old_items as $old_item)
  51.                 {
  52.                     if (!in_array$old_item->id$keep_items))
  53.                     {
  54.                         $old_item->delete();
  55.                     }
  56.                 }
  57.             }
  58.     
  59.             TTransaction::close(); // close the transaction   
  60.       
  61.             // reload form and session items
  62.             $this->onEdit(array('key'=>$master->id));
  63.             
  64.             
  65.             // open a transaction with database
  66.             TTransaction::open('projeto');
  67.             
  68.             $data $this->form->getData();
  69.             $master2 = new TabelaVendas($master->id);
  70.             $master2->fromArray( (array) $data);
  71.             $this->form->validate(); // form validation
  72.             
  73.             $master2->store(); // save master object
  74.             
  75.             // delete details
  76.             $old_items2 TabelaVendasServicos::where('tabela_vendas_id''='$master2->id)->load();
  77.             
  78.             $keep_items2 = array();
  79.             
  80.             // get session items
  81.             $items2 TSession::getValue(__CLASS__.'_items2');
  82.             
  83.             if( $items2 )
  84.             {
  85.                 foreach( $items2 as $item2 )
  86.                 {
  87.                     if (substr($item2['id'],0,1) == 'X' // new record
  88.                     {
  89.                         $detail2 = new TabelaVendasServicos;
  90.                     }
  91.                     else
  92.                     {
  93.                         $detail2 TabelaVendasServicos::find($item2['id']);
  94.                     }
  95.                     $detail2->tabela_servicos_id  $item2['tabela_servicos_id'];
  96.                     $detail2->qtd_servico  $item2['qtd_servico'];
  97.                     $detail2->valor_servico  $item2['valor_servico'];
  98.                     $detail2->desconto_servico  $item2['desconto_servico'];
  99.                     $detail2->tabela_vendas_id $master2->id;
  100.                     $detail2->valor_total_servico = ($detail2->qtd_servico * ($detail2->valor_servico $detail2->desconto_servico));
  101.                     $detail2->store();
  102.                     
  103.                     $master2->valor_total += ($detail->valor_total_produto $detail2->valor_total_servico);
  104.                     $keep_items2[] = $detail2->id;
  105.                 }
  106.                 
  107.                 $master2->store();
  108.             }
  109.             
  110.             if ($old_items2)
  111.             {
  112.                 foreach ($old_items2 as $old_item2)
  113.                 {
  114.                     if (!in_array$old_item2->id$keep_items2))
  115.                     {
  116.                         $old_item2->delete();
  117.                     }
  118.                 }
  119.             }
  120.             TTransaction::close(); // close the transaction
  121.             
  122.             // reload form and session items
  123.             $this->onEdit2(array('key'=>$master->id));
  124.             
  125.             
  126.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  127.         }
  128.         catch (Exception $e// in case of exception
  129.         {
  130.             new TMessage('error'$e->getMessage());
  131.             $this->form->setData$this->form->getData() ); // keep form data
  132.             TTransaction::rollback();
  133.         }     
  134.     }?>
RA

Reformulando:

Mas me esbarrei em uma situação: quando edito ele não exclui o antigo MESTRE, ele mantem o MESTRE e salva um novo MESTRE. O que pode ser?
FC

Em algum lugar ele está dando o store com o id vazio por isso cria um novo registro.
RA

Consegui Felipe, achei o mesmo problema em outro tópico e o Samuel me ajudou. Obrigado.