Lançado Adianti Framework 8.1!
Clique aqui para saber mais
Master-Detail III No formulário mestre-detalhe, tenho um método static onProductChange no formulário de detalhes, preciso pegar um valor de uma variável no formulário mestre. Como faço? Já tentei de várias formas com TFORM::getData('form_Saida'); e dá um erro de formulário não encontrado; Segue o código abaixo Formulário Mestre: ...
CJ
Master-Detail III  
No formulário mestre-detalhe, tenho um método static onProductChange no formulário de detalhes, preciso pegar um valor de uma variável no formulário mestre. Como faço? Já tentei de várias formas com TFORM::getData('form_Saida'); e dá um erro de formulário não encontrado;

Segue o código abaixo Formulário Mestre:

  1. <?php
  2. class SaidaForm extends TPage
  3. {
  4.     protected $form// form
  5.     
  6.     function __construct()
  7.     {
  8.         parent::__construct();
  9.                
  10.         // creates the form
  11.         $this->form   = new BootstrapFormBuilder('form_Saida');
  12.         $this->form->setFormTitle'Saída' );
  13.         
  14.         // master fields
  15.         $id               = new TEntry('id');
  16.         $data_atual       = new TDate('data_atual');
  17.         $cliente_id       = new TDBUniqueSearch('cliente_id''sisestoque''Cliente''id''nome');
  18.         $almoxarifado_id  = new TDBCombo('almoxarifado_id''sisestoque''Almoxarifado''id''nome');        
  19.         
  20.         $id->setSize('15%');
  21.         $cliente_id->setSize('100%');
  22.         $data_atual->setSize('100%');
  23.         $almoxarifado_id->setSize('100%');
  24.         
  25.         $id->setEditable(false);
  26.         $data_atual->setValue(date("d/m/Y"));
  27.         $almoxarifado_id->enableSearch();
  28.         $cliente_id->setMinLength(3);
  29.         
  30.         $data_atual->setEditable(false);        
  31.                 
  32.         $data_atual->setMask('dd/mm/yyyy'false);
  33.         $data_atual->setDatabaseMask('yyyy-mm-dd');
  34.         
  35.         $data_atual->addValidation('Data', new TRequiredValidator);
  36.         $almoxarifado_id->addValidation('Almoxarifado', new TRequiredValidator);
  37.         $cliente_id->addValidation('Cliente', new TRequiredValidator);
  38.         
  39.         $this->form->addFields( [ new TLabel('ID') ], [ $id ] );
  40.         $this->form->addFields( [ $label_cli = new TLabel('Cliente') ], [ $cliente_id ]);        
  41.         $this->form->addFields( [ $label_almox = new TLabel('Almoxarifado') ], [ $almoxarifado_id ] , [ $label_data = new TLabel('Data') ], [ $data_atual ]  );
  42.         $label_data->setFontColor('#FF0000');
  43.         $label_cli->setFontColor('#FF0000');
  44.         $label_almox->setFontColor('#FF0000');
  45.         
  46.         $btn $this->form->addAction_t('Save'),  new TAction(array($this'onSave')),  'fa:floppy-o');
  47.         $btn->class 'btn btn-sm btn-success';
  48.         $this->form->addAction_t('Clear'), new TAction(array($this'onClear')), 'fa:eraser red');
  49.         
  50.         // place where the products page will be inserted
  51.         $details_area = new TElement('div');
  52.         $details_area->id 'detalhesai_area';
  53.         
  54.         $this->form->addContent( [TElement::tag('h4''Ítens')] );
  55.         $this->form->addContent( [$details_area] );
  56.         // Load SaleDetailForm into details_area
  57.         AdiantiCoreApplication::loadPage('SaidaDetalheForm''onReload', ['register_state'=>'false']);
  58.         
  59.         // create the page container
  60.         $container = new TVBox;
  61.         $container->add(new TXMLBreadCrumb('menu.xml'__CLASS__));
  62.         $container->add($this->form);
  63.         
  64.         parent::add($container);
  65.     }
  66.     
  67.     /**
  68.      * Pre load some data
  69.      */
  70.     public function onLoad($param)
  71.     {
  72.     }
  73.           
  74.     /**
  75.      * Clear form
  76.      * @param $param URL parameters
  77.      */
  78.     function onClear($param)
  79.     {
  80.         $this->form->clear(TRUE);
  81.         TSession::setValue('saida_items', array());
  82.     }
  83.     
  84.     /**
  85.      * method onEdit()
  86.      * Executed whenever the user clicks at the edit button da datagrid
  87.      */
  88.     function onEdit($param)
  89.     {
  90.         try
  91.         {
  92.             TTransaction::open('sisestoque');
  93.             
  94.             if (isset($param['id']))
  95.             {
  96.                 $key $param['id'];
  97.                 
  98.                 $object = new Saida($key);
  99.                 $sale_items $object->getEntradaItems();
  100.                 
  101.                 $session_items = array();
  102.                 foreach( $sale_items as $item )
  103.                 {
  104.                     $session_items[$item->product_id] = $item->toArray();
  105.                     $session_items[$item->product_id]['material_id'] = $item->material_id;
  106.                     $session_items[$item->product_id]['product_name'] = $item->material->nome;
  107.                     $session_items[$item->product_id]['quant'] = $item->quant;
  108.                 }
  109.                 TSession::setValue('saida_items'$session_items);
  110.                 
  111.                 $this->form->setData($object); // fill the form with the active record data
  112.                 
  113.                 TTransaction::close(); // close transaction
  114.             }
  115.             else
  116.             {
  117.                 $this->form->clear();
  118.                 TSession::setValue('saida_items'null);
  119.             }
  120.         }
  121.         catch (Exception $e// in case of exception
  122.         {
  123.             new TMessage('error'$e->getMessage());
  124.             TTransaction::rollback();
  125.         }
  126.     }
  127.     
  128.     public function tofloat($num) {
  129.         $dotPos strrpos($num'.');
  130.         $commaPos strrpos($num',');
  131.         $sep = (($dotPos $commaPos) && $dotPos) ? $dotPos 
  132.             ((($commaPos $dotPos) && $commaPos) ? $commaPos false);
  133.        
  134.         if (!$sep) {
  135.             return floatval(preg_replace("/[^0-9]/"""$num));
  136.         } 
  137.     
  138.         return floatval(
  139.             preg_replace("/[^0-9]/"""substr($num0$sep)) . '.' .
  140.             preg_replace("/[^0-9]/"""substr($num$sep+1strlen($num)))
  141.         );
  142.     }
  143.     
  144.     function onLimpa()
  145.     {
  146.         $this->form->clear();            
  147.         TSession::setValue('saida_items', array());
  148.         $data = new stdClass;
  149.         $this->form->setData($data);
  150.     }
  151.     
  152.     function onPrintNF$param )
  153.     {                         
  154.         $action1 = new TAction( array($this'onGenerate') );        
  155.         $action1->setParameter('dados'$param['dados']);
  156.         
  157.         $action2 = new TAction( array($this'onLimpa') );
  158.         
  159.         new TQuestion('Deseja imprimir ?'$action1$action2);
  160.     }
  161.     
  162.     function onGenerate$param )
  163.     {                   
  164.         try
  165.         {
  166.             TTransaction::open('sisestoque');
  167.             $criteria   = new TCriteria;            
  168.             $criteria->add(new TFilter('id''='$param['dados']));
  169.        
  170.             $ordem['order'] = 'id'
  171.             $ordem['direction'] = 'desc'
  172.             $criteria->setProperties($ordem); 
  173.                 
  174.             $repository = new TRepository('Saida');
  175.             $entradas $repository->load$criteria );
  176.             
  177.             if ($entradas)
  178.             {
  179.                 $designer = new TEntradaAV;                
  180.                 $designer->SetTitle('Saída de materiais');
  181.                 
  182.                 $designer->fromXml('app/reports/formRetrato.pdf.xml');
  183.                 $designer->Dados_Header('Saída de materiais');
  184.                 $designer->SetAutoPageBreak(true60); 
  185.                 $designer->generate();
  186.                                               
  187.                 $controle_quebra NULL;
  188.                 
  189.                 $contador 1;
  190.                 
  191.                 $designer->SetLineWidth(.4);
  192.                 $designer->SetY(142); 
  193.                 $designer->SetX(36); 
  194.                 
  195.                 foreach ($entradas as $entrada)
  196.                 {
  197.                     if (!isset($controle_quebra) OR $controle_quebra !== $entrada->id)
  198.                     {
  199.                         if (isset($controle_quebra))
  200.                         {                                                                                   
  201.                             $designer->generate();                            
  202.                             $designer->SetFont('Arial'''12);                                                                         
  203.                         }
  204.                         
  205.                         // CABEÇALHO NOTA FISCAL                        
  206.                         $designer->SetY(142); 
  207.                         $designer->SetX(36);
  208.                         $designer->SetFont('Arial','B',12);                   
  209.                         $designer->Cell(3820,'TIPO:'00,'L'true);
  210.                         $designer->SetFont('Arial','',12);
  211.                         $designer->Cell(5020,$entrada->tipo00,'L'true);
  212.                         $designer->SetFont('Arial','B',12);                   
  213.                         $designer->Cell(10520,'DATA ENTRADA:'00,'L'true);
  214.                         $designer->SetFont('Arial','',12);
  215.                         $designer->Cell(9020,TDate::date2br($entrada->data_atual), 01,'L'true);
  216.                         
  217.                         //CABEÇALHO DETALHES                        
  218.                         $designer->SetFont('Arial','B',10);
  219.                         $designer->SetX(38); 
  220.                         $designer->SetFillColor(200200200);            
  221.                         $designer->Cell(4822,'ITEM'10,'C'TRUE);
  222.                         $designer->Cell(5022,utf8_decode('CÓDIGO'), 10,'C'TRUE);                 
  223.                         $designer->Cell(30022,'MATERIAL'10,'L'TRUE);
  224.                         $designer->Cell(3022,'UND'10,'C'TRUE);
  225.                         $designer->Cell(9322utf8_decode('QUANTIDADE'), 11,'C'TRUE);
  226.                         $controle_quebra $entrada->id;
  227.                     }
  228.                                        
  229.                     $itens EntradaItens::where('entrada_id''='$entrada->id)->orderBy('entrada_id')->load();    
  230.                                                
  231.                     foreach ($itens as $item)
  232.                     {                                                                         
  233.                         $designer->SetFont('Arial'''10);
  234.                         $designer->SetX(38);  
  235.                         $designer->Cell4820$contador10'C');
  236.                         $designer->Cell5020utf8_decode($item->material->id), 10'R');                        
  237.                         $designer->Cell30020utf8_decode($item->material_nome), 10'L');
  238.                         $designer->Cell3020$item->material->und10'C');                        
  239.                         $designer->Cell9320number_format($item->quant2',''.'), 11'R');
  240.                         $contador $contador 1;
  241.                     }  
  242.                                                     
  243.                 }
  244.                     
  245.                 $file 'app/output/' .time(). 'entradaAV.pdf';
  246.             
  247.                 if (!file_exists($file) OR is_writable($file))
  248.                 {
  249.                     $designer->output($file);
  250.                     parent::openFile($file);
  251.                 }
  252.                 else
  253.                 {
  254.                     throw new Exception(_t('Permission denied') . ': ' $file);
  255.                 }
  256.                 
  257.                 new TMessage('info''Relatório gerado. Por favor habilite os popups do seu navegador');
  258.                  
  259.             }
  260.             else
  261.             {
  262.                 new TMessage('info''Não há dados para serem impressos !');
  263.             }            
  264.                         
  265.             TTransaction::close();
  266.         }
  267.         catch (Exception $e)
  268.         {
  269.             new TMessage('error'$e->getMessage());
  270.             TTransaction::rollback();
  271.         }        
  272.                                 
  273.         $this->onLimpa();
  274.     }
  275.     
  276.     function onSave()
  277.     {        
  278.         try
  279.         {
  280.             TTransaction::open('sisestoque');
  281.             
  282.             $sale $this->form->getData('Saida');
  283.             $this->form->validate(); // form validation
  284.             
  285.             $sale_items TSession::getValue('saida_items');
  286.                        
  287.             // get session items                      
  288.             if ( ! $sale_items)
  289.             {
  290.                 throw new Exception('Não há itens cadastrados');
  291.             }            
  292.             
  293.             if ( $sale_items )
  294.             {                              
  295.                 foreach( $sale_items as $sale_item )
  296.                 {
  297.                     $item               = new EntradaItens;
  298.                     $item->material_id  $sale_item['material_id'];
  299.                     $item->quant        $sale_item['quant'];
  300.                     
  301.                     $sale->addEntradaItem($item);
  302.                     
  303.                     // Atualiza Estoque
  304.                     $repo = new TRepository('Estoque');
  305.                     $criteria = new TCriteria;
  306.                     $criteria->add(new TFilter('material_id''='$item->material_id));
  307.                     $criteria->add(new TFilter('almoxarifado_id''='$sale->almoxarifado_id));
  308.                     $objects $repo->count($criteria);
  309.                     if ( $objects 
  310.                     {
  311.                         $update_repo = new TRepository('Estoque');
  312.                         $objs $update_repo->load($criteria);
  313.                         foreach ($objs as $obj)
  314.                         {
  315.                             $obj->estoque $obj->estoque $this->tofloat$item->quant );
  316.                             $obj->store();                                
  317.                         }
  318.                     }
  319.                     else
  320.                     {
  321.                         $estoque = new Estoque;
  322.                         $estoque->almoxarifado_id $sale->almoxarifado_id;
  323.                         $estoque->material_id $item->material_id;
  324.                         $estoque->estoque $estoque->estoque $this->tofloat$item->quant);
  325.                         $estoque->store();
  326.                     }
  327.                 }
  328.                 
  329.                 $sale->store(); // stores the object
  330.                 
  331.                 $action = new TAction( array($this'onPrintNF') );                                                   
  332.                 $action->setParameter('dados'$sale->id);
  333.                 
  334.                 new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'), $action);
  335.             }                       
  336.                       
  337.             TTransaction::close(); // close the transaction                                                                  
  338.         }
  339.         catch (Exception $e// in case of exception
  340.         {
  341.             new TMessage('error'$e->getMessage());
  342.             $this->form->setData$this->form->getData() ); // keep form data
  343.             TTransaction::rollback();
  344.         }
  345.     }
  346. }
  347. ?>


