Conheça as melhorias da versão 8.0, 8.1, 8.2!
Clique aqui para saber mais
Update X Insert nos forms gerados pelo Adianti Studio Boa tarde Plabo e demais colegas! Estou utilizando o wizard do Adianti Studio para geração de formulário e listagem de uma base de dados que possui os seguinte campos: id Dicas Tudo funciona perfeitamente, resolvemos o problema com padrão iso X uft8 porém agora ao tentar atualizar um arquivo é feito um novo insert no lugar de um update, pode me ajudar? Estou analisando os códigos ...
IC
Update X Insert nos forms gerados pelo Adianti Studio  
Fechado
Boa tarde Plabo e demais colegas!

Estou utilizando o wizard do Adianti Studio para geração de formulário e listagem de uma base de dados que possui os seguinte campos:

id
Dicas

Tudo funciona perfeitamente, resolvemos o problema com padrão iso X uft8 porém agora ao tentar atualizar um arquivo é feito um novo insert no lugar de um update, pode me ajudar? Estou analisando os códigos gerados, mas não consigo localizar o problema.

Obrigada!
Atenciosamente,

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)


PD

Oi Itália,

Está usando a estratégia MAX ou SERIAL na model?

um abraço,
Pablo
IC

Olá Pablo!

Tentei das duas formas. Na última vez tentei SERIAL.

O que pode estar acontecendo?

Obrigada!
Atenciosamente,
Ilália Cristina
ES

Olá Itália, disponiblize o código pra gente tentar te ajudar melhor.

att.

Eliezer
IC

 
  1. <?php
  2. /**
  3. * DBDicasIForm Registration
  4. * @author <your name here>
  5. */
  6. class DBDicasIForm extends TPage
  7. {
  8. protected $form; // form
  9. protected $notebook;
  10. /**
  11. * Class constructor
  12. * Creates the page and the registration form
  13. */
  14. function __construct()
  15. {
  16. parent::__construct();
  17. // creates the notebook
  18. $this->notebook = new TNotebook;
  19. $this->notebook->setSize(500, 300);
  20. $scroll = new TScroll;
  21. $scroll->setSize(490, 290);
  22. $scroll->setTransparency(TRUE);
  23. // creates the table container
  24. $table = new TTable;
  25. // creates the form
  26. $this->form = new TForm('form_DBDicasI');
  27. $this->notebook->appendPage(_t('Data'), $scroll);
  28. $scroll->add($table);
  29. // add the notebook inside the form
  30. $this->form->add($this->notebook);
  31. // create the form fields
  32. $Dicas = new TText('Dicas');
  33. // define the sizes
  34. $Dicas->setSize(420, 100);
  35. // add a row for the field Dicas
  36. $row=$table->addRow();
  37. $row->addCell(new TLabel('Dicas:'));
  38. $row->addCell($Dicas);
  39. // create an action button (save)
  40. $save_button=new TButton('save');
  41. // define the button action
  42. $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));
  43. $save_button->setImage('ico_save.png');
  44. $this->form->setFields(array($Dicas,$save_button));
  45. $container = new TTable;
  46. $container->addRow()->addCell($this->form);
  47. $container->addRow()->addCell($save_button);
  48. // add the form to the page
  49. parent::add($container);
  50. }
  51. /**
  52. * method onSave()
  53. * Executed whenever the user clicks at the save button
  54. */
  55. function onSave()
  56. {
  57. echo "<script language='javascript'>alert('Passei em SALVAR form!!!!');</script>";
  58. try
  59. {
  60. // open a transaction with database 'Emagrecimento'
  61. TTransaction::open('Emagrecimento');
  62. // get the form data into an active record DBDicasI
  63. $object = $this->form->getData('DBDicasI');
  64. // form validation
  65. $this->form->validate();
  66. // stores the object
  67. $object->store();
  68. // fill the form with the active record data
  69. $this->form->setData($object);
  70. // close the transaction
  71. TTransaction::close();
  72. // shows the success message
  73. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  74. // reload the listing
  75. }
  76. catch (Exception $e) // in case of exception
  77. {
  78. // shows the exception error message
  79. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  80. // undo all pending operations
  81. TTransaction::rollback();
  82. }
  83. }
  84. /**
  85. * method onEdit()
  86. * Executed whenever the user clicks at the edit button da datagrid
  87. */
  88. function onEdit($param)
  89. {
  90. echo "<script language='javascript'>alert('Passei em EDITAR form!!!!');</script>";
  91. try
  92. {
  93. if (isset($param['key']))
  94. {
  95. // get the parameter $key
  96. $key=$param['key'];
  97. // open a transaction with database 'Emagrecimento'
  98. TTransaction::open('Emagrecimento');
  99. // instantiates object DBDicasI
  100. $object = new DBDicasI($key);
  101. // fill the form with the active record data
  102. $this->form->setData($object);
  103. // close the transaction
  104. TTransaction::close();
  105. }
  106. else
  107. {
  108. $this->form->clear();
  109. }
  110. }
  111. catch (Exception $e) // in case of exception
  112. {
  113. // shows the exception error message
  114. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  115. // undo all pending operations
  116. TTransaction::rollback();
  117. }
  118. }
  119. }
  120. ?>
