Monday 22 August 2016

Prevent records from being edited by multiple users at same time

When 2 users start editing the same record, the first user who saves the record wins, and the other user will lose the changes with an error message similar to “The record you were editing was modified by *someone* during your edit session. Please re-display the record before editing again.”
This could be an inconvenient as any user who opened the record for editing will lose his changes if he/she doesn’t hit Save quick enough.
To prevent the record from being edited when the first user opens it for editing, you can implement the following 4 steps:


  • Create a Date/Time custom field LastEditTimeStamp. This field will store the time-stamp when the record was opened for editing.
  • Create a custom detail page button with behavior Execute JavaScript to prevent editing record during the period when it is edited by some other user.(a period of 5 minutes so that no one can keep the record locked indefinitely).
  • If the LastEditTimeStamp is not blank and difference between LastEditTimeStamp  and current time is more than 5 minutes, update the LastEditTimeStamp field with current time and redirect to the record edit page.

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
// prepare account for updating the last edit date time
var accountObj = new sforce.SObject( "Account" );
accountObj.id = '{!Account.Id}';
var lastModifiedUser = '{!Account.LastModifiedById}';
var loggedInUser = '{!$User.Id}';
var lastEdit = new Date('{!Account.LastEditTimeStamp__c}');
var dateNow = new Date('{!Now()}');
var timeDiff = dateNow.getTime() - lastEdit.getTime();
var allowEdit = 'No';
if(lastModifiedUser != loggedInUser){
   if(timeDiff < 30000){
      alert('The record is locked for editing by another user. Please try after some time.')
      window.location.href = '/{!Account.Id}';
   }else{
      allowEdit = 'Yes';
   }
}else{
   allowEdit = 'Yes';
}
if(allowEdit == 'Yes'){
   var dtNow = new Date();
   var nowInJSON = dtNow.toJSON();
   accountObj.Last_Edit_Date_Time__c = nowInJSON;
   // update the account
   var result = sforce.connection.update([accountObj]);
   window.location.href = '/{!Account.Id}/e';
}
  • Replace the standard Edit button with custom Edit button on page layout.
Now if an user clicks Edit, it will set the Last Edit Time Stamp. JavaScript code will prevent updates to the record from anyone else during the next 5 minutes. If another user attempts to Edit the same record, it will prompt below alert.