+ Start a Discussion

Trigger for highest parent is not working on update and delete

Hi ,
I have written a trigger on Account to get the highest parent.  The trigger should also get few fieldvalues from highest parent and update the child record.

Ex1:  P1-->P2-->P3
P2 & P3 should get details of P1.  This is working fine.

Ex2: When I create another parent P11 and restructure it as below
P2 & P3 should get updated with details of P11.  Only P2 is getting updated but not P3. P3 is still having the old parent(P1) details.

When I delete a parent P11, P3 should get updated to P2 details.  This is not happening. P3 is still having the old parent(P1) details.

Here is my trigger code

trigger UpdateHighestParent on Account (before insert, before update) {
    Map<Id, Id> accountParentIdMap=new Map<Id, Id>();
     Map<Id, Id> parentIdMasterIdMap=new Map<Id, Id>();
       List<Account> nonParentAccounts=[select id, parentId from Account where parentId!=null];
    for(Account acc: nonParentAccounts){
        accountParentIdMap.put(acc.Id, acc.ParentId);
    List<Id> masterAccountIds=new List<Id>();
    //iterate over all accounts in trigger
    for(Account curAccount: Trigger.New){
            Id parentId=curAccount.ParentId;
            while(accountParentIdMap.get(parentId)!=null){ //find master account
            parentIdMasterIdMap.put(curAccount.ParentId, parentId);
     //get global Master Accounts information
     Map<Id, Account> globalMasterAccountsMap=new Map<Id, Account>([select id, Name, Account_ID__c, DunsNumber, parentId from Account where parentId=null and id in:masterAccountIds ]);
     //iterate over all accounts in trigger
    for(Account curAccount: Trigger.New){
            Id masterId=parentIdMasterIdMap.get(curAccount.ParentId);
                Account masterAccount= globalMasterAccountsMap.get(masterId);
            {   //system.debug('Else..' + curAccount.Name +'-curAccount.Account_ID__c-' + curAccount.Account_ID__c + '-curAccount.DunsNumber-' + curAccount.DunsNumber);

Let me know what I have to change in my code.