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
DaveGDaveG 

Not updating other records after update

I am new to apex and I can't get my code to work.  When a new record is inserted, any existing records should have the Current__c field cleared. This seems to be working.

I also want to udpdate other existing records when a existing record is updated. So if a user checks the Current field, clear the Current field on the other records. What am I doing wrong here?
 
trigger UpdateCurrent on Risk_Assessment__c (before insert,before update) {

List<Risk_Assessment__c> riskList = new List<Risk_Assessment__c>();

Set<Id> setAccIds=new Set<Id>();

 if (Trigger.isInsert) {
        For(Risk_Assessment__c riskObj : trigger.new){
            if(riskObj.Current__c){
              setAccIds.add(riskObj.Account__c);
            }        
        }
}


List<Risk_Assessment__c> Risks = [SELECT Id, Name, Account__c,Current__c FROM Risk_Assessment__c where Account__c In :setAccIds];

// For loop to iterate through all the queried Account records
for(Risk_Assessment__c risk: Risks){
 if(risk.Current__c == True)
        risk.Current__c = False;
        riskList.add(risk);
}
update riskList;

}

 
DaveGDaveG
I think I figured it out.  It seems to be working but not sure if can be optimized?
trigger UpdateCurrent on Risk_Assessment__c (before insert,before update) {

Map<Id, Risk_Assessment__c> mapRAObjs = new Map<Id, Risk_Assessment__c>();
List<Risk_Assessment__c> riskList = new List<Risk_Assessment__c>();

Set<Id> setAccIds=new Set<Id>();
        For(Risk_Assessment__c riskObj : trigger.new){
            if(riskObj.Current__c){
              setAccIds.add(riskObj.Account__c);
              mapRAObjs.put(riskObj.Id, riskObj);
            }        
        }
		
List<Risk_Assessment__c> Risks = [SELECT Id, Name, Account__c,Current__c FROM Risk_Assessment__c where Account__c In :setAccIds];

	//For loop to iterate through all the queried Account records
	for(Risk_Assessment__c risk: Risks){
		if(mapRAObjs.containsKey(risk.Id)==False){
		 if(risk.Current__c == True)
				risk.Current__c = False;
				riskList.add(risk);
		}
	}
	update riskList;
}