Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Product Massive Update com TCombo Oi Galera. Alguém já usou o atulizador parecido com deste exemplo: http://www.adianti.com.br/framework_files/tutor/index.php?class=ProductUpdateList Eu estou tentando usar o exemplo acima em uma FormList, só que ao invés de usar TEntry, eu estou usando TCombos. Estou com problema ao capturar o valor selecionado na combo, nesta parte do código: function onAtualiza...
GE
Product Massive Update com TCombo  
Oi

Galera.

Alguém já usou o atulizador parecido com deste exemplo:

www.adianti.com.br/framework_files/tutor/index.php?class=ProductUpda


Eu estou tentando usar o exemplo acima em uma FormList, só que ao invés de usar TEntry, eu estou usando TCombos.

Estou com problema ao capturar o valor selecionado na combo, nesta parte do código:
function onAtualizar() { $data = $this->form->getData(); $this->form->setData($data); // keep the form filled try { TTransaction::open('atividade'); foreach ($this->form->getFields() as $name => $field) { if ($field instanceof TDBCombo) { if($name == 'sistema_id_10') { print_r($field); } //var_dump($field); // print $name. ' teste '.$field->getValue().'<br/>'; $parts = explode('_', $name); $id = $parts[2]; if($parts[0] == 'ticket') { $object = new TipoAtividade($id); $object->ticket_id = $field->getValue(); //$object->store(); } if($parts[0] == 'sistema') { $object = new TipoAtividade($id); $object->sistema_id = $field->getValue(); //$object->store(); } } } new TMessage('info', 'Tipos de atividades atualizados'); TTransaction::close(); } catch (Exception $e) { // show the message new TMessage('error', $e->getMessage()); } }


a variavel $field->getValue(); vem vazia...

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)


FC

Tente alterar:

if ($field instanceof TDBCombo)
Por
if ($field instanceof TCombo)


FC
GE

Oi Felipe.

Troquei inclusive a TDBCombo por TCombo, preenchendo o conteudo com TRepository.

Tu já usou o exemplo do Jackson?

Eu vou tentar usar adaptar o arquivo dele sem as instancias no banco para ver o que estou fazendo que não consigo pegar o value do TCombo.
FC

Não usei, mas imaginei que como a TDBCombo estende TCombo poderia resolver, pelo que vi rapidamente do exemplo parece que a combo dele é manual essa é a única diferença. Deve ser algo nesse sentido tipo ser necessário percorrer o key assim como fazemos no multifield.
GE

Eu consegui implementar o código do Jackson, só que somente em uma tela com datagrid.

Eu gostaria de usar na tela em que permite a inclusao/edicao de itens na datagrid.

Dai parece q ele se perde nos forms...
GE

Eu digo em uma tela como essa:

www.adianti.com.br/framework_files/tutor/index.php?class=CompleteFor
FC

