Lançado Adianti Framework 7.6!
Clique aqui para saber mais
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 ...
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:
  1. <?php
  2.     class LideresForm extends TPage
  3.     {
  4.         use Adianti\Base\AdiantiStandardFormTrait;
  5.         
  6.         protected $form;
  7.                 
  8.         public function __construct()
  9.         {
  10.             parent::__construct();
  11.             
  12.             $this->setDatabase('warriors');
  13.             $this->setActiveRecord('Lideres');
  14.             
  15.             $this->form = new BootstrapFormBuilder(__CLASS__.'form');
  16.             $this->form->setFormTitle('Cadastro de Líderes');
  17.             $this->form->style 'width:100%';
  18.             
  19.             $id              = new TEntry('id');
  20.             $nome            = new TEntry('nome');
  21.             $uf              = new TDBCombo('uf''warriors''Estados''uf''{nome}');
  22.             $cidade          = new TDBCombo('cidade''warriors''Cidades''id''{nome}');
  23.             $igreja_id       = new TDBCombo('igreja_id''warriors''Igrejas''id''apelido');
  24.             $departamento_id = new TDBCombo('departamento_id''warriors''Departamentos''id''descricao');
  25.             $fone            = new TEntry('fone');
  26.             $email           = new TEntry('email');
  27.             $senha           = new TPassword('senha');
  28.             $ativo           = new TCombo('ativo');
  29.             $ativo->addItems(['S'=>'Sim''N'=>'Não']);
  30.             
  31.             $id->setEditable(FALSE);
  32.             $senha->setEditable(FALSE);
  33.             
  34.             $uf->enableSearch();
  35.             $cidade->enableSearch();
  36.             $igreja_id->enableSearch();
  37.             
  38.             $uf->setChangeAction(new TAction([$this'onChangeUf']));
  39.             $cidade->setChangeAction(new TAction([$this'onChangeCidade']));
  40.             
  41.             $this->form->addFields([new TLabel('Id')],[$id]);
  42.             $this->form->addFields([new TLabel('Nome')],[$nome]);
  43.             $this->form->addFields([new TLabel('UF')],[$uf]);
  44.             $this->form->addFields([new TLabel('Cidade')],[$cidade]);
  45.             $this->form->addFields([new TLabel('Igreja')],[$igreja_id]);
  46.             $this->form->addFields([new TLabel('Departamento')],[$departamento_id]);
  47.             $this->form->addFields([new TLabel('Fone')],[$fone]);
  48.             $this->form->addFields([new TLabel('Email')],[$email]);
  49.             $this->form->addFields([new TLabel('Senha')],[$senha]);
  50.             $this->form->addFields([new TLabel('Ativo')],[$ativo]);
  51.             
  52.             $this->form->addAction(_t('Save'), new TAction([$this'onSave']), 'fa: fa-save green');
  53.             $this->form->addAction('Gerar Nova Senha', new TAction([$this'onSave'], ['renew'=>true]), 'fa: fa-cogs red');
  54.             $this->form->addAction(_t('Back'), new TAction(['LideresList''onReload']), 'fa: fa-arrow-circle-left blue');            
  55.             
  56.             $container = new TVBox();
  57.             $container->style 'width:100%; overflow-x:auto';
  58.             $bread = new TBreadCrumb;
  59.             $bread->addHome();
  60.             $bread->addItem('Líderes');
  61.             $bread->addItem('Cadastro de Líderes'TRUE);
  62.             $container->add($bread);
  63.             $container->add($this->form);
  64.             parent::add($container);
  65.         }
  66.         
  67.          public function fire_events($object)
  68.          {
  69.             TForm::sendData(__CLASS__."form"$object);
  70.          }
  71.         
  72.         public function onEdit($param)
  73.         {
  74.             try
  75.             {
  76.                 if (empty($this->database))
  77.                 {
  78.                     throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3'AdiantiCoreTranslator::translate('Database'), 'setDatabase()'AdiantiCoreTranslator::translate('Constructor')));
  79.                 }
  80.                 
  81.                 if (empty($this->activeRecord))
  82.                 {
  83.                     throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3''Active Record''setActiveRecord()'AdiantiCoreTranslator::translate('Constructor')));
  84.                 }
  85.                 
  86.                 if (isset($param['key']))
  87.                 {
  88.                     // get the parameter $key
  89.                     $key=$param['key'];
  90.                     
  91.                     // open a transaction with database
  92.                     TTransaction::open($this->database);
  93.                     
  94.                     $class $this->activeRecord;
  95.                     
  96.                     // instantiates object
  97.                     $object = new $class($key);
  98.                     
  99.                     // fill the form with the active record data
  100.                     $this->form->setData($object);
  101.                     
  102.                     // close the transaction
  103.                     TTransaction::close(); 
  104.                     
  105.                     $this->fire_events($object); /* aqui executa o evento*/
  106.                     
  107.                     return $object;                    
  108.                 }
  109.                 else
  110.                 {
  111.                     $this->form->cleartrue );
  112.                 }
  113.             }
  114.             catch (Exception $e// in case of exception
  115.             {
  116.                 // shows the exception error message
  117.                 new TMessage('error'$e->getMessage());
  118.                 // undo all pending operations
  119.                 TTransaction::rollback();
  120.             }
  121.         }
  122.     
  123.         public function onSave($param NULL)
  124.         {
  125.             try
  126.             {
  127.                 if (empty($this->database))
  128.                 {
  129.                     throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3'AdiantiCoreTranslator::translate('Database'), 'setDatabase()'AdiantiCoreTranslator::translate('Constructor')));
  130.                 }
  131.                 
  132.                 if (empty($this->activeRecord))
  133.                 {
  134.                     throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3''Active Record''setActiveRecord()'AdiantiCoreTranslator::translate('Constructor')));
  135.                 }
  136.                 
  137.                 // open a transaction with database
  138.                 TTransaction::open($this->database);
  139.                 
  140.                 // get the form data
  141.                 $object $this->form->getData($this->activeRecord);
  142.                 
  143.                 if (empty($object->senha)||isset($param['renew']))
  144.                 {
  145.                     $nova_senha TUtil::geraSenha(6FALSE);
  146.                     $object->senha md5($nova_senha);
  147.                 } 
  148.                 else
  149.                 {
  150.                     unset($object->senha);
  151.                 }
  152.     
  153.                 // validate data
  154.                 $this->form->validate();
  155.                 
  156.                 // stores the object
  157.                 $object->store();
  158.                 
  159.                 // fill the form with the active record data
  160.                 $this->form->setData($object);
  161.                 
  162.                 //Verifica se o email foi preenchido e faz a validação do usuario vinculado ao líder
  163.                 if(!empty($object->email))
  164.                 {
  165.                     $user SystemUser::newFromEmail($object->email); 
  166.                     
  167.                     if (empty($user)) //Usuário não existe
  168.                     {
  169.                         $user = new SystemUser();
  170.                         $user->name  $object->nome;
  171.                         $user->email $object->email;
  172.                         $user->login $object->email;
  173.                         $user->password $object->senha;
  174.                         $user->frontpage_id 7;
  175.                         $user->active 'Y'
  176.                         $user->store(); 
  177.                         
  178.                         $user->addSystemUserGroup(SystemGroup::find(2));                  
  179.                     }
  180.                     else //Usuário já existe
  181.                     {
  182.                          //Alterou senha
  183.                          if ($object->senha)
  184.                          {
  185.                              $user->password $object->senha;
  186.                              $user->store(); 
  187.                          }     
  188.                     }
  189.                 }
  190.     
  191.                 // close the transaction
  192.                 TTransaction::close();
  193.                 
  194.                 $this->fire_events($object);
  195.                 
  196.                 // shows the success message
  197.                 if (isset($this->useMessages) AND $this->useMessages === false)
  198.                 {
  199.                     AdiantiCoreApplication::loadPageURL$this->afterSaveAction->serialize() );
  200.                 }
  201.                 else
  202.                 {
  203.                     new TMessage('info'AdiantiCoreTranslator::translate('Record saved'), $this->afterSaveAction);
  204.                     if (isset($nova_senha)) {$this->form->add(new TAlert('info''A senha gerada é: <br>'.$nova_senha));}
  205.                 }
  206.                 
  207.                 return $object;
  208.             }
  209.             catch (Exception $e// in case of exception
  210.             {
  211.                 // get the form data
  212.                 $object $this->form->getData();
  213.                 
  214.                 // fill the form with the active record data
  215.                 $this->form->setData($object);
  216.                 
  217.                 // shows the exception error message
  218.                 new TMessage('error'$e->getMessage());
  219.                 
  220.                 // undo all pending operations
  221.                 TTransaction::rollback();
  222.             }
  223.         }
  224.         public static function onChangeUf($param)
  225.         {
  226.             $criteria = new TCriteria();
  227.             
  228.             if(!empty($param['key']))
  229.             {
  230.                 $criteria->add(new TFilter('uf','='$param['key']));
  231.                 
  232.                 TDBCombo::reloadFromModel(
  233.                             __CLASS__.'form',
  234.                             'cidade',
  235.                             'warriors',
  236.                             'Cidades',
  237.                             'id',
  238.                             'nome',
  239.                             null,
  240.                             $criteria);            
  241.             }
  242.             else
  243.             {
  244.                   TDBCombo::clearField(__CLASS__.'form''cidade');   
  245.             } 
  246.                         
  247.         }
  248.         
  249.         public static function onChangeCidade($param)
  250.         {
  251.             if(!empty($param['key']))
  252.             {
  253.                 $criteria = new TCriteria();
  254.                 $criteria->add(new TFilter('cidade','='$param['key'])); 
  255.                 
  256.                 TDBCombo::reloadFromModel(
  257.                             __CLASS__.'form',
  258.                             'igreja_id',
  259.                             'warriors',
  260.                             'Igrejas',
  261.                             'id',
  262.                             '{apelido} {cidade_nome}',
  263.                             null,
  264.                             $criteria);           
  265.             }
  266.             else
  267.             {
  268.                 TDBCombo::clearField(__CLASS__.'form''igreja_id');     
  269.             }  
  270.         }             
  271.  }
  272. ?>

Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


