Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Atualização automática de datagrid com refresh Pessoal, Preciso de alguma forma ficar atualizando a cada X segundos os dados de uma tela de monitoramento com as informações contidas numa tabela. Alguma sugestão? Obrigado. ...
JD
Atualização automática de datagrid com refresh  
Fechado
Pessoal,

Preciso de alguma forma ficar atualizando a cada X segundos os dados de uma tela de monitoramento com as informações contidas numa tabela.

Alguma sugestão?

Obrigado.


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 (11)


JD

Uma solução ( não ideal ) foi colocar no código:

  1. <?php
  2. $script = new TElement('script'); 
  3.         $script->type 'text/javascript'
  4.         $script->add('
  5.             $(document).ready(function(){
  6.                    window.setTimeout(function(){ document.location.reload(true); }, 20000);
  7.             });
  8.         ');
  9. ....
  10. parent::add($script)
  11. ?>


Mas eu queria algo que não carregasse a página inteira, somente os dados.


JD

Olá Julio, tudo bem?
Sobre sua dúvida, veja se entendi, você tem um TGrid e você quer que este TGrid, atualize em um determinado período de tempo, porém, não quer atualizar a pagina inteira, é isso?
Se for este o caso, onde você tem exatamente um TGrid, sugiro trocar o
document.location.reload(true);
por
__adianti_load_page('engine.php?class={SuaClasse}');

Trocando {SuaClasse} pelo nome da classe que esta com o TGrid, caso esteja invoncando um metodo use
__adianti_load_page('engine.php?class={SuaClasse}&method={SeuMetodo}');

Trocando {SeuMetodo} pelo nome do método.
E se me permite uma sugestão, se esta rotina for apenas uma rotina de monitoramento, onde não há a necessidade de se manipular os dados (CRUD), sugiro que você crie uma tabela utilizando a classe TElement, depois crie uma rotina no backend que irá te retornar os dados no formato JSON e utilize javascript(Jquery talvez) para popular a tabela, assim você ganha desempenho e a interação do usuário fica mais amigável.
Não sei se estes são os métodos ideais, mas espero que ajude.
JD

Opa Jheferson,

No caso eu tenho mesmo que ler de uma tabela.

Queria te agradecer pois ficou perfeito a sugestão de colocar :
  1. <?php__adianti_load_page('engine.php?class={SuaClasse}&method={SeuMetodo}'); ?>


Muito obrigado.
JD


index.php?class=SystemStatusForm ( no SystemStatusForm eu coloquei o que vc sugeriu )

Aí eu naveguei e fui para

index.php?class=SettingsList

E após X segundos ele voltou para SystemStatusForm&method=onReload



JD

Olá Julio, que bom que pude ajudar.
Poste seu código completo, deixa eu ver como esta, acredito que o problema pode esta na hora de add o script na pagina, pois esta adicionando e mantendo no DOM.
JD

Tá aí Jheferson:


  1. <?php 
  2. class SystemStatusForm extends TPage {
  3.     private $loaded;
  4.     private $form;
  5.     private $f_hw_cores;
  6.     private $f_hw_memory;
  7.     private $f_hw_uptime;
  8.     private $f_sw_radius;
  9.     private $f_sw_uptime;
  10.     private $f_sw_version;
  11.  /**
  12.      * Class constructor
  13.      * Creates the tb
  14.      */
  15.     function __construct()
  16.     {
  17.         parent::__construct();
  18.         $script = new TElement('script'); 
  19.         $script->type 'text/javascript'
  20.         $script->add('$(document).ready(function(){
  21. //                           window.setTimeout(function(){ document.location.reload(true); }, 5000);
  22.                            window.setTimeout(function(){ __adianti_load_page("engine.php?class=SystemStatusForm&method=onReload") }, 5000);
  23.                       });
  24.                     ');
  25.          // creates the form
  26.         $this->form = new TQuickForm('form_SystemStatus');
  27.         $this->form->class 'tform'// change CSS
  28.         $this->form->style 'display: table;width:100%'// change style
  29.         
  30.         // define the form title
  31.         $this->form->setFormTitle('Status do Sistema');
  32.        
  33.         // create the values labels
  34.         $this->f_hw_cores  = new TLabel('');
  35.         $this->f_hw_memory = new TLabel('');
  36.         $this->f_hw_uptime = new TLabel('');
  37.         $this->f_sw_radius = new TLabel('');
  38.         $this->f_sw_uptime = new TLabel('');
  39.         $this->f_sw_version = new TLabel('');
  40.         // create the labels for the values labels
  41.         $l_hw_cores  = new TLabel('Cores:');
  42.         $l_hw_memory = new TLabel('Memory:');
  43.         $l_hw_uptime = new TLabel('Uptime:');
  44.         $l_sw_radius = new TLabel('Radius:');
  45.         $l_sw_uptime = new TLabel('Uptime:');
  46.         $l_sw_version = new TLabel('Version:');
  47.         
  48.         $button_hw_restart = new TButton('action_hw_restart');
  49.         $button_hw_restart->setAction( new TAction(array($this'HwRestart')), 'Reiniciar hardware' );
  50.         $button_hw_restart->setImage('fa:cubes blue');
  51.         $button_sw_restart = new TButton('action_sw_restart');
  52.         $button_sw_restart->setAction( new TAction(array($this'SwRestart')), 'Reiniciar software' );
  53.         $button_sw_restart->setImage('fa:cubes green');
  54.         
  55.         $this->form->setFields(array($button_hw_restart,$button_sw_restart));
  56.                  
  57.         // define label layout
  58.         $l_hw_cores->style 'line-height: 30px; font-size: 20px';
  59.         $l_hw_memory->style 'line-height: 30px; font-size: 20px';
  60.         $l_hw_uptime->style 'line-height: 30px; font-size: 20px';
  61.         $l_sw_radius->style 'line-height: 30px; font-size: 20px';
  62.         $l_sw_uptime->style 'line-height: 30px; font-size: 20px';
  63.         $l_sw_version->style 'line-height: 30px; font-size: 20px';
  64.         // define label values layout
  65.         $this->f_hw_cores->style 'color: blue; font-style: italic;  font-size: 20px';
  66.         $this->f_hw_cores->style 'color: blue; font-style: italic;  font-size: 20px';
  67.         $this->f_hw_memory->style 'color: blue; font-style: italic;  font-size: 20px';
  68.         $this->f_hw_uptime->style 'color: blue; font-style: italic;  font-size: 20px';
  69.         $this->f_sw_radius->style 'color: blue; font-style: italic;  font-size: 20px';
  70.         $this->f_sw_uptime->style 'color: blue; font-style: italic;  font-size: 20px';
  71.         $this->f_sw_version->style 'color: blue; font-style: italic;  font-size: 20px';
  72.  
  73.         // creates a frame_hw
  74.         $frame_hw = new TFrame;
  75.         $frame_hw->oid 'frame_hw';
  76.         $frame_hw->setLegend('HARDWARE');
  77.        
  78.         // add tb_hw inside the frame_hw
  79.         $tb_hw = new TTable;
  80.         $frame_hw->add($tb_hw);
  81.         
  82.         // add a row for tb_hw fields
  83.         $row=$tb_hw->addRow();
  84.         $row->addCell($l_hw_cores);
  85.         $row->addCell($this->f_hw_cores);
  86.         // add a row for tb_hw fields
  87.         $row=$tb_hw->addRow();
  88.         $row->addCell($l_hw_memory);
  89.         $row->addCell($this->f_hw_memory);
  90.         // add a row for tb_hw fields
  91.         $row=$tb_hw->addRow();
  92.         $row->addCell($l_hw_uptime);
  93.         $row->addCell($this->f_hw_uptime);       
  94.         // add a row for tb_hw fields
  95.         $row=$tb_hw->addRow();
  96.         $row->addCell($button_hw_restart);
  97.        
  98.        
  99.         // creates a frame_sw
  100.         $frame_sw = new TFrame;
  101.         $frame_sw->oid 'frame_sw';
  102.         $frame_sw->setLegend('SOFTWARE');
  103.         // add frame_sw inside the form
  104.         $row=$this->form->addRow();
  105.         $row->addCell($frame_hw);
  106.         $row->addCell($frame_sw);
  107.         // add tb_sw inside the frame_sw
  108.         $tb_sw = new TTable;    
  109.         $frame_sw->add($tb_sw);
  110.         
  111.         // add a row for tb_sw fields
  112.         $row=$tb_sw->addRow();
  113.         $row->addCell($l_sw_radius);
  114.         $row->addCell($this->f_sw_radius);
  115.         // add a row for tb_sw fields
  116.         $row=$tb_sw->addRow();
  117.         $row->addCell($l_sw_uptime);
  118.         $row->addCell($this->f_sw_uptime);
  119.         // add a row for tb_sw fields
  120.         $row=$tb_sw->addRow();
  121.         $row->addCell($l_sw_version);
  122.         $row->addCell($this->f_sw_version);        
  123.         // add a row for tb_hw fields
  124.         $row=$tb_sw->addRow();
  125.         $row->addCell($button_sw_restart);
  126.       
  127.         // wrap the tb content using vertical box
  128.         $vbox = new TVBox;
  129.         $vbox->style 'width: 90%';
  130.         $vbox->add($this->form);
  131.         
  132.         parent::add($script);
  133.         parent::add($vbox);
  134.         
  135.     }
  136.     
  137.     function onReload()
  138.     {
  139.         try
  140.         {
  141.             TTransaction::open('conPPPOE');
  142.             $repository = new TRepository('SystemStatus');
  143.             $criteria = new TCriteria;
  144.             $objects $repository->load$criteria );
  145.             
  146.             foreach( $objects as $obj ) {
  147.                 if( $obj->varname == 'hw_cores' ) {
  148.                     if( $obj->varextra != '' 
  149.                         $this->f_hw_cores->setValue$obj->varvalue." [ ".$obj->varextra." ]" );
  150.                     else
  151.                         $this->f_hw_cores->setValue$obj->varvalue );
  152.                 }
  153.                 if( $obj->varname == 'hw_memory' ) {
  154.                     if( $obj->varextra != '' 
  155.                         $this->f_hw_memory->setValue$obj->varvalue." [ ".$obj->varextra." ]" );
  156.                     else
  157.                         $this->f_hw_memory->setValue$obj->varvalue );
  158.                 }
  159.                 if( $obj->varname == 'hw_uptime' ) {
  160.                     if( $obj->varextra != '' 
  161.                         $this->f_hw_uptime->setValue$obj->varvalue." [ ".$obj->varextra." ]" );
  162.                     else
  163.                         $this->f_hw_uptime->setValue$obj->varvalue );
  164.                 }
  165.                 if( $obj->varname == 'sw_radius' ) {
  166.                     if( $obj->varextra != '' 
  167.                         $this->f_sw_radius->setValue$obj->varvalue." [ ".$obj->varextra." ]" );
  168.                     else
  169.                         $this->f_sw_radius->setValue$obj->varvalue );
  170.                 }
  171.                 if( $obj->varname == 'sw_uptime' ) {
  172.                     if( $obj->varextra != '' 
  173.                         $this->f_sw_uptime->setValue$obj->varvalue." [ ".$obj->varextra." ]" );
  174.                     else
  175.                         $this->f_sw_uptime->setValue$obj->varvalue );
  176.                 }
  177.                 if( $obj->varname == 'sw_version' ) {
  178.                     if( $obj->varextra != '' 
  179.                         $this->f_sw_version->setValue$obj->varvalue." [ ".$obj->varextra." ]" );
  180.                     else
  181.                         $this->f_sw_version->setValue$obj->varvalue );
  182.                 }
  183.                                   
  184.             }
  185.         
  186.         }
  187.         catch (Exception $e)
  188.         {
  189.             new TMessage('error',$e->getMessage());
  190.         }
  191.         
  192.         $this->loaded TRUE;    
  193.     }
  194.     
  195.     /**
  196.      * shows the page
  197.      */    
  198.     function show()
  199.     {
  200.         if( !$this->loaded ) {
  201.             $this->onReloadfunc_get_arg(0));
  202.         }
  203.         parent::show();
  204.        
  205.     }
  206.     
  207.     function onSwRestart()
  208.     {  
  209.         // define the disconnect action
  210.         $action = new TAction(array($this'SwRestart'));
  211.         // shows a dialog to the user
  212.         new TQuestion(('Realmente deseja reniciar o Software ?'), $action);
  213.     }
  214.       
  215.     function SwRestart()
  216.     {
  217.         try
  218.         {
  219.             system("reboot software");
  220.             new TMessage('Reiniciar Software','O Software está sendo reniciado.');
  221.         }
  222.         catch (Exception $e)
  223.         {
  224.             new TMessage('error',$e->getMessage());
  225.         }
  226.     }
  227.     
  228.     function onHwRestart()
  229.     {
  230.         // define the disconnect action
  231.         $action = new TAction(array($this'HwRestart'));
  232.         // shows a dialog to the user
  233.         new TQuestion(('Realmente deseja reniciar o Hardware ?'), $action);
  234.     }
  235.   
  236.     function HwRestart()
  237.     {
  238.         try
  239.         {
  240.             system("reboot hardware");
  241.             new TMessage('Reiniciar Hardware','O Hardware está sendo reniciado.');
  242.         }
  243.         catch (Exception $e)
  244.         {
  245.             new TMessage('error',$e->getMessage());
  246.         }    
  247.     }
  248.  
  249. }
  250. ?>
