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


Código formulário detalhe:

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

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.