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
AprilVAprilV 

Update Account Name on Case Detail based on value selected on another field on case record

I would like to update the Account Name field on the case based on what was input for the case's Opportunity lookup field (custom lookup field, field name is Opportunity__c). I would like to update the Account Name field on the case to the selected Opportunity's Account.

I am not familiar enough with apex triggers to get this to work. If anyone can offer me some sample code to get me started, I would greatly appreciate it.

Best Answer chosen by Admin (Salesforce Developers) 
joshbirkjoshbirk

 

trigger UpdateCaseAccountName on Case (before insert, before update) {

	List<Id> oppids = new List<Id>();
	Map<Id,Id> oppmap = new Map<Id,Id>();
	for(Case c : Trigger.new) {
		oppids.add(c.Opportunity__c);
	}
	List<Opportunity> opps = [SELECT Id, AccountId from Opportunity where ID IN :oppids];
	for(Opportunity o : opps) {
		oppmap.put(o.Id,o.AccountId);
	}
	
	for(Case c : Trigger.new) {
		if(c.Opportunity__c != null) {c.AccountId = oppmap.get(c.Opportunity__c);}
	}

}

 

Little trickier than it sounds because you need to pull the related information into the trigger in a manner that will remain bulkified - so it's better to resist the temptation to throw SOQL at the problem.  Early test, this seems to work, and only requires one SOQL statement.

 

HTH

 

 

All Answers

joshbirkjoshbirk

 

trigger UpdateCaseAccountName on Case (before insert, before update) {

	List<Id> oppids = new List<Id>();
	Map<Id,Id> oppmap = new Map<Id,Id>();
	for(Case c : Trigger.new) {
		oppids.add(c.Opportunity__c);
	}
	List<Opportunity> opps = [SELECT Id, AccountId from Opportunity where ID IN :oppids];
	for(Opportunity o : opps) {
		oppmap.put(o.Id,o.AccountId);
	}
	
	for(Case c : Trigger.new) {
		if(c.Opportunity__c != null) {c.AccountId = oppmap.get(c.Opportunity__c);}
	}

}

 

Little trickier than it sounds because you need to pull the related information into the trigger in a manner that will remain bulkified - so it's better to resist the temptation to throw SOQL at the problem.  Early test, this seems to work, and only requires one SOQL statement.

 

HTH

 

 

This was selected as the best answer
AprilVAprilV

Wow, this is so great! I really appreciate you taking the time to help me out!

 

It works great in intitial tests!