Hi Everyone,
I want to share my experience of current problem. Basically it is the minor thing however it’s always good to share your experience with other. First Let me tell you my scenario. I have three SFDC Custom Object Call Report, Meeting Attendee and Action. Now I have to save these three object on button click on VF page.
I want to share my experience of current problem. Basically it is the minor thing however it’s always good to share your experience with other. First Let me tell you my scenario. I have three SFDC Custom Object Call Report, Meeting Attendee and Action. Now I have to save these three object on button click on VF page.
So my code
was like below:
try {
insert oCallReport;
insert oMeetingAttendee;
insert oAction;
} catch
(Exception e) {
...
}
This is still alright if there is any error occurs in the first DML insert statement as the error will be caught and the second DML insert statement won't be execute. But, what if there is a problem occurs on the second DML insert statement? This will cause some bad data in your Salesforce if the data in the “oCallReport″ should not be inserted if there is any error occurs on “oAction″.
To overcome
this issue, you can implement transaction control into your code as following:
Savepoint sp = Database.setSavepoint();
try {
insert oCallReport;
insert oMeetingAttendee;
insert oAction;
} catch
(Exception e) {
Database.rollback(sp);
}
By doing this, Salesforce will helps you to revert data back to the state before the first DML insert statement is executed. But again I got one issue that salesforce.com sets the ID of a record before the insert as you can’t set values after inserts as the object would become read-only. To overcome this issue I have created clone the record without preserving the Id and assign this clone back to the original object .Something like this:
Savepoint sp = Database.setSavepoint();
try{
insert
oCallReport;
insert oMeetingAttendee;
insert oAction;
}catch(exception
e){
Database.rollback(sp);
oCallReport = oCallReport.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 there should be no issues.
No comments:
Post a Comment