</your>
IC

 
  1. <?php
  2. /**
  3. * DBDicasIList Listing
  4. * @author <your name here>
  5. */
  6. class DBDicasIList extends TPage
  7. {
  8. private $form; // registration form
  9. private $datagrid; // listing
  10. private $pageNavigation;
  11. private $loaded;
  12. /**
  13. * Class constructor
  14. * Creates the page, the form and the listing
  15. */
  16. public function __construct()
  17. {
  18. parent::__construct();
  19. // creates the form
  20. $this->form = new TForm('form_search_DBDicasI');
  21. // creates a table
  22. $table = new TTable;
  23. // add the table inside the form
  24. $this->form->add($table);
  25. // create the form fields
  26. $filter = new TEntry('Dicas');
  27. $filter->setValue(TSession::getValue('DBDicasI_Dicas'));
  28. // add a row for the filter field
  29. $row=$table->addRow();
  30. $row->addCell(new TLabel('Dicas:'));
  31. $row->addCell($filter);
  32. // create two action buttons to the form
  33. $find_button = new TButton('find');
  34. $new_button = new TButton('new');
  35. // define the button actions
  36. $find_button->setAction(new TAction(array($this, 'onSearch')), _t('Find'));
  37. $find_button->setImage('ico_find.png');
  38. $new_button->setAction(new TAction(array('DBDicasIForm', 'onEdit')), _t('New'));
  39. $new_button->setImage('ico_new.png');
  40. // add a row for the form actions
  41. $row=$table->addRow();
  42. $row->addCell($find_button);
  43. $row->addCell($new_button);
  44. // define wich are the form fields
  45. $this->form->setFields(array($filter, $find_button, $new_button));
  46. // creates a DataGrid
  47. $this->datagrid = new TDataGrid;
  48. $this->datagrid->setHeight(320);
  49. // creates the datagrid columns
  50. $id = new TDataGridColumn('id', 'id', 'right', 100);
  51. $Dicas = new TDataGridColumn('Dicas', 'Dicas', 'left', 900);
  52. // add the columns to the DataGrid
  53. $this->datagrid->addColumn($id);
  54. $this->datagrid->addColumn($Dicas);
  55. // creates two datagrid actions
  56. $action1 = new TDataGridAction(array('DBDicasIForm', 'onEdit'));
  57. $action1->setLabel(_t('Edit'));
  58. $action1->setImage('ico_edit.png');
  59. $action1->setField('id');
  60. $action2 = new TDataGridAction(array($this, 'onDelete'));
  61. $action2->setLabel(_t('Delete'));
  62. $action2->setImage('ico_delete.png');
  63. $action2->setField('id');
  64. // add the actions to the datagrid
  65. $this->datagrid->addAction($action1);
  66. $this->datagrid->addAction($action2);
  67. // create the datagrid model
  68. $this->datagrid->createModel();
  69. // creates the page navigation
  70. $this->pageNavigation = new TPageNavigation;
  71. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  72. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  73. // creates the page structure using a table
  74. $table = new TTable;
  75. // add a row to the form
  76. $row = $table->addRow();
  77. $row->addCell($this->form);
  78. // add a row to the datagrid
  79. $row = $table->addRow();
  80. $row->addCell($this->datagrid);
  81. // add a row for page navigation
  82. $row = $table->addRow();
  83. $row->addCell($this->pageNavigation);
  84. // add the table inside the page
  85. parent::add($table);
  86. }
  87. /**
  88. * method onSearch()
  89. * Register the filter in the session when the user performs a search
  90. */
  91. function onSearch()
  92. {
  93. // get the search form data
  94. $data = $this->form->getData();
  95. TSession::setValue('DBDicasI_filter', NULL);
  96. TSession::setValue('DBDicasI_Dicas', '');
  97. // check if the user has filled the form
  98. if (isset($data->Dicas))
  99. {
  100. // creates a filter using what the user has typed
  101. $filter = new TFilter('Dicas', 'like', "%{$data->Dicas}%");
  102. // stores the filter in the session
  103. TSession::setValue('DBDicasI_filter', $filter);
  104. TSession::setValue('DBDicasI_Dicas', $data->Dicas);
  105. // fill the form with data again
  106. $this->form->setData($data);
  107. }
  108. $param=array();
  109. $param['offset'] =0;
  110. $param['first_page']=1;
  111. $this->onReload($param);
  112. }
  113. /**
  114. * method onReload()
  115. * Load the datagrid with the database objects
  116. */
  117. function onReload($param = NULL)
  118. {
  119. try
  120. {
  121. // open a transaction with database 'Emagrecimento'
  122. TTransaction::open('Emagrecimento');
  123. // creates a repository for DBDicasI
  124. $repository = new TRepository('DBDicasI');
  125. $limit = 10;
  126. // creates a criteria
  127. $criteria = new TCriteria;
  128. $criteria->setProperties($param); // order, offset
  129. $criteria->setProperty('limit', $limit);
  130. if (TSession::getValue('DBDicasI_filter'))
  131. {
  132. // add the filter stored in the session to the criteria
  133. $criteria->add(TSession::getValue('DBDicasI_filter'));
  134. }
  135. // load the objects according to criteria
  136. $objects = $repository->load($criteria);
  137. $this->datagrid->clear();
  138. if ($objects)
  139. {
  140. // iterate the collection of active records
  141. foreach ($objects as $object)
  142. {
  143. // add the object inside the datagrid
  144. $this->datagrid->addItem($object);
  145. }
  146. }
  147. // reset the criteria for record count
  148. $criteria->resetProperties();
  149. $count= $repository->count($criteria);
  150. $this->pageNavigation->setCount($count); // count of records
  151. $this->pageNavigation->setProperties($param); // order, page
  152. $this->pageNavigation->setLimit($limit); // limit
  153. // close the transaction
  154. TTransaction::close();
  155. $this->loaded = true;
  156. }
  157. catch (Exception $e) // in case of exception
  158. {
  159. // shows the exception error message
  160. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  161. // undo all pending operations
  162. TTransaction::rollback();
  163. }
  164. }
  165. /**
  166. * method onDelete()
  167. * executed whenever the user clicks at the delete button
  168. * Ask if the user really wants to delete the record
  169. */
  170. function onDelete($param)
  171. {
  172. // get the parameter $key
  173. $key=$param['key'];
  174. // define two actions
  175. $action = new TAction(array($this, 'Delete'));
  176. // define the action parameters
  177. $action->setParameter('key', $key);
  178. // shows a dialog to the user
  179. new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  180. }
  181. /**
  182. * method Delete()
  183. * Delete a record
  184. */
  185. function Delete($param)
  186. {
  187. try
  188. {
  189. // get the parameter $key
  190. $key=$param['key'];
  191. // open a transaction with database 'Emagrecimento'
  192. TTransaction::open('Emagrecimento');
  193. // instantiates object DBDicasI
  194. $object = new DBDicasI($key);
  195. // deletes the object from the database
  196. $object->delete();
  197. // close the transaction
  198. TTransaction::close();
  199. // reload the listing
  200. $this->onReload();
  201. // shows the success message
  202. new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted'));
  203. }
  204. catch (Exception $e) // in case of exception
  205. {
  206. // shows the exception error message
  207. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  208. // undo all pending operations
  209. TTransaction::rollback();
  210. }
  211. }
  212. /**
  213. * method show()
  214. * Shows the page
  215. */
  216. function show()
  217. {
  218. // check if the datagrid is already loaded
  219. if (!$this->loaded)
  220. {
  221. $this->onReload();
  222. }
  223. parent::show();
  224. }
  225. }
  226. ?>
</your>
ES

Olá Itália,
veja bem, pelo que vi em seu código você criou um formulário com apenas um campo texto ("Dicas") mas não colocou em seu formulário o campo id de registro.
Se você não quer que o campo apareça no formulário basta criá-lo como hidden mas ele precisa figurar no formulário ou o método onSave não terá o parâmetro id de comparação para certificar que exista na tabela e por isso insere um novo registro.

Veja se é isso e comente por favor.

att.

Eliezer
IC

Muito obrigada Eliezer! Era isso mesmo!
ES

Disponha!
LS

Muito interessante.
Estive pensando que talvez fosse possível otimizar o código do Adianti Framework de forma que possa evitar esse erro.
PD

Oi Lando,

Algumas decisões (colocar ou não o ID no formulário) devem ser do desenvolvedor. Em alguns casos, ele desejará criar um form para inserir um registro após o outro por causa de algum requisito funcional do usuário (por exemplo).

um abraço,
Pablo
FC

A documentação, o exemplo e a comunidade do Adianti são impressionantes. Tenho tido alguns problemas mas tenho sempre encontrado um caminho para solucionar.
Todos de parabéns.
Obrigado Pablo, excelente software.