function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
A.ZaykovA.Zaykov 

First error: Record Currently Unavailable: The record you are attempting to edit, or one of its related records, is currently being modified by another user. Please try again.

Hello,

The business requirement is to have a lookup relation ship between a Contract and Opportunity. A field on the opportunity must get the SUM of a custom field on the Contracts which belong to the opportunity.

On mass update, I get an error "first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record"

After I lock the Account record, I get "First error: Record Currently Unavailable: The record you are attempting to edit, or one of its related records, is currently being modified by another user. Please try again."
 
public class contractRollUpCLASS {
    @future
    public static void calculate(Set<Id> recordIds) {
  
    List<Contract> contrList = [SELECT Id, AccountId, Renewal_Opportunity__c FROM Contract WHERE Id IN : recordIds];
    Set<Id> oppIds = new Set<Id>();
    Set<Id> accIds = new Set<Id>();
    
    for(Contract con : contrList) {
        oppIds.add(con.Renewal_Opportunity__c);
        accIds.add(con.AccountId);
        
    }
        
//lock the account
    List<Account> accList = [SELECT Id FROM Account WHERE Id IN : accIds FOR UPDATE];
    
    
    //Map will contain one Opportunity Id to one sum value.
    map<Id, Double> OpportunityMap = new Map<Id,Double>();
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    //aggregate result.
    for(AggregateResult q : [SELECT Renewal_Opportunity__c, SUM(Latest_PD_Renewal_Amount__c) sumLatest FROM Contract WHERE Renewal_Opportunity__c IN : oppIds AND Latest_PD_Renewal_Amount__c != null GROUP BY Renewal_Opportunity__c]) {
  
        OpportunityMap.put((Id)q.get('Renewal_Opportunity__c'),(Double)q.get('sumLatest'));
    }
    
    for(Opportunity opp : [SELECT Id, Annual_Maintenance_Value__c, AccountId FROM Opportunity WHERE Id IN : oppIds]) {
 
        Double sumLatestPD = OpportunityMap.get(opp.Id);
        opp.Annual_Maintenance_Value__c = sumLatestPD;
        oppsToUpdate.add(opp);     
    }    

        update oppsToUpdate;   

    }
}


Any ideas how I can bypass this issue?
Thanks,

Angel

v varaprasadv varaprasad
Hi Angel,

what is the use future annotation here?. Please remove it and check once.


Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com