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:
Código formulário detalhe:
Segue o código abaixo Formulário Mestre:
- <?php
- class SaidaForm extends TPage
- {
- protected $form; // form
- function __construct()
- {
- parent::__construct();
- // creates the form
- $this->form = new BootstrapFormBuilder('form_Saida');
- $this->form->setFormTitle( 'Saída' );
- // master fields
- $id = new TEntry('id');
- $data_atual = new TDate('data_atual');
- $cliente_id = new TDBUniqueSearch('cliente_id', 'sisestoque', 'Cliente', 'id', 'nome');
- $almoxarifado_id = new TDBCombo('almoxarifado_id', 'sisestoque', 'Almoxarifado', 'id', 'nome');
- $id->setSize('15%');
- $cliente_id->setSize('100%');
- $data_atual->setSize('100%');
- $almoxarifado_id->setSize('100%');
- $id->setEditable(false);
- $data_atual->setValue(date("d/m/Y"));
- $almoxarifado_id->enableSearch();
- $cliente_id->setMinLength(3);
- $data_atual->setEditable(false);
- $data_atual->setMask('dd/mm/yyyy', false);
- $data_atual->setDatabaseMask('yyyy-mm-dd');
- $data_atual->addValidation('Data', new TRequiredValidator);
- $almoxarifado_id->addValidation('Almoxarifado', new TRequiredValidator);
- $cliente_id->addValidation('Cliente', new TRequiredValidator);
- $this->form->addFields( [ new TLabel('ID') ], [ $id ] );
- $this->form->addFields( [ $label_cli = new TLabel('Cliente') ], [ $cliente_id ]);
- $this->form->addFields( [ $label_almox = new TLabel('Almoxarifado') ], [ $almoxarifado_id ] , [ $label_data = new TLabel('Data') ], [ $data_atual ] );
- $label_data->setFontColor('#FF0000');
- $label_cli->setFontColor('#FF0000');
- $label_almox->setFontColor('#FF0000');
- $btn = $this->form->addAction( _t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');
- $btn->class = 'btn btn-sm btn-success';
- $this->form->addAction( _t('Clear'), new TAction(array($this, 'onClear')), 'fa:eraser red');
- // place where the products page will be inserted
- $details_area = new TElement('div');
- $details_area->id = 'detalhesai_area';
- $this->form->addContent( [TElement::tag('h4', 'Ítens')] );
- $this->form->addContent( [$details_area] );
- // Load SaleDetailForm into details_area
- AdiantiCoreApplication::loadPage('SaidaDetalheForm', 'onReload', ['register_state'=>'false']);
- // create the page container
- $container = new TVBox;
- $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- parent::add($container);
- }
- /**
- * Pre load some data
- */
- public function onLoad($param)
- {
- }
- /**
- * Clear form
- * @param $param URL parameters
- */
- function onClear($param)
- {
- $this->form->clear(TRUE);
- TSession::setValue('saida_items', array());
- }
- /**
- * method onEdit()
- * Executed whenever the user clicks at the edit button da datagrid
- */
- function onEdit($param)
- {
- try
- {
- TTransaction::open('sisestoque');
- if (isset($param['id']))
- {
- $key = $param['id'];
- $object = new Saida($key);
- $sale_items = $object->getEntradaItems();
- $session_items = array();
- foreach( $sale_items as $item )
- {
- $session_items[$item->product_id] = $item->toArray();
- $session_items[$item->product_id]['material_id'] = $item->material_id;
- $session_items[$item->product_id]['product_name'] = $item->material->nome;
- $session_items[$item->product_id]['quant'] = $item->quant;
- }
- TSession::setValue('saida_items', $session_items);
- $this->form->setData($object); // fill the form with the active record data
- TTransaction::close(); // close transaction
- }
- else
- {
- $this->form->clear();
- TSession::setValue('saida_items', null);
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- }
- public function tofloat($num) {
- $dotPos = strrpos($num, '.');
- $commaPos = strrpos($num, ',');
- $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
- ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
- if (!$sep) {
- return floatval(preg_replace("/[^0-9]/", "", $num));
- }
- return floatval(
- preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
- preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
- );
- }
- function onLimpa()
- {
- $this->form->clear();
- TSession::setValue('saida_items', array());
- $data = new stdClass;
- $this->form->setData($data);
- }
- function onPrintNF( $param )
- {
- $action1 = new TAction( array($this, 'onGenerate') );
- $action1->setParameter('dados', $param['dados']);
- $action2 = new TAction( array($this, 'onLimpa') );
- new TQuestion('Deseja imprimir ?', $action1, $action2);
- }
- function onGenerate( $param )
- {
- try
- {
- TTransaction::open('sisestoque');
- $criteria = new TCriteria;
- $criteria->add(new TFilter('id', '=', $param['dados']));
- $ordem['order'] = 'id';
- $ordem['direction'] = 'desc';
- $criteria->setProperties($ordem);
- $repository = new TRepository('Saida');
- $entradas = $repository->load( $criteria );
- if ($entradas)
- {
- $designer = new TEntradaAV;
- $designer->SetTitle('Saída de materiais');
- $designer->fromXml('app/reports/formRetrato.pdf.xml');
- $designer->Dados_Header('Saída de materiais');
- $designer->SetAutoPageBreak(true, 60);
- $designer->generate();
- $controle_quebra = NULL;
- $contador = 1;
- $designer->SetLineWidth(.4);
- $designer->SetY(142);
- $designer->SetX(36);
- foreach ($entradas as $entrada)
- {
- if (!isset($controle_quebra) OR $controle_quebra !== $entrada->id)
- {
- if (isset($controle_quebra))
- {
- $designer->generate();
- $designer->SetFont('Arial', '', 12);
- }
- // CABEÇALHO NOTA FISCAL
- $designer->SetY(142);
- $designer->SetX(36);
- $designer->SetFont('Arial','B',12);
- $designer->Cell(38, 20,'TIPO:', 0, 0,'L', true);
- $designer->SetFont('Arial','',12);
- $designer->Cell(50, 20,$entrada->tipo, 0, 0,'L', true);
- $designer->SetFont('Arial','B',12);
- $designer->Cell(105, 20,'DATA ENTRADA:', 0, 0,'L', true);
- $designer->SetFont('Arial','',12);
- $designer->Cell(90, 20,TDate::date2br($entrada->data_atual), 0, 1,'L', true);
- //CABEÇALHO DETALHES
- $designer->SetFont('Arial','B',10);
- $designer->SetX(38);
- $designer->SetFillColor(200, 200, 200);
- $designer->Cell(48, 22,'ITEM', 1, 0,'C', TRUE);
- $designer->Cell(50, 22,utf8_decode('CÓDIGO'), 1, 0,'C', TRUE);
- $designer->Cell(300, 22,'MATERIAL', 1, 0,'L', TRUE);
- $designer->Cell(30, 22,'UND', 1, 0,'C', TRUE);
- $designer->Cell(93, 22, utf8_decode('QUANTIDADE'), 1, 1,'C', TRUE);
- $controle_quebra = $entrada->id;
- }
- $itens = EntradaItens::where('entrada_id', '=', $entrada->id)->orderBy('entrada_id')->load();
- foreach ($itens as $item)
- {
- $designer->SetFont('Arial', '', 10);
- $designer->SetX(38);
- $designer->Cell( 48, 20, $contador, 1, 0, 'C');
- $designer->Cell( 50, 20, utf8_decode($item->material->id), 1, 0, 'R');
- $designer->Cell( 300, 20, utf8_decode($item->material_nome), 1, 0, 'L');
- $designer->Cell( 30, 20, $item->material->und, 1, 0, 'C');
- $designer->Cell( 93, 20, number_format($item->quant, 2, ',', '.'), 1, 1, 'R');
- $contador = $contador + 1;
- }
- }
- $file = 'app/output/' .time(). 'entradaAV.pdf';
- if (!file_exists($file) OR is_writable($file))
- {
- $designer->output($file);
- parent::openFile($file);
- }
- else
- {
- throw new Exception(_t('Permission denied') . ': ' . $file);
- }
- new TMessage('info', 'Relatório gerado. Por favor habilite os popups do seu navegador');
- }
- else
- {
- new TMessage('info', 'Não há dados para serem impressos !');
- }
- TTransaction::close();
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- $this->onLimpa();
- }
- function onSave()
- {
- try
- {
- TTransaction::open('sisestoque');
- $sale = $this->form->getData('Saida');
- $this->form->validate(); // form validation
- $sale_items = TSession::getValue('saida_items');
- // get session items
- if ( ! $sale_items)
- {
- throw new Exception('Não há itens cadastrados');
- }
- if ( $sale_items )
- {
- foreach( $sale_items as $sale_item )
- {
- $item = new EntradaItens;
- $item->material_id = $sale_item['material_id'];
- $item->quant = $sale_item['quant'];
- $sale->addEntradaItem($item);
- // Atualiza Estoque
- $repo = new TRepository('Estoque');
- $criteria = new TCriteria;
- $criteria->add(new TFilter('material_id', '=', $item->material_id));
- $criteria->add(new TFilter('almoxarifado_id', '=', $sale->almoxarifado_id));
- $objects = $repo->count($criteria);
- if ( $objects > 0 )
- {
- $update_repo = new TRepository('Estoque');
- $objs = $update_repo->load($criteria);
- foreach ($objs as $obj)
- {
- $obj->estoque = $obj->estoque - $this->tofloat( $item->quant );
- $obj->store();
- }
- }
- else
- {
- $estoque = new Estoque;
- $estoque->almoxarifado_id = $sale->almoxarifado_id;
- $estoque->material_id = $item->material_id;
- $estoque->estoque = $estoque->estoque - $this->tofloat( $item->quant);
- $estoque->store();
- }
- }
- $sale->store(); // stores the object
- $action = new TAction( array($this, 'onPrintNF') );
- $action->setParameter('dados', $sale->id);
- new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'), $action);
- }
- TTransaction::close(); // close the transaction
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- $this->form->setData( $this->form->getData() ); // keep form data
- TTransaction::rollback();
- }
- }
- }
- ?>
Código formulário detalhe:
- <?php
- class SaidaDetalheForm extends TPage
- {
- protected $form;
- protected $product_list;
- public function __construct()
- {
- parent::__construct();
- $this->adianti_target_container = 'detalhesai_area';
- $this->form = new BootstrapFormBuilder('form_DetailsSai');
- // detail fields
- $material_id = new TDBUniqueSearch('material_id','sisestoque','Material','id','nome','nome');
- $quant = new TEntry('quant');
- $und = new TEntry('und');
- $estoque = new TEntry('estoque');
- $material_id->addValidation( 'Material', new TRequiredValidator );
- $quant->addValidation( 'Quantidade', new TRequiredValidator );
- $quant->setInputType('numeric');
- $quant->setNumericMask(2, ',', '.', true);
- $material_id->setSize('calc(100% - 140px)');
- $material_id->setMinLength(3);
- $quant->setSize('100%');
- $estoque->setSize('100%');
- $material_id->setChangeAction(new TAction(array($this,'onProductChange')));
- $und->setSize(140);
- $und->setEditable(FALSE);
- $estoque->setEditable(FALSE);
- $this->form->addFields( [$label_product = new TLabel('Material')], [$material_id, $und]);
- $this->form->addFields( [$label_quant = new TLabel('Quantidade')], [$quant], [ new TLabel('Estoque Atual')], [$estoque]);
- $label_product->setFontColor('#FF0000');
- $label_quant->setFontColor('#FF0000');
- $add_action = new TAction(array($this, 'onProductAdd'));
- $add_action->setParameter('register_state', 'false');
- $btn1 = $this->form->addAction( 'Adicionar', $add_action, 'fa:hand-o-down');
- $btn1->class = 'btn btn-sm btn-primary';
- $this->product_list = new BootstrapDatagridWrapper(new TQuickGrid);
- $this->product_list->style = 'margin-bottom:0px;';
- $this->product_list->addQuickColumn('ID', 'material_id', 'left', '10%');
- $this->product_list->addQuickColumn('Material', 'product_name', 'left', '65%');
- $qt = $this->product_list->addQuickColumn('Quantidade', 'quant', 'right', '25%');
- $edit_action = new TDataGridAction([$this, 'onEdit']);
- $delete_action = new TDataGridAction([$this, 'onDelete']);
- $edit_action->setParameter('register_state', 'false');
- $delete_action->setParameter('register_state', 'false');
- $this->product_list->addQuickAction('Edit', $edit_action, 'material_id', 'fa:edit blue');
- $this->product_list->addQuickAction('Delete', $delete_action, 'material_id', 'fa:trash red');
- $this->product_list->createModel();
- $format_value_num = function($value) {
- if (is_numeric($value)) {
- return number_format($value, 2, ',', '.');
- }
- return $value;
- };
- $qt->setTransformer( $format_value_num );
- $panel = TPanelGroup::pack('', $this->product_list);
- $panel->style = 'margin-bottom:0';
- $vbox = new TVBox;
- $vbox->style = 'width: 100%';
- $vbox->add( $this->form );
- $vbox->add( $panel );
- parent::add($vbox);
- }
- /**
- * On product change
- */
- static function onProductChange( $params )
- {
- if( isset($params['material_id']) && $params['material_id'] )
- {
- try
- {
- TTransaction::open('sisestoque');
- // PETGAR O VALOR DE $almoxarifado_id no form_Saida
- $dados = TForm::getData('form_Saida');
- print_r($dados);
- $product = new Material($params['material_id']);
- $fill_data = new StdClass;
- $fill_data->und = $product->und;
- TForm::sendData('form_Saida', $fill_data);
- TTransaction::close();
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- }
- }
- /**
- * Add a product into item list
- * @param $param URL parameters
- */
- public function onProductAdd( $param )
- {
- try
- {
- TTransaction::open('sisestoque');
- $data = $this->form->getData();
- $this->form->validate();
- $product = new Material($data->material_id);
- $sale_items = TSession::getValue('saida_items');
- $key = (int) $data->material_id;
- $sale_items[ $key ] = array('material_id' => $data->material_id,
- 'product_name' => $product->nome,
- 'quant' => $data->quant);
- TSession::setValue('saida_items', $sale_items);
- // clear product form fields after add
- $data->material_id = '';
- $data->product_name = '';
- $data->quant = '';
- TTransaction::close();
- $this->form->setData($data);
- $this->onReload( $param ); // reload the sale items
- }
- catch (Exception $e)
- {
- $this->form->setData( $this->form->getData());
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Edit a product from item list
- * @param $param URL parameters
- */
- public function onEdit( $param )
- {
- // read session items
- $sale_items = TSession::getValue('saida_items');
- // get the session item
- $sale_item = $sale_items[ (int) $param['material_id'] ];
- $data = new stdClass;
- $data->material_id = $param['material_id'];
- $data->product_name = $sale_item['product_name'];
- $data->quant = $sale_item['quant'];
- // fill product fields
- $this->form->setData( $data );
- $this->onReload( $param );
- }
- /**
- * Delete a product from item list
- * @param $param URL parameters
- */
- public function onDelete( $param )
- {
- // read session items
- $sale_items = TSession::getValue('saida_items');
- // delete the item from session
- unset($sale_items[ (int) $param['material_id'] ] );
- TSession::setValue('saida_items', $sale_items);
- // reload sale items
- $this->onReload( $param );
- }
- /**
- * Reload the products list
- * @param $param URL parameters
- */
- public function onReload()
- {
- // read session items
- $sale_items = TSession::getValue('saida_items');
- $this->product_list->clear(); // clear product list
- $data = $this->form->getData();
- if ($sale_items)
- {
- foreach ($sale_items as $list_material_id => $list_product)
- {
- $item = (object) $list_product;
- $this->product_list->addItem( $item );
- }
- }
- $this->loaded = TRUE;
- }
- /**
- * method show()
- * Shows the page
- */
- public function show()
- {
- // check if the datagrid is already loaded
- if (!$this->loaded )
- {
- $this->onReload();
- }
- parent::show();
- }
- }
- ?>
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.