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
IX Salesforce AdminIX Salesforce Admin 

Trigger update child account field from parent

Hello,
On accounts we have a field called Category, that field is a Picklist. I would like to create a tirgger to update child accounts Category field with the value from parent account Category field.
This is what I have so far:
 
trigger updateCategoryFromParent on Account (after insert, after update) {

    List<Account> accList = new List<Account>();

    for (Account ac : Trigger.new) {
        if(ac.ParentId != null){
            Account ap = new Account();
            account au = new Account(Id = ac.Id);
            ap.Id = ac.ParentId;
            au.Category__c = ap.Category__c;
            accList.add(au);
        }
    }
    update accList;
}

 
Best Answer chosen by IX Salesforce Admin
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
trigger updateCategoryFromParent on Account (before insert, before update){

	Set<ID> setParentId = new Set<Id>();
    for (Account ac : Trigger.new) {
        if(ac.ParentId != null){
			setParentId.add(ac.ParentId);
		}
	}
	
	Map<Id,Account> mapParentAcc = new Map<Id,Account>([ SELECT id,Category__c FROM Account WHERE id in:setParentId ]);
    for (Account ac : Trigger.new) {
        if(ac.ParentId != null && mapParentAcc.containsKey(ac.ParentId) )
		{
            ac.Category__c = mapParentAcc.get(ac.ParentId).Category__c;
        }
    }
}

Try to use before event. To Avoid mulitple DML

Let us know if this will help you
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
trigger updateCategoryFromParent on Account (before insert, before update){

	Set<ID> setParentId = new Set<Id>();
    for (Account ac : Trigger.new) {
        if(ac.ParentId != null){
			setParentId.add(ac.ParentId);
		}
	}
	
	Map<Id,Account> mapParentAcc = new Map<Id,Account>([ SELECT id,Category__c FROM Account WHERE id in:setParentId ]);
    for (Account ac : Trigger.new) {
        if(ac.ParentId != null && mapParentAcc.containsKey(ac.ParentId) )
		{
            ac.Category__c = mapParentAcc.get(ac.ParentId).Category__c;
        }
    }
}

Try to use before event. To Avoid mulitple DML

Let us know if this will help you
 
This was selected as the best answer
IX Salesforce AdminIX Salesforce Admin
Thank you Amit! This worked great!
IX Salesforce AdminIX Salesforce Admin
Amit,
I can't deploy thi without test coverdage. Would you be able to provide an example of a test for this trigger?