Create one percentage field on Account with API Name Discount__c. Task : Create one apex trigger on account so that whenever the value of Discount__c field is update on parent account, the same value must be updated on the child accounts of the parent.

Here what i have done till now i'm sharing the code but i'm not able to contain the error

A non foreign key field cannot be referenced in a path expression: ParentId

Here is my code --

trigger testAccountTrigger on Account (after update) {
    List<Id> acctId = new List<Id>();
    List<Account> acctToUpdate = new List<Account>();
    for(Account acc : Trigger.new) {
    for(Account a : [select id,Discount__c from Account where id in: acctId]) 
        for(Account ac : trigger.new) 
            a.Discount__c = ac.ParentId.Discount__c;
    if(acctToUpdate.size()>0) {
        update acctToUpdate;

how to solve this issue

1 Answer 1


This is the pattern I would use here:

trigger testAccountTrigger on Account (after update) {
    Map<Id, Account> parents = new Map<Id, Account>();

    // Only care about changes to this specific field
    for (Account a : Trigger.new) {
        Account old = Trigger.oldMap.get(a.Id);
        if (a.Discount__c != old.Discount__c) {
            parents.put(a.Id, a);

    if (parents.size() > 0) {

        Account[] updates = new Account[] {};

        // Query the children
        for (Account child : [
            select Id, ParentId, Discount__c
            from Account
            where ParentId in :parents.keySet()
        ]) {
            // Only update if necessary, though probably always necessary
            Decimal parentDiscount = parents.get(child.ParentId).Discount__c;
            if (child.Discount__c != parentDiscount) {
                 child.Discount__c = parentDiscount;

        update updates;

Note that this approach could run into trouble for very deep trees i.e. trees that have many layers of parent/child relationships because the update will cause the same trigger to be run again per layer.

  • getting error while editing parent account testAccountTrigger: execution of AfterUpdate caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account.ParentId Trigger.testAccountTrigger: line 24, column 1 Nov 14, 2020 at 8:12
  • @soumyaranjantripathy That field was missing from select Id, Discount__c; I've changed it above to select Id, ParentId, Discount__c.
    – Keith C
    Nov 14, 2020 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.