RF
Bloqueio de campos
Fechado
Boa tarde...
Tenho o formulário de cotação no meu projeto e gostaria que alguns campos ficassem desabilitados (setEditable(false)) conforme o valor dentro do campo Status, por exemplo: Se o registro selecionado tiver com Status = Aprovado, os campos de calculo do frete não podem estar habilitados, pois o usuário poderia alterar o valor de uma cotação que já foi aprovada.
Segue anexo tela e código do formulário:
Tenho o formulário de cotação no meu projeto e gostaria que alguns campos ficassem desabilitados (setEditable(false)) conforme o valor dentro do campo Status, por exemplo: Se o registro selecionado tiver com Status = Aprovado, os campos de calculo do frete não podem estar habilitados, pois o usuário poderia alterar o valor de uma cotação que já foi aprovada.
Segue anexo tela e código do formulário:
- <?php
- class CotacaoForm extends TPage
- {
- private $form; // form
- function __construct()
- {
- parent::__construct();
- // creates the form
- $this->form = new TForm('form_cotacao');
- $this->form->class = 'tform';
- // cria as tabelas
- $table_data = new TTable;
- $table_destino = new TTable;
- $table_carga = new TTable;
- $table_frete = new TTable;
- $table_diversos = new TTable;
- //Tamanho do notebook
- $notebook = new TNotebook(500, 250);
- // adiciona as abas do notebook
- $this->form->add($notebook);
- // Adiciona o nome das abas do notebook
- $notebook->appendPage('Solicitante', $table_data);
- $notebook->appendPage('Destino', $table_destino);
- $notebook->appendPage('Carga',$table_carga);
- $notebook->appendPage('Frete', $table_frete);
- $notebook->appendPage('Diversos',$table_diversos);
- // campos do formulário
- 2356 = new TEntry('id');
- $customer_cnpj = new TSeekButton('customer_cnpj');
- $status = new TCombo('status');
- $observacoes = new TText('observacoes');
- $solicitante = new TEntry('solicitante');
- $address = new TEntry('address');
- $numero = new TEntry('numero');
- $complemento = new TEntry('complemento');
- $bairro = new TEntry('bairro');
- $cep = new TEntry('cep');
- $uf = new TEntry('uf');
- $municipio = new TEntry('municipio');
- $contato = new TEntry('contato');
- $telefone = new TEntry('telefone');
- $email = new TEntry('email');
- $empresa_col = new TEntry('empresa_col');
- $customercol_cnpj = new TSeekButton('customercol_cnpj');
- $address_col = new TEntry('address_col');
- $numero_col = new TEntry('numero_col');
- $complemento_col = new TEntry('complemento_col');
- $bairro_col = new TEntry('bairro_col');
- $cep_col = new TEntry('cep_col');
- $uf_col = new TEntry('uf_col');
- $municipio_col = new TEntry('municipio_col');
- $produto_id = new TDBCombo('produto_id' , 'samples', 'produto' , 'id', 'name');//busca o produto
- $grnatureza_id = new TDBCombo('grnatureza_id', 'samples', 'Grunatureza', 'id', 'name');//busca a natureza
- $embalagem_id = new TDBCombo('embalagem_id' , 'samples', 'Embalagem' , 'id', 'name');//busca a embalagem
- $distancia = new TEntry('distancia');
- $prod_quimico = new TCombo('prod_quimico');
- $onu = new TEntry('onu');
- $volume = new TEntry('volume');
- $peso = new TEntry('peso');
- $comprimento = new TEntry('comprimento');
- $largura = new TEntry('largura');
- $altura = new TEntry('altura');
- //$cubagem = new TEntry('cubagem');
- //$pesocubado = new TEntry('pesocubado');
- $peso_cubico = new TEntry('peso_cubico');
- $peso_cubado = new TEntry('peso_cubado');
- $valor_nf = new TEntry('valor_nf');
- $comentarios = new TText('comentarios');
- $fretepeso = new TEntry('fretepeso');
- $fretevalor = new TEntry('fretevalor');
- $coleta = new TEntry('coleta');
- $entrega = new TEntry('entrega');
- $data_cotacao = new TDate('data_cotacao');
- $outros = new TEntry('outros');
- $cat = new TEntry('cat');
- $sec_cat = new TEntry('sec_cat');
- $gris = new TEntry('gris');
- $txdespacho = new TEntry('txdespacho');
- $pedagio = new TEntry('pedagio');
- $perc_icms = new TEntry('perc_icms');
- $base_icms = new TEntry('base_icms');
- $valor_icms = new TEntry('valor_icms');
- $frete_total = new TEntry('frete_total');
- $alteracao = new TEntry('alteracao');
- // Tamanho dos campos e desabilitação para editar
- 2356 ->setSize(150);
- 2356 ->setEditable(false);
- $status ->setSize(150);
- $data_cotacao ->setSize(133);
- //Dados do Solicitante
- $solicitante ->setSize(220);
- $solicitante ->style = "text-transform: uppercase";
- $customer_cnpj ->setSize(130);
- $address ->setSize(220);
- $address ->style = "text-transform: uppercase";
- $municipio ->setSize(220);
- $municipio ->style = "text-transform: uppercase";
- $numero ->setSize(75);
- $complemento ->setSize(220);
- $complemento ->style = "text-transform: uppercase";
- $bairro ->setSize(173);
- $bairro ->style = "text-transform: uppercase";
- $cep ->setSize(122);
- $uf ->setSize(50);
- $uf ->style = "text-transform: uppercase";
- $contato ->setSize(220);
- $contato ->style = "text-transform: uppercase";
- $telefone ->setSize(155);
- $email ->setSize(220);
- $email ->style = "text-transform: lowercase";
- //Dados do destino
- $empresa_col ->setSize(220);
- $customercol_cnpj ->setSize(130);
- $address_col ->setSize(220);
- $municipio_col ->setSize(220);
- $numero_col ->setSize(75);
- $complemento_col ->setSize(220);
- $bairro_col ->setSize(173);
- $cep_col ->setSize(122);
- $uf_col ->setSize(50);
- //Dados do produto
- $produto_id ->setSize(350);
- $grnatureza_id ->setSize(350);
- $embalagem_id ->setSize(220);
- $distancia ->setSize(90);
- $prod_quimico ->setSize(144);
- $onu ->setSize(145);
- $observacoes ->setSize(350);
- //Dados da carga
- $volume ->setSize(144);
- $peso ->setSize(144);
- $peso_cubico ->setSize(144);
- $peso_cubado ->setSize(100);
- $comprimento ->setSize(44);
- $largura ->setSize(44);
- $altura ->setSize(44);
- $valor_nf ->setSize(144);
- //Dados do frete
- $fretepeso ->setSize(150);
- $fretevalor ->setSize(150);
- $coleta ->setSize(150);
- $entrega ->setSize(150);
- $txdespacho ->setSize(150);
- $outros ->setSize(150);
- $cat ->setSize(150);
- $sec_cat ->setSize(150);
- $gris ->setSize(150);
- $pedagio ->setSize(150);
- $perc_icms ->setSize(50);
- $base_icms ->setSize(145);
- $valor_icms ->setSize(95);
- $frete_total ->setSize(150);
- //Demais informações
- $alteracao ->setSize(150);
- $comentarios ->setSize(350);
- //Mascaras de entrada, campos obrigatórios, validações e campos obrigatórios
- $fretepeso ->setNumericMask(2, ',', '.',true);
- $fretevalor ->setNumericMask(2, ',', '.',true);
- $coleta ->setNumericMask(2, ',', '.',true);
- $entrega ->setNumericMask(2, ',', '.',true);
- $txdespacho ->setNumericMask(2, ',', '.',true);
- $outros ->setNumericMask(2, ',', '.',true);
- $cat ->setNumericMask(2, ',', '.',true);
- $sec_cat ->setNumericMask(2, ',', '.',true);
- $gris ->setNumericMask(2, ',', '.',true);
- $pedagio ->setNumericMask(2, ',', '.',true);
- $valor_icms ->setNumericMask(2, ',', '.',true);
- $frete_total ->setNumericMask(2, ',', '.',true);
- $valor_nf ->setNumericMask(2, ',', '.',true);
- $base_icms ->setNumericMask(2, ',', '.',true);
- $perc_icms ->setNumericMask(2, ',', '.',true);
- $peso_cubico ->setNumericMask(2, ',','.' ,true);
- $peso_cubado ->setNumericMask(2, ',','.' ,true);
- $comprimento ->setNumericMask(2, ',','.' ,true);
- $largura ->setNumericMask(2, ',','.' ,true);
- $altura ->setNumericMask(2, ',','.' ,true);
- $data_cotacao ->setMask('dd/mm/yyyy');
- $cep ->setMask('99999-999');
- $telefone ->setMask('(99)9999-9999');
- $cep_col ->setMask('99999-999');
- $email ->addValidation('E-mail',new TEmailValidator);
- //Ação dos campos ao perder o foco
- $altura ->setExitAction(new TAction(array($this, 'onCubagem' )));
- $peso_cubico ->setExitAction(new TAction(array($this, 'onPesocubado')));
- //Objeto para criar o campo de busca de solicitante e destinatário por cnpj ou rz social
- $obj = new Remetente; //
- $customer_cnpj->setAction(new TAction(array($obj, 'onReload')));
- $obj2 = new Destinatario; //
- $customercol_cnpj->setAction(new TAction(array($obj2, 'onReload')));
- //Itens do Status
- $itemStatus= array();
- $itemStatus['Lançado'] = 'Lançado';
- $itemStatus['Impresso'] = 'Impresso';
- $itemStatus['Aprovado'] = 'Aprovado';
- $itemStatus['Reprovado'] = 'Reprovado';
- $status->setValue('Lançado');
- $status->addItems($itemStatus);
- //Itens do químico
- $itemQ= array();
- $itemQ['Não'] = 'Não';
- $itemQ['Sim'] = 'Sim';
- $prod_quimico->setValue('Não');
- $prod_quimico->addItems($itemQ);
- //Valores padrões para os campos de calculo do frete, isso evita o erro da linha 79
- $fretepeso ->setValue('0');
- $fretevalor ->setValue('0');
- $coleta ->setValue('0');
- $entrega ->setValue('0');
- $txdespacho ->setValue('0');
- $outros ->setValue('0');
- $cat ->setValue('0');
- $sec_cat ->setValue('0');
- $gris ->setValue('0');
- $pedagio ->setValue('0');
- $valor_icms ->setValue('0');
- $frete_total ->setValue('0');
- $valor_nf ->setValue('0');
- $base_icms ->setValue('0');
- $comprimento ->setValue('0');
- $largura ->setValue('0');
- $altura ->setValue('0');
- $peso_cubico ->setValue('0');
- $peso_cubado ->setValue('0');
- $perc_icms ->setValue('12');
- $status ->setValue('Lançado');
- $alteracao ->setValue(date('d-m-Y / H:i'));
- $alteracao ->setEditable(FALSE);
- $base_icms ->setEditable(FALSE);
- $valor_icms ->setEditable(FALSE);
- // Campos da Aba Solicitante
- $table_data->addRowSet(new TLabel(''));
- $table_data->addRowSet(new TLabel('Número:') ,array(2356, new TLabel('Data de solicitação :'),$data_cotacao));
- $table_data->addRowSet(new TLabel('CNPJ:') ,array($customer_cnpj,new TLabel('Rz Social:'),$solicitante));
- $table_data->addRowSet(new TLabel('Endereço:') ,array($address, new TLabel('Número do endereço:'),$numero));
- $table_data->addRowSet(new TLabel('Complemento:'),array($complemento));
- $table_data->addRowSet(new TLabel('Cidade:') ,array($municipio, new TLabel('Bairro:'),$bairro));
- $table_data->addRowSet(new TLabel('Estado:') ,array($uf, new TLabel('CEP:'),$cep));
- $table_data->addRowSet(new TLabel('Contato:') ,array($contato, new TLabel('Telefone :'),$telefone));
- $table_data->addRowSet(new TLabel('E-mail:') ,$email);
- // Campos da Aba Destino
- $table_destino->addRowSet(new TLabel(''));
- $table_destino->addRowSet(new TLabel('CNPJ:') ,array($customercol_cnpj, new TLabel('Rz Social:'),$empresa_col));
- $table_destino->addRowSet(new TLabel('Endereço:') ,array($address_col, new TLabel('Número do endereço:'),$numero_col));
- $table_destino->addRowSet(new TLabel('Complemento:'),array($complemento_col));
- $table_destino->addRowSet(new TLabel('Cidade:') ,array($municipio_col, new TLabel('Bairro:'),$bairro_col));
- $table_destino->addRowSet(new TLabel('Estado:') ,array($uf_col, new TLabel('CEP:'),$cep_col));
- // Campos da Aba carga
- $table_carga->addRowSet(new TLabel(''));
- $table_carga->addRowSet(new TLabel('Produto:') ,array($produto_id));
- $table_carga->addRowSet(new TLabel('Grupo:') ,array($grnatureza_id) );
- $table_carga->addRowSet(new TLabel('Embalagem:'),array($embalagem_id, new TLabel('KM:'),$distancia));
- $table_carga->addRowSet(new TLabel('Químico?') ,array($prod_quimico, new TLabel('O.n.U :'),$onu));
- $table_carga->addRowSet(new TLabel('Volume:') ,array($volume, new TLabel('PESO :') ,$peso));
- $table_carga->addRowSet(new TLabel('Vlr NF-e:') ,array($valor_nf, new TLabel('C') ,$comprimento,new TLabel('L'),$largura,new TLabel('A'),$altura));
- $table_carga->addRowSet(new TLabel('Cubagem:') ,array($peso_cubico, new TLabel('Peso Cubado:') ,$peso_cubado));
- $table_carga->addRowSet(new TLabel('A carga é:'),array($observacoes));
- //Campos da Aba Frete
- $table_frete->addRowSet(new TLabel(''));
- $table_frete->addRowSet(new TLabel('Frete Peso:'),array($fretepeso, new TLabel('Frete Valor :') ,$fretevalor));
- $table_frete->addRowSet(new TLabel('Entrega:') ,array($entrega, new TLabel('T.Despacho:') ,$txdespacho));
- $table_frete->addRowSet(new TLabel('Coleta:') ,array($coleta, new TLabel('Outra taxa .:') ,$outros));
- $table_frete->addRowSet(new TLabel('C.A.T:') ,array($cat, new TLabel('Vlr. Pedágio:') ,$pedagio));
- $table_frete->addRowSet(new TLabel('GRIS:') ,array($gris, new TLabel('S.E.C / CAT.:') ,$sec_cat));
- $table_frete->addRowSet(new TLabel(''));
- $table_frete->addRowSet(new TLabel('ICMS %') ,array($perc_icms, new TLabel('Base:'),$base_icms, new TLabel('ICMS:'),$valor_icms));
- $table_frete->addRowSet(new TLabel('Total') ,array($frete_total) );
- // Campos da Aba Diversos
- $table_diversos->addRowSet(new TLabel(''));
- $table_diversos->addRowSet(new TLabel('Status:') ,array($status));
- $table_diversos->addRowSet(new TLabel('Comentário:') ,array($comentarios));
- $table_diversos->addRowSet(new TLabel(''));
- $table_diversos->addRowSet(new TLabel('Alterado:') ,array($alteracao));
- //criação das ações dos botões (action button)
- $button1=new TButton('action1');
- $button1->setAction(new TAction(array($this, 'onSave')), 'Salvar');
- $button1->setImage('fa:floppy-o');
- // create an action button (go to list)
- $button2=new TButton('list');
- $button2->setAction(new TAction(array('CotacaoFormView', 'onReload')), 'Voltar para a listagem');
- $button2->setImage('fa:table blue');
- // create an action button (go to list)
- $button3=new TButton('novo');
- $button3->setAction (new TAction(array($this, 'onClear')), _t('New'));//onEdit
- $button3->setImage('bs:plus-sign green');
- // Vai chamar a função para calcular o frete
- $button4=new TButton('calcFrete');
- $button4->setAction (new TAction(array($this, 'onFrete')), ('Calcula o Frete'));
- $button4->setImage('bs:plus-sign green');
- // define os campos que são gravados na model e a variável dos botões
- $this->form->setFields(array(2356, $status, $customer_cnpj,$solicitante,$observacoes,$address,$numero,$complemento,
- $bairro,$cep,$uf,$contato,
- $telefone,$email,$empresa_col,$customercol_cnpj,$address_col,$numero_col,$complemento_col,$bairro_col,$cep_col,
- $uf_col,$produto_id,$municipio_col,$municipio,
- $grnatureza_id,$embalagem_id,$distancia,$prod_quimico,$onu,$volume,$peso,$peso_cubico,$peso_cubado,$valor_nf,
- $comentarios,$fretepeso,$fretevalor,
- $coleta,$entrega,$txdespacho,$outros,$cat,$sec_cat,$gris,$pedagio,$perc_icms,$valor_icms,$frete_total,
- $data_cotacao,$alteracao,
- $button1,$button2,$button3,$button4,$altura,$comprimento,$largura,$base_icms));
- // coloca os botões
- $subtable = new TTable;
- $row = $subtable->addRow();
- $row->addCell($button1);
- $row->addCell($button3);
- $row->addCell($button2);
- $row->addCell($button4);
- // Sub menu bonito
- $vbox = new TVBox;
- $vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $vbox->add($this->form);
- $vbox->style = 'width: 55%';
- //$vbox->add($this->datagrid); //pra mostra a grid
- $vbox->add($subtable);
- parent::add($vbox);
- }
- //*********************** Funções ******************************
- public function onClear( $param ) // botão novo
- {
- $this->form->clear();//Limpa o formulário
- //Informações padrões a serem preenchidas no formulário
- $perc_icms = 12;
- $status = 'Lançado';
- $alteracao = date('d-m-Y / H:i');
- //Apresentação e tratamento do campos
- $obj = new StdClass;
- $obj->perc_icms = number_format($perc_icms , 2, ',', '.');
- $obj->status = $status;
- $obj->alteracao = $alteracao;
- TForm::sendData('form_cotacao', $obj);
- }
- // Calculo da cubagem
- static function onCubagem($param)
- {
- $comprimento = str_replace(',','.', str_replace('.','', $param['comprimento']));
- $largura = str_replace(',','.', str_replace('.','', $param['largura']));
- $altura = str_replace(',','.', str_replace('.','', $param['altura']));
- $peso_cubico = $comprimento * $largura * $altura;
- $obj = new StdClass;
- $obj->peso_cubico = number_format($peso_cubico, 2, ',', '.');
- TForm::sendData('form_cotacao', $obj);
- }
- // Calculo do peso cubado
- static function onPesocubado($param)
- {
- $peso_cubico = str_replace(',','.', str_replace('.','', $param['peso_cubico']));
- $peso_cubado = $peso_cubico * 300;
- $obj = new StdClass;
- $obj->peso_cubado = number_format($peso_cubado, 2, ',', '.');
- TForm::sendData('form_cotacao', $obj);
- }
- // Calculo do valor do frete
- static function onFrete($param)
- {
- //Tratamento dos campos
- $fretepeso = str_replace(',','.', str_replace('.','', $param['fretepeso']));
- $fretevalor = str_replace(',','.', str_replace('.','', $param['fretevalor']));
- $coleta = str_replace(',','.', str_replace('.','', $param['coleta']));
- $entrega = str_replace(',','.', str_replace('.','', $param['entrega']));
- $txdespacho = str_replace(',','.', str_replace('.','', $param['txdespacho']));
- $outros = str_replace(',','.', str_replace('.','', $param['outros']));
- $cat = str_replace(',','.', str_replace('.','', $param['cat']));
- $sec_cat = str_replace(',','.', str_replace('.','', $param['sec_cat']));
- $gris = str_replace(',','.', str_replace('.','', $param['gris']));
- $pedagio = str_replace(',','.', str_replace('.','', $param['pedagio']));
- $perc_icms = str_replace(',','.', str_replace('.','', $param['perc_icms']));
- //Calculos
- $base_icms = ($fretepeso + $fretevalor + $coleta + $entrega + $txdespacho +
- $outros + $cat + $sec_cat + $gris + $pedagio) ;
- $frete_total = $base_icms / ((100 - $perc_icms)/100);
- $valor_icms = $frete_total - $base_icms;
- //Apresentação e tratamento do campos
- $obj = new StdClass;
- $obj->base_icms = number_format($base_icms , 2, ',', '.');
- $obj->frete_total = number_format($frete_total, 2, ',', '.');
- $obj->valor_icms = number_format($valor_icms , 2, ',', '.');
- TForm::sendData('form_cotacao', $obj);
- }
- /**
- * Load object to form data
- * @param $param Request
- */
- public function onEdit( $param )
- {
- try
- {
- if (isset($param['key']))
- {
- $key = $param['key']; // get the parameter $key
- TTransaction::open('samples'); // open a transaction
- $object = new Cotacao($key); // instantiates the Active Record
- $object->data_cotacao = TDate::date2br($object->data_cotacao);
- $this->form->setData($object); // fill the form
- TTransaction::close(); // close the transaction
- }
- else
- {
- $this->form->clear();
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
- /**
- * method onSave()
- * Executed whenever the user clicks at the save button
- */
- function onSave()
- {
- try
- {
- $alteracao = date('d-m-Y / H:i');
- $obj = new StdClass;
- $obj->alteracao = $alteracao;
- TForm::sendData('form_cotacao', $obj);
- TTransaction::open('samples'); // Abre a conexão com o banco
- $this->form->validate(); // validação dos dados
- $object = $this->form->getData('Cotacao');//abre a tabela
- $object->data_cotacao = TDate::date2us($object->data_cotacao);//converte para formato US
- $object->store();//grava
- $object->data_cotacao = TDate::date2br($object->data_cotacao);
- $this->form->setData($object);//
- new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
- TTransaction::close(); //fecha o banco
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- TTransaction::rollback();
- }
- }
- }
Olá Robson. Tenta com JQuery:
Não sei se é a melhor forma de fazer isso, mas eu uso assim e funciona!
Boa noite Ivan, quase funcionou do modo como desejado, na verdade ao abrir o formulário de lançamento (CotacaoForm) o campo continua sendo exibido, ou seja, só funciona quando altero o status.
Na verdade eu queria: Ao selecionar um registro do formulário CotacaoFormView, e o Status fosse "Aprovado" ao abrir CotacaoForm alguns campos (por exemplo frete_total) aparecesse desabilitado.
Entendi, então faça assim:
No início do programa declare os campos que vc vai querer manipular como private:
Depois declare as variáveis dos campos com o this:
Na function onEdit(), vc faz a verificação do status e altera o atributo dos campos:
Acho que é isso
Boa noite Ivan, muito obrigado mais uma vez. Deu certo, aprendi mais algumas coisas.
Na verdade para esse momento vou fazer algo diferente. Só não vou permitir que o registro seja gravado se o Status for igual a Lançado, para a próxima tela (Ordens de coleta e Romaneio) vou usar esse conceito que entendi.
Amanhã publico a versão corrigida, se desejar dar uma olhada no meu trabalho entre em transpalog.esy.es usuário convidado, senha convidado.
Até a próxima dúvida... rssss
Ok Robson, vou dar uma olhada. Abraço