{parts/gtag_head.html} {parts/gtag_body.html}
Conheça  A Ferramenta LowCode mais moderna e veloz para desenvolvimento PHP: Adianti Creator
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...

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (11)


FC

Tente alterar:

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


FC

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