Resolving the Cannot specify ID in an insert call error using database.savepoint and database.rollback

Sharing something interesting while using database.savepoint and database.rollback in the apex code.

The scenario is:
1) Set a database save point with Apex
2) Insert a record with Apex
3) Some type of validation error prevents the record from being inserted
4) Using a try-catch statement catch the error and display it to user
5) Roll back to your Database savepoint
6) Allow the user to fix the error.
7) When the save occurs the second time I would receive this error: “cannot specify Id in an insert call

This problem occurs because database.rollback will remove the inserted record from the database but doesn't resets the variable. So when we try to insert again after fixing the error, the variable still contains an id(even though there is no record with the id) and hence the error is thrown.

This issue can be resolved using the following code:

Savepoint sp = Database.setSavepoint();
try
{                                
   insert object
;
    }catch(exception e){
                Database.
rollback(sp);
                object 
= object.clone(false);
                return 
null;                                 

                       } 

The false parameter in the clone method makes an exact copy of the object without preserving the Id. So the next time the user attempts to save, the Id is null and the record gets inserted

Comments

Popular posts