Lançado Adianti Framework 7.6!
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,

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)


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