Código formulário detalhe:

  1. <?php
  2. class SaidaDetalheForm extends TPage
  3. {
  4.     protected $form;
  5.     protected $product_list;
  6.         
  7.     public function __construct()
  8.     {
  9.         parent::__construct();
  10.         
  11.         $this->adianti_target_container 'detalhesai_area';
  12.         
  13.         $this->form = new BootstrapFormBuilder('form_DetailsSai');
  14.         
  15.         // detail fields
  16.         $material_id   = new TDBUniqueSearch('material_id','sisestoque','Material','id','nome','nome');        
  17.         $quant         = new TEntry('quant');
  18.         $und           = new TEntry('und');
  19.         $estoque       = new TEntry('estoque');
  20.         
  21.         $material_id->addValidation'Material', new TRequiredValidator );
  22.         $quant->addValidation'Quantidade', new TRequiredValidator );
  23.         
  24.         $quant->setInputType('numeric');
  25.         $quant->setNumericMask(2',''.'true);
  26.         
  27.         $material_id->setSize('calc(100% - 140px)');
  28.         $material_id->setMinLength(3);        
  29.         $quant->setSize('100%');                
  30.         $estoque->setSize('100%');
  31.         $material_id->setChangeAction(new TAction(array($this,'onProductChange')));
  32.         
  33.         $und->setSize(140);
  34.         $und->setEditable(FALSE);
  35.         $estoque->setEditable(FALSE);
  36.         
  37.         $this->form->addFields( [$label_product = new TLabel('Material')], [$material_id$und]);
  38.         $this->form->addFields( [$label_quant = new TLabel('Quantidade')], [$quant], [ new TLabel('Estoque Atual')], [$estoque]);
  39.         
  40.         $label_product->setFontColor('#FF0000');
  41.         $label_quant->setFontColor('#FF0000');
  42.         
  43.         $add_action = new TAction(array($this'onProductAdd'));
  44.         $add_action->setParameter('register_state''false');
  45.         $btn1 $this->form->addAction'Adicionar'$add_action'fa:hand-o-down');
  46.         $btn1->class 'btn btn-sm btn-primary';
  47.         
  48.         $this->product_list = new BootstrapDatagridWrapper(new TQuickGrid);
  49.         $this->product_list->style 'margin-bottom:0px;';
  50.         $this->product_list->addQuickColumn('ID''material_id''left''10%');
  51.         $this->product_list->addQuickColumn('Material''product_name''left''65%');
  52.         $qt $this->product_list->addQuickColumn('Quantidade''quant''right''25%');
  53.         
  54.         $edit_action = new TDataGridAction([$this'onEdit']);
  55.         $delete_action = new TDataGridAction([$this'onDelete']);
  56.         $edit_action->setParameter('register_state''false');
  57.         $delete_action->setParameter('register_state''false');
  58.         $this->product_list->addQuickAction('Edit'$edit_action'material_id''fa:edit blue');
  59.         $this->product_list->addQuickAction('Delete'$delete_action'material_id''fa:trash red');
  60.         
  61.         $this->product_list->createModel();
  62.                 
  63.         $format_value_num = function($value) {
  64.             if (is_numeric($value)) {
  65.                 return number_format($value2',''.');
  66.             }
  67.             return $value;
  68.         };
  69.        
  70.         $qt->setTransformer$format_value_num );
  71.                
  72.         $panel TPanelGroup::pack(''$this->product_list);
  73.         $panel->style 'margin-bottom:0';
  74.         $vbox = new TVBox;
  75.         $vbox->style 'width: 100%';
  76.         $vbox->add$this->form );
  77.         $vbox->add$panel );
  78.         
  79.         parent::add($vbox);
  80.     }
  81.     /**
  82.      * On product change
  83.      */
  84.     static function onProductChange$params )
  85.     {
  86.         if( isset($params['material_id']) && $params['material_id'] )
  87.         {
  88.             try
  89.             {
  90.                 TTransaction::open('sisestoque');               
  91.                 
  92.                // PETGAR O VALOR DE $almoxarifado_id no form_Saida
  93.                 $dados TForm::getData('form_Saida');
  94.                 print_r($dados);
  95.                 
  96.                 $product = new Material($params['material_id']);
  97.                 $fill_data = new StdClass;
  98.                 $fill_data->und $product->und;
  99.                 TForm::sendData('form_Saida'$fill_data);
  100.                 TTransaction::close();
  101.             }
  102.             catch (Exception $e// in case of exception
  103.             {
  104.                 new TMessage('error'$e->getMessage());
  105.                 TTransaction::rollback();
  106.             }
  107.         }
  108.     }
  109.     
  110.     /**
  111.      * Add a product into item list
  112.      * @param $param URL parameters
  113.      */
  114.     public function onProductAdd$param )
  115.     {
  116.         try
  117.         {
  118.             TTransaction::open('sisestoque');
  119.             $data $this->form->getData();
  120.             
  121.             $this->form->validate();
  122.             $product = new Material($data->material_id);
  123.             
  124.             $sale_items TSession::getValue('saida_items');
  125.             $key = (int) $data->material_id;
  126.             $sale_items$key ] = array('material_id'       => $data->material_id,
  127.                                         'product_name'     => $product->nome,
  128.                                         'quant'   => $data->quant);                                                                                
  129.             
  130.             TSession::setValue('saida_items'$sale_items);
  131.             
  132.             // clear product form fields after add
  133.             $data->material_id '';
  134.             $data->product_name '';
  135.             $data->quant '';
  136.             TTransaction::close();
  137.             $this->form->setData($data);
  138.             
  139.             $this->onReload$param ); // reload the sale items
  140.         }
  141.         catch (Exception $e)
  142.         {
  143.             $this->form->setData$this->form->getData());
  144.             new TMessage('error'$e->getMessage());
  145.         }
  146.     }
  147.     
  148.     /**
  149.      * Edit a product from item list
  150.      * @param $param URL parameters
  151.      */
  152.     public function onEdit$param )
  153.     {
  154.         // read session items
  155.         $sale_items TSession::getValue('saida_items');
  156.         
  157.         // get the session item
  158.         $sale_item $sale_items[ (int) $param['material_id'] ];
  159.         
  160.         $data = new stdClass;
  161.         $data->material_id       $param['material_id'];
  162.         $data->product_name     $sale_item['product_name'];
  163.         $data->quant   $sale_item['quant'];
  164.         
  165.         // fill product fields
  166.         $this->form->setData$data );
  167.     
  168.         $this->onReload$param );
  169.     }
  170.     
  171.     /**
  172.      * Delete a product from item list
  173.      * @param $param URL parameters
  174.      */
  175.     public function onDelete$param )
  176.     {
  177.         // read session items
  178.         $sale_items TSession::getValue('saida_items');
  179.         
  180.         // delete the item from session
  181.         unset($sale_items[ (int) $param['material_id'] ] );
  182.         TSession::setValue('saida_items'$sale_items);
  183.         
  184.         // reload sale items
  185.         $this->onReload$param );
  186.     }
  187.     
  188.     /**
  189.      * Reload the products list
  190.      * @param $param URL parameters
  191.      */
  192.     public function onReload()
  193.     {
  194.         // read session items
  195.         $sale_items TSession::getValue('saida_items');
  196.         
  197.         $this->product_list->clear(); // clear product list
  198.         $data $this->form->getData();
  199.         
  200.         if ($sale_items)
  201.         {
  202.             foreach ($sale_items as $list_material_id => $list_product)
  203.             {
  204.                 $item = (object) $list_product;
  205.                 $this->product_list->addItem$item );
  206.             }
  207.         }
  208.         
  209.         $this->loaded TRUE;
  210.     }
  211.     
  212.     /**
  213.      * method show()
  214.      * Shows the page
  215.      */
  216.     public function show()
  217.     {
  218.         // check if the datagrid is already loaded
  219.         if (!$this->loaded )
  220.         {
  221.             $this->onReload();
  222.         }
  223.         parent::show();
  224.     }
  225. }
  226. ?>

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (1)


NR

Crie um campo hidden no form Detail para armazenar esse valor.

No formulário mestre atribua uma changeAction a combo de almoxarifado e faça essa action capturar o valor da combo e enviar ao hidden do formulário detail usando a função sendData.