RS
Funcao fire_events TDBCombo dinamico
Ola pessoal,
Estou tendo um problema com o fire_events dos TDBCombo,
Ele esta sendo acionado no evento onEdit de uma classe para carregar 2 combos automaticamente.
1. apos alimentar combo UF
->faz o filtro das cidades daquela uf*
2. apos alimentar a combo CIDADES
->faz o filtro das igrejas daquela cidade*
O problema é que se eu der um F5 ele me mostra os dados corretamente e logo em seguida perde os valores, como se executasse mais de uma vez a trigger
tenho uma outra classe com as mesmas funcoes e mesmo nome de campos que funciona perfeitamente.
segue classe abaixo, se puderem me dar uma ajuda agradeço:
Estou tendo um problema com o fire_events dos TDBCombo,
Ele esta sendo acionado no evento onEdit de uma classe para carregar 2 combos automaticamente.
1. apos alimentar combo UF
->faz o filtro das cidades daquela uf*
2. apos alimentar a combo CIDADES
->faz o filtro das igrejas daquela cidade*
O problema é que se eu der um F5 ele me mostra os dados corretamente e logo em seguida perde os valores, como se executasse mais de uma vez a trigger
tenho uma outra classe com as mesmas funcoes e mesmo nome de campos que funciona perfeitamente.
segue classe abaixo, se puderem me dar uma ajuda agradeço:
- <?php
- class LideresForm extends TPage
- {
- use Adianti\Base\AdiantiStandardFormTrait;
- protected $form;
- public function __construct()
- {
- parent::__construct();
- $this->setDatabase('warriors');
- $this->setActiveRecord('Lideres');
- $this->form = new BootstrapFormBuilder(__CLASS__.'form');
- $this->form->setFormTitle('Cadastro de Líderes');
- $this->form->style = 'width:100%';
- $id = new TEntry('id');
- $nome = new TEntry('nome');
- $uf = new TDBCombo('uf', 'warriors', 'Estados', 'uf', '{nome}');
- $cidade = new TDBCombo('cidade', 'warriors', 'Cidades', 'id', '{nome}');
- $igreja_id = new TDBCombo('igreja_id', 'warriors', 'Igrejas', 'id', 'apelido');
- $departamento_id = new TDBCombo('departamento_id', 'warriors', 'Departamentos', 'id', 'descricao');
- $fone = new TEntry('fone');
- $email = new TEntry('email');
- $senha = new TPassword('senha');
- $ativo = new TCombo('ativo');
- $ativo->addItems(['S'=>'Sim', 'N'=>'Não']);
- $id->setEditable(FALSE);
- $senha->setEditable(FALSE);
- $uf->enableSearch();
- $cidade->enableSearch();
- $igreja_id->enableSearch();
- $uf->setChangeAction(new TAction([$this, 'onChangeUf']));
- $cidade->setChangeAction(new TAction([$this, 'onChangeCidade']));
- $this->form->addFields([new TLabel('Id')],[$id]);
- $this->form->addFields([new TLabel('Nome')],[$nome]);
- $this->form->addFields([new TLabel('UF')],[$uf]);
- $this->form->addFields([new TLabel('Cidade')],[$cidade]);
- $this->form->addFields([new TLabel('Igreja')],[$igreja_id]);
- $this->form->addFields([new TLabel('Departamento')],[$departamento_id]);
- $this->form->addFields([new TLabel('Fone')],[$fone]);
- $this->form->addFields([new TLabel('Email')],[$email]);
- $this->form->addFields([new TLabel('Senha')],[$senha]);
- $this->form->addFields([new TLabel('Ativo')],[$ativo]);
- $this->form->addAction(_t('Save'), new TAction([$this, 'onSave']), 'fa: fa-save green');
- $this->form->addAction('Gerar Nova Senha', new TAction([$this, 'onSave'], ['renew'=>true]), 'fa: fa-cogs red');
- $this->form->addAction(_t('Back'), new TAction(['LideresList', 'onReload']), 'fa: fa-arrow-circle-left blue');
- $container = new TVBox();
- $container->style = 'width:100%; overflow-x:auto';
- $bread = new TBreadCrumb;
- $bread->addHome();
- $bread->addItem('Líderes');
- $bread->addItem('Cadastro de Líderes', TRUE);
- $container->add($bread);
- $container->add($this->form);
- parent::add($container);
- }
- public function fire_events($object)
- {
- TForm::sendData(__CLASS__."form", $object);
- }
- public function onEdit($param)
- {
- try
- {
- if (empty($this->database))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', AdiantiCoreTranslator::translate('Database'), 'setDatabase()', AdiantiCoreTranslator::translate('Constructor')));
- }
- if (empty($this->activeRecord))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', 'Active Record', 'setActiveRecord()', AdiantiCoreTranslator::translate('Constructor')));
- }
- if (isset($param['key']))
- {
- // get the parameter $key
- $key=$param['key'];
- // open a transaction with database
- TTransaction::open($this->database);
- $class = $this->activeRecord;
- // instantiates object
- $object = new $class($key);
- // fill the form with the active record data
- $this->form->setData($object);
- // close the transaction
- TTransaction::close();
- $this->fire_events($object); /* aqui executa o evento*/
- return $object;
- }
- else
- {
- $this->form->clear( true );
- }
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- public function onSave($param = NULL)
- {
- try
- {
- if (empty($this->database))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', AdiantiCoreTranslator::translate('Database'), 'setDatabase()', AdiantiCoreTranslator::translate('Constructor')));
- }
- if (empty($this->activeRecord))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', 'Active Record', 'setActiveRecord()', AdiantiCoreTranslator::translate('Constructor')));
- }
- // open a transaction with database
- TTransaction::open($this->database);
- // get the form data
- $object = $this->form->getData($this->activeRecord);
- if (empty($object->senha)||isset($param['renew']))
- {
- $nova_senha = TUtil::geraSenha(6, FALSE);
- $object->senha = md5($nova_senha);
- }
- else
- {
- unset($object->senha);
- }
- // validate data
- $this->form->validate();
- // stores the object
- $object->store();
- // fill the form with the active record data
- $this->form->setData($object);
- //Verifica se o email foi preenchido e faz a validação do usuario vinculado ao líder
- if(!empty($object->email))
- {
- $user = SystemUser::newFromEmail($object->email);
- if (empty($user)) //Usuário não existe
- {
- $user = new SystemUser();
- $user->name = $object->nome;
- $user->email = $object->email;
- $user->login = $object->email;
- $user->password = $object->senha;
- $user->frontpage_id = 7;
- $user->active = 'Y';
- $user->store();
- $user->addSystemUserGroup(SystemGroup::find(2));
- }
- else //Usuário já existe
- {
- //Alterou senha
- if ($object->senha)
- {
- $user->password = $object->senha;
- $user->store();
- }
- }
- }
- // close the transaction
- TTransaction::close();
- $this->fire_events($object);
- // shows the success message
- if (isset($this->useMessages) AND $this->useMessages === false)
- {
- AdiantiCoreApplication::loadPageURL( $this->afterSaveAction->serialize() );
- }
- else
- {
- new TMessage('info', AdiantiCoreTranslator::translate('Record saved'), $this->afterSaveAction);
- if (isset($nova_senha)) {$this->form->add(new TAlert('info', 'A senha gerada é: <br>'.$nova_senha));}
- }
- return $object;
- }
- catch (Exception $e) // in case of exception
- {
- // get the form data
- $object = $this->form->getData();
- // fill the form with the active record data
- $this->form->setData($object);
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- public static function onChangeUf($param)
- {
- $criteria = new TCriteria();
- if(!empty($param['key']))
- {
- $criteria->add(new TFilter('uf','=', $param['key']));
- TDBCombo::reloadFromModel(
- __CLASS__.'form',
- 'cidade',
- 'warriors',
- 'Cidades',
- 'id',
- 'nome',
- null,
- $criteria);
- }
- else
- {
- TDBCombo::clearField(__CLASS__.'form', 'cidade');
- }
- }
- public static function onChangeCidade($param)
- {
- if(!empty($param['key']))
- {
- $criteria = new TCriteria();
- $criteria->add(new TFilter('cidade','=', $param['key']));
- TDBCombo::reloadFromModel(
- __CLASS__.'form',
- 'igreja_id',
- 'warriors',
- 'Igrejas',
- 'id',
- '{apelido} {cidade_nome}',
- null,
- $criteria);
- }
- else
- {
- TDBCombo::clearField(__CLASS__.'form', 'igreja_id');
- }
- }
- }
- ?>
Na versão 7 foi alterado o método sendData nesse caso passe o false depois do objeto.
Bom dia Felipe, obrigado pela resposta amigo,
Antes de postar aqui no fórum eu dei uma olhada na função sendData dentro da classe TForm, e fiz esse teste, o caso é que dessa maneira o sistema não faz o TCombo::reload enão tras somente as cidades da UF selecionada na combo UF anterior.
Tenho uma classe na versão 7 tambem que possui as funcoes identicas, inclusive com o mesmo nome dos fields e nome funcao, e nela funciona normalmente ao carregar a pagina,
não consigo entender porque aqui nao funciona, já olhei em tudo, é uma tela muito simplista e um código limpo na medida do possível, porém nao consigo encontrar o Wally rsrs.
Tem mais alguma idéia?
Eu faço um pouco diferente no seu caso vc excuta o setData e o sendData eu acredito que vc não precisa fazer isso basta fazer o TDBCombo::reloadFromModel no onEdit e depois mandar por setData mesmo não testei mas acho que não está preenchendo pq não existe o option quando vc manda para o form.
tenta algo assim para testar.
Ontem eu fiz esse teste tambem, nesse caso o app entra em loop, ele fica mandando o value e executando a trigger sem parar,
Simplifiquei o codigo pra ficar mais legivel, deixei apenas os componentes que estao afetados.
Abra o inspecionar vá na aba network e depois execute o onEdit e veja o que ele está executando.
Pelo que vi, esta executando as triggers fora de ordem..
Na classe que funciona normalmente executa:
1. engine.php?class=InscricoesForm&method=onEdit&key=1&id=1 (preenche todo Formulario e preenche os TDBCombo sem filtros indicando o "Selected" correto)
2. engine.php?class=InscricoesForm&method=onChangeUf&static=1&static=1 (tras apenas cidades de acordo com TDBCombo UF)
3. engine.php?class=InscricoesForm&method=onChangeCidade&static=1&static=1 (somente fazendo um clear_TDBCombo IGREJA_ID)
4. engine.php?class=InscricoesForm&method=onChangeCidade&static=1&static=1 (tras apenas as igrejas de acordo com TDBCombo CIDADE)
Já na classe que com problema:
1. engine.php?class=LideresForm&method=onEdit&key=1&id=1 (preenche todo Formulario e preenche os TDBCombo sem filtros indicando o "Selected" correto)
2. engine.php?class=LideresForm&method=onChangeCidade&static=1&static=1 (tras apenas as igrejas de acordo com TDBCombo CIDADE) /*mais ainda nao passou a CIDADE*/
3. engine.php?class=LideresForm&method=onChangeUf&static=1&static=1 (tras apenas cidades de acordo com TDBCombo UF)
4. engine.php?class=LideresForm&method=onChangeCidade&static=1&static=1 (somente fazendo um clear_TDBCombo IGREJA_ID)
Resumindo esta executando as ChangeActions fora de ordem, há como resolver isso?
Felipe Cortez,
descobri o problema e você não vai acreditar,
analisando com sua dica da aba network, e com esses resultados que coloquei, comecei a filosofar aqui,
fui no TRecord que funciona e a ordem estava:
parent::addAttribute('uf');
parent::addAttribute('cidade');
parent::addAttribute('igreja_id');
ja no TRecord que não funciona e a ordem estava errada:
parent::addAttribute('cidade');
parent::addAttribute('uf');
parent::addAttribute('igreja_id');
mudei, salvei e não funcionou, mais não desisti,
Fui na tabela do Mysql.. mudei lá também e pra minha surpresa funcionou...
Ou seja, as ChangeActions executam de acordo com a ordem dos campos na tabela do banco de dados.
Não sei se voce ja sabia dessa condição (eu não sabia), mais fica o conhecimento,
Muito obrigado pelo apoio,
www.adianti.com.br/forum/pt/view_5093?minha-aplicacao-esta-com-erro-
Conselho, revise seu código. Não faz sentido ter duas funções de envio de dados para o form.
Boa sorte !!!
Faz sentido sua observação, eu segui o conselho do tutor:
www.adianti.com.br/framework_files/tutor/index.php?class=FormHierarc
Observei que lá tem o setData no metodo onEdit e o sendData no fire_events,
Obrigado pelo apoio.