Dominando o Adianti 7 Quero me inscrever agora!

Comentários (9)


FC

Na versão 7 foi alterado o método sendData nesse caso passe o false depois do objeto.

  1. <?php
  2. public function fire_events($object)
  3.          {
  4.             TForm::sendData(__CLASS__."form"$objectfalsefalse);
  5.          }
  6. ?>
RS

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?
FC

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.

  1. <?php
  2.  $criteria = new TCriteria();
  3.  $criteria->add(new TFilter('cidade','='$object->cidade_id)); 
  4.                 
  5.                 TDBCombo::reloadFromModel(
  6.                             __CLASS__.'form',
  7.                             'igreja_id',
  8.                             'warriors',
  9.                             'Igrejas',
  10.                             'id',
  11.                             '{apelido} {cidade_nome}',
  12.                             null,
  13.                             $criteria);     
  14. $this->form->setData($object);
  15. ?>
RS

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.

  1. <?php
  2.     class LideresForm extends TPage
  3.     {
  4.         use Adianti\Base\AdiantiStandardFormTrait;
  5.         
  6.         protected $form;
  7.                 
  8.         public function __construct()
  9.         {
  10.             parent::__construct();
  11.             
  12.             $this->setDatabase('warriors');
  13.             $this->setActiveRecord('Lideres');
  14.             
  15.             $this->form = new BootstrapFormBuilder(__CLASS__.'form');
  16.             $this->form->setFormTitle('Cadastro de Líderes');
  17.             $this->form->style 'width:100%';
  18.             $uf              = new TDBCombo('uf''warriors''Estados''uf''nome');
  19.             $cidade          = new TDBCombo('cidade''warriors''Cidades''id''nome');
  20.             $igreja_id       = new TDBCombo('igreja_id''warriors''Igrejas''id''apelido');
  21.             
  22.             $uf->setChangeAction(new TAction([$this'onChangeUf']));
  23.             $cidade->setChangeAction(new TAction([$this'onChangeCidade']));
  24.             
  25.             $this->form->addFields([new TLabel('UF')],[$uf]);
  26.             $this->form->addFields([new TLabel('Cidade')],[$cidade]);
  27.             $this->form->addFields([new TLabel('Igreja')],[$igreja_id]);
  28.             
  29.             $this->form->addAction(_t('Save'), new TAction([$this'onSave']), 'fa: fa-save green');
  30.             $this->form->addAction(_t('Back'), new TAction(['LideresList''onReload']), 'fa: fa-arrow-circle-left blue');            
  31.             
  32.             $container = new TVBox();
  33.             $container->style 'width:100%; overflow-x:auto';
  34.             $bread = new TBreadCrumb;
  35.             $bread->addHome();
  36.             $bread->addItem('Líderes');
  37.             $bread->addItem('Cadastro de Líderes'TRUE);
  38.             $container->add($bread);
  39.             $container->add($this->form);
  40.             parent::add($container);
  41.         }
  42.         
  43.          public function fire_events($object)
  44.          {
  45.             TForm::sendData(__CLASS__."form"$object);
  46.          }
  47.         
  48.         public function onEdit($param)
  49.         {
  50.             try
  51.             {
  52.                 if (empty($this->database))
  53.                 {
  54.                     throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3'
  55.                     AdiantiCoreTranslator::translate('Database'), 'setDatabase()'AdiantiCoreTranslator::translate('Constructor')));
  56.                 }
  57.                 
  58.                 if (empty($this->activeRecord))
  59.                 {
  60.                     throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3'
  61.                     'Active Record''setActiveRecord()'AdiantiCoreTranslator::translate('Constructor')));
  62.                 }
  63.                 
  64.                 if (isset($param['key']))
  65.                 {
  66.                     // get the parameter $key
  67.                     $key=$param['key'];
  68.                     
  69.                     // open a transaction with database
  70.                     TTransaction::open($this->database);
  71.                     
  72.                     $class $this->activeRecord;
  73.                     
  74.                     // instantiates object
  75.                     $object = new $class($key);
  76.                     
  77.                     // fill the form with the active record data
  78.                     $this->form->setData($object);                
  79.                     
  80.                     // close the transaction
  81.                     TTransaction::close(); 
  82.                     
  83.                     $this->fire_events($object);
  84.                     
  85.                     return $object;                    
  86.                 }
  87.                 else
  88.                 {
  89.                     $this->form->cleartrue );
  90.                 }
  91.             }
  92.             catch (Exception $e// in case of exception
  93.             {
  94.                 // shows the exception error message
  95.                 new TMessage('error'$e->getMessage());
  96.                 // undo all pending operations
  97.                 TTransaction::rollback();
  98.             }
  99.         }
  100.     
  101.         public static function onChangeUf($param)
  102.         {
  103.             $criteria = new TCriteria();
  104.             
  105.             if(!empty($param['key']))
  106.             {
  107.                 $criteria = new TCriteria();
  108.                 $criteria->add(new TFilter('uf','='$param['key']));
  109.                         
  110.                 TDBCombo::reloadFromModel(
  111.                             __CLASS__.'form',
  112.                             'cidade',
  113.                             'warriors',
  114.                             'Cidades',
  115.                             'id',
  116.                             'nome',
  117.                             null,
  118.                             $criteria);            
  119.             }
  120.             else
  121.             {
  122.                   TDBCombo::clearField(__CLASS__.'form''cidade');   
  123.             } 
  124.                         
  125.         }
  126.         
  127.         public static function onChangeCidade($param)
  128.         {
  129.             if(!empty($param['key']))
  130.             {           
  131.                 $criteria = new TCriteria();
  132.                 $criteria->add(new TFilter('cidade','='$param['key'])); 
  133.                 
  134.                 TDBCombo::reloadFromModel(
  135.                             __CLASS__.'form',
  136.                             'igreja_id',
  137.                             'warriors',
  138.                             'Igrejas',
  139.                             'id',
  140.                             'apelido',
  141.                             null,
  142.                             $criteria);           
  143.             }
  144.             else
  145.             {
  146.                 TDBCombo::clearField(__CLASS__.'form''igreja_id');     
  147.             }  
  148.         }             
  149.  }
  150. ?>

FC

Abra o inspecionar vá na aba network e depois execute o onEdit e veja o que ele está executando.
RS

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?
RS

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,

FC

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 !!!
RS

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.