Posta seu código para analisarmos.
GE

  1. <?php
  2. /**
  3.  * TipoAtividadeFormList Registration
  4.  * @author  <your name here>
  5.  */
  6. class TipoAtividadeFormList extends TPage
  7. {
  8.     protected $form// form
  9.     protected $datagrid// datagrid
  10.     protected $pageNavigation;
  11.     protected $loaded;
  12.     
  13.     /**
  14.      * Class constructor
  15.      * Creates the page and the registration form
  16.      */
  17.     function __construct()
  18.     {
  19.         parent::__construct();
  20.         
  21.         // creates the form
  22.         $this->form = new TQuickForm('form_TipoAtividade');
  23.         $this->form->class 'tform'// CSS class
  24.         $this->form->setFormTitle('Tabela de Tipos de Atividades'); // define the form title
  25.         
  26.         // create the form fields
  27.         $nome                           = new TEntry('nome');
  28.         $id                             = new THidden('id');
  29.         // add the fields
  30.         $this->form->addQuickField('Tipo de atividade'$nome,  200, new TRequiredValidator );
  31.         $this->form->addQuickField('Cod.'$id,  50);
  32.         // create the form actions
  33.         $this->form->addQuickAction(_t('Save'), new TAction(array($this'onSave')), 'ico_save.png');
  34.         $this->form->addQuickAction(_t('New'),  new TAction(array($this'onEdit')), 'ico_new.png');
  35.         
  36.         
  37.         // creates a DataGrid
  38.         $this->datagrid = new TQuickGrid;
  39.         $this->datagrid->setHeight(320);
  40.         
  41.         $this->datagrid->disableDefaultClick();
  42.         
  43.         // creates the action button
  44.         $button1 = new TButton('action1');
  45.         // define the button action
  46.         $action_button1 = new TAction(array($this'onUpdate'));
  47.         $action_button1->setParameter('id'filter_input(INPUT_GET'id'));
  48.         $button1->setAction($action_button1'Atualizar');
  49.         $button1->setImage('ico_apply.png');
  50.  
  51.         $this->form->addField($button1);
  52.         // creates the datagrid columns
  53.         $nome         $this->datagrid->addQuickColumn('Tipo de atividade:''nome''left');
  54.         $ticket_id    $this->datagrid->addQuickColumn('Ticket:''ticket''left');
  55.         $sistema_id   $this->datagrid->addQuickColumn('Sistema:''sistema''left');
  56.         
  57.         // create the datagrid actions
  58.         $edit_action   = new TDataGridAction(array($this'onEdit'));
  59.         $delete_action = new TDataGridAction(array($this'onDelete'));
  60.         
  61.         // add the actions to the datagrid
  62.         $this->datagrid->addQuickAction(_t('Edit'), $edit_action'id''ico_edit.png');
  63.         $this->datagrid->addQuickAction(_t('Delete'), $delete_action'id''ico_delete.png');
  64.         
  65.         // create the datagrid model
  66.         $this->datagrid->createModel();
  67.         
  68.         // creates the page navigation
  69.         $this->pageNavigation = new TPageNavigation;
  70.         $this->pageNavigation->setAction(new TAction(array($this'onReload')));
  71.         $this->pageNavigation->setWidth($this->datagrid->getWidth());
  72.         
  73.         // create the page container
  74.         $container TVBox::pack$this->form$button1$this->datagrid$this->pageNavigation);
  75.         $container->style 'width:80%;max-width:900px';
  76.         $this->datagrid->style 'width:100%';
  77.         parent::add($container);
  78.     }
  79.     /**
  80.      * Load the data into the datagrid
  81.      */
  82.     function onReloadTwo() {
  83.         $this->onReload();
  84.     }
  85.     /**
  86.      * method onReload()
  87.      * Load the datagrid with the database objects
  88.      */
  89.     function onReload($param NULL)
  90.     {
  91.         try
  92.         {
  93.             TTransaction::open('atividade');
  94.  
  95.             $repository = new TRepository('TipoAtividade');
  96.             $criteria = new TCriteria;
  97.             $criteria->setProperty('order''nome asc');
  98.             $cadastros $repository->load($criteria);
  99.     
  100.             //array de tickets
  101.             $ticketItem = array();
  102.             
  103.             $cri = new TCriteria;
  104.             $cri->setProperty('order''id asc');
  105.             $repo = new TRepository('Ticket');
  106.             $tickets $repo->load($cri);
  107.             foreach($tickets as $ticket)
  108.             {
  109.                 $ticketItem[$ticket->id] = $ticket->id.' - '.$ticket->titulo;
  110.             }
  111.     
  112.             //array de sistemas
  113.             $sistemaItem = array();
  114.             
  115.             $repo = new TRepository('Sistema');
  116.             $sistemas $repo->load();
  117.             foreach($sistemas as $sistema)
  118.             {
  119.                 $sistemaItem[$sistema->id] = $sistema->nome;
  120.             }
  121.             
  122.             $this->datagrid->clear();
  123.             if ($cadastros) {
  124.                 // percorre os objetos retornados
  125.                 foreach ($cadastros as $key => $cadastro) {
  126.      
  127.                     // add an regular object to the datagrid
  128.                     $itemObj = new StdClass;
  129.            
  130.                     $itemObj->id $cadastro->id;
  131.                     $itemObj->nome $cadastro->nome;
  132.                    
  133.                     $tempId $cadastro->id;
  134.                     $tempAtiSistema $cadastro->sistema;
  135.                     $itemObj->sistema = new TCombo('sistema' $key);
  136.                     $itemObj->sistema->addItems($sistemaItem);
  137.                     $itemObj->sistema->setValue($cadastro->sistema_id);
  138.                     $itemObj->sistema->setSize(180);
  139.                     
  140.                     $tempAtividadeTicket $cadastro->ticket;
  141.                     $itemObj->ticket = new TCombo('ticket' $key);
  142.                     $itemObj->ticket->addItems($ticketItem);
  143.                     $itemObj->ticket->setValue($cadastro->ticket_id);
  144.                     $itemObj->ticket->setSize(180);
  145.      
  146.                     // adiciona o objeto na DataGrid
  147.                     $this->datagrid->addItem($itemObj);
  148.      
  149.                     $this->form->addField($itemObj->sistema); // important!
  150.                     $this->form->addField($itemObj->ticket); // important!
  151.     
  152.                     // armazenar valor dos campos no array
  153.                     $itemObj->id $tempId;
  154.                     $itemObj->sistema $tempAtiSistema;
  155.                     $itemObj->ticket $tempAtividadeTicket;
  156.      
  157.                     // converte campo de objeto para array
  158.                     $array_items[] = get_object_vars($itemObj);
  159.                 }
  160.      
  161.                 // joga array para sessao
  162.                 TSession::setValue('array_items'$array_items);
  163.             }
  164.             // finaliza a transacao
  165.             TTransaction::close();
  166.             $this->loaded true;
  167.         
  168.         }
  169.         catch (Exception $e// in case of exception
  170.         {
  171.             new TMessage('error''<b>Error</b> ' $e->getMessage()); // shows the exception error message
  172.             TTransaction::rollback(); // undo all pending operations
  173.         }
  174.     }
  175.     
  176.     
  177.     public function onUpdate($param) {
  178.  
  179.         $data $this->form->getData("TipoAtividade"); // optional parameter: active record class
  180.         // pegar os dados da sessao armazenar na variavel
  181.         $cotacao_items TSession::getValue('array_items');
  182.         // inicia transacao com o banco 'pg_ceres'
  183.         TTransaction::open('atividade');
  184.  
  185.         // put the data back to the form
  186.         $this->form->setData($data);
  187.  
  188.         $msg '';
  189.         $contAdd 0;
  190.  
  191.         foreach ($cotacao_items as $item) {
  192.             $itemObj = new StdClass;
  193.  
  194.             $itemObj->id $item['id'];
  195.             $itemObj->no $item['nome'];
  196.  
  197.             foreach ($this->form->getFields() as $name => $field) {
  198.                 // pegando valor do combo
  199.                 if ($field instanceof TCombo) {
  200.                     if ($name === ( 'sistema' $contAdd )) {
  201.                         $itemObj->sistema $field->getValue();
  202.                     }
  203.                     if ($name === ( 'ticket' $contAdd )) {
  204.                         $itemObj->ticket $field->getValue();
  205.                     }
  206.                 }
  207.             }
  208.             $contAdd++;
  209.             $cotacao_items_add[] = get_object_vars($itemObj);
  210.         }
  211.  
  212.         try {
  213.  
  214.             if ($msg == '') {
  215.  
  216.                 // percore o objeto e armazena
  217.                 foreach ($cotacao_items_add as $item) {
  218.  
  219.                     $itemObj = new TipoAtividade($item['id']);
  220.                     
  221.                     $itemObj->nome $item['nome'];
  222.                     $itemObj->sistema_id $item['sistema'];
  223.                     $itemObj->ticket_id $item['ticket'];
  224.                     
  225.                     print $itemObj->sistema_id.'<br />';
  226.                     
  227.                     // armazena o objeto
  228.                     //$itemObj->store();
  229.                 }
  230.                 $msg 'Registro salvo com sucesso!';
  231.  
  232.                 // finaliza a transacao
  233.                 TTransaction::close();
  234.             } else {
  235.                 $icone 'error';
  236.             }
  237.  
  238.             if ($icone == 'error') {
  239.                 // exibe mensagem de erro
  240.                 new TMessage($icone"Erro ao Salvar o registro!");
  241.             } else {
  242.                 // show the message
  243.                 $param = array();
  244.                 $param['id'] = filter_input(INPUT_GET'id');
  245.                 //chama o formulario com o grid
  246.                 TApplication::gotoPage('TipoAtividadeFormList''onReloadTwo'$param); // reload
  247.                 new TMessage("info"$msg);
  248.             }
  249.         } catch (Exception $e) { // em caso de exce??o
  250.             // exibe a mensagem gerada pela excecao
  251.             new TMessage('error'$e->getMessage());
  252.             // desfaz todas altera??es no banco de dados
  253.             TTransaction::rollback();
  254.         }
  255.     }
  256.     
  257.     /**
  258.      * method onDelete()
  259.      * executed whenever the user clicks at the delete button
  260.      * Ask if the user really wants to delete the record
  261.      */
  262.     function onDelete($param)
  263.     {
  264.         // define the delete action
  265.         $action = new TAction(array($this'Delete'));
  266.         $action->setParameters($param); // pass the key parameter ahead
  267.         
  268.         // shows a dialog to the user
  269.         new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  270.     }
  271.     
  272.     /**
  273.      * method Delete()
  274.      * Delete a record
  275.      */
  276.     function Delete($param)
  277.     {
  278.         try
  279.         {
  280.             // get the parameter $key
  281.             $key=$param['key'];
  282.             
  283.             TTransaction::open('atividade'); // open the transaction
  284.             $object = new TipoAtividade($keyFALSE); // instantiates the Active Record
  285.             $object->delete(); // deletes the object
  286.             TTransaction::close(); // close the transaction
  287.             
  288.             $this->onReload$param ); // reload the listing
  289.             new TMessage('info'TAdiantiCoreTranslator::translate('Record deleted')); // success message
  290.         }
  291.         catch (Exception $e// in case of exception
  292.         {
  293.             new TMessage('error''<b>Error</b> ' $e->getMessage()); // shows the exception error message
  294.             TTransaction::rollback(); // undo all pending operations
  295.         }
  296.     }
  297.     
  298.     /**
  299.      * method onSave()
  300.      * Executed whenever the user clicks at the save button
  301.      */
  302.     function onSave()
  303.     {
  304.         try
  305.         {
  306.             TTransaction::open('atividade'); // open a transaction with database
  307.             
  308.             // get the form data into an active record TipoAtividade
  309.             $object $this->form->getData('TipoAtividade');
  310.             $this->form->validate(); // form validation
  311.             $object->store(); // stores the object
  312.             $this->form->setData($object); // fill the form with the active record data
  313.             TTransaction::close(); // close the transaction
  314.             
  315.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved')); // success message
  316.             $this->onReload(); // reload the listing
  317.         }
  318.         catch (Exception $e// in case of exception
  319.         {
  320.             new TMessage('error''<b>Error</b> ' $e->getMessage()); // shows the exception error message
  321.             TTransaction::rollback(); // undo all pending operations
  322.         }
  323.     }
  324.     
  325.     /**
  326.      * method onEdit()
  327.      * Executed whenever the user clicks at the edit button da datagrid
  328.      */
  329.     function onEdit($param)
  330.     {
  331.         try
  332.         {
  333.             if (isset($param['key']))
  334.             {
  335.                 
  336.                 $key=$param['key']; // get the parameter $key
  337.                 TTransaction::open('atividade'); // open a transaction with the database
  338.                 $object = new TipoAtividade($key); // instantiates the Active Record
  339.                 $this->form->setData($object); // fill the form with the active record data
  340.                 TTransaction::close(); // close the transaction
  341.             }
  342.             else
  343.             {
  344.                 $this->form->clear();
  345.             }
  346.         }
  347.         catch (Exception $e// in case of exception
  348.         {
  349.             new TMessage('error''<b>Error</b> ' $e->getMessage()); // shows the exception error message
  350.             TTransaction::rollback(); // undo all pending operations
  351.         }
  352.     }
  353.     
  354.     /**
  355.      * method show()
  356.      * Shows the page e seu conteúdo
  357.      */
  358.       function show() {
  359.         if (filter_input(INPUT_GET'method') == 'onReloadTwo') {
  360. //            $this->onReloadTwo();
  361.         } else {
  362.             $this->onReload();
  363.         }
  364.         parent::show();
  365.     }
  366. }
  367. ?>
</your>
FC

O erro seu está no onSave certo ?

Imagino que nessa linha ele está trazendo varios id´s por causa do onReload, por isso ocorre o erro.
$object = $this->form->getData('TipoAtividade');

Se estiver certo altera para
$object = $this->form->getData();




GE

tb da erro...
o problema eh manter as duas edições (tanto na datagrid quanto no formulario para criar um novo item ou editar um item da listagem)
JA

  1. <?php 
  2.   /**
  3.      * Run before the datagrid is loaded
  4.      */
  5.     public function onBeforeLoad($objects$param)
  6.     {
  7.         // update the action parameters to pass the current page to action
  8.         // without this, the action will only work for the first page
  9.         $saveAction $this->saveButton->getAction();
  10.         $saveAction->setParameters($param); // important!
  11.         
  12.         $gridfields = array( $this->saveButton );
  13.         
  14.         foreach ($objects as $object)
  15.         {
  16.             $object->status_widget = new TDBCombo('status''db_academico''Status''id''description');
  17.             $object->status_widget->setValue$object->status );
  18.             $object->status_widget->setSize(120);
  19.             $gridfields[] = $object->status_widget// important
  20.         }
  21.         
  22.         $this->formgrid->setFields($gridfields);
  23.     }
  24. ?>