JD

Olá Julio, o que está acontecendo é que no momento que você chama o setTimeout, o javascript ja registra isso no DOM, acionando o timer mesmo que vc mude de pagina assim que o timer terminar de contar ele vai executar, chamando a tela novamente.
Tente fazer o seguinte:

  1. <?php
  2.  $script = new TElement('script'); 
  3.     $script->type 'text/javascript'
  4.     $script->add("$(document).ready(function(){
  5.       window.setTimeout(function(){ 
  6.         var results = new RegExp('[\\?&]class=([^&#]*)').exec(window.location.href);
  7.         if('".__CLASS__."' == results[1] )
  8.         __adianti_load_page('engine.php?class=SystemStatusForm&method=onReload');
  9.       }, 5000);
  10.    });
  11.    ");
  12. ?>


Isso irá fazer com que a chamada da pagina ocorra somente se o usuário estiver com ela aberta, pois ao navegar para outra pagina, o dom vai executar o script porem o if não deixará que a chamada ocorra novamente.
JD

Funcionou.

Acho que entendi, dessa forma o setTimout é criado com uma checagem da classe SystemStatusForm e fazendo o onReload em caso de match. Isso?


Cara, muito obrigado.
JD

Exatamente, assim não entra em um loop infinito.
ML

Boa tarde, Jheferson Fonseca.
Estou usando a tua dica para atualizar minha tela de pendencias após alguns segundos.
Acontece que necessito abrir uma TWindow e com o SetTime ligado a tela do Twindow acaba fechando.


Como posso fazer para a TPage somente atualizar quando o Twindow nao tiver aberto?

Obrigado.
RS

no caso em vez de usar addAction para chamar o TWindow use o addActionLink assim:

$btn_deli = $this->form->addActionLink

ai resolveu e não fechou mais o Twindow