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
sksfdc221sksfdc221 

Trigger to update child with new parent id

I have a requirement where the child record (Account_Transfer_Policy__c) should be updated with new Parent record (Account_Transfer__c) if the district_from__c of current parent do not match with district_Acct_Code__c of child record.

This new parent update will be done when District_from__c of any Account Transfer record and District_Acct_Code__c of child matches

Now, below is my trigger
trigger ATwithATP on Account_Transfer_Policy__c (after insert) {
    Map<Id,Account_Transfer__c> mapIDWithAccount = new Map<Id,Account_Transfer__c>();
    Map<string,Account_Transfer__c> mapATwithATP = new Map<string,Account_Transfer__c>();

    for (Account_Transfer__c acc : [select id,District_From__c from Account_Transfer__c where District_From__c != Null and createddate = TODAY ORDER BY createddate DESC ]){
       
        mapATwithATP.put(acc.District_From__c,acc);
    }
    
    list<Account_Transfer_Policy__c> ATP = new list<Account_Transfer_Policy__c>();
    for(Account_Transfer_Policy__c c : trigger.new){
        
        if(c.Account_Transfer__c !=null && c.Policy__r.District_Acct_Code__c != c.Account_Transfer__r.District_From__c){
            if(mapATwithATP.containsKey(c.Policy__r.District_Acct_Code__c)){
                c.Account_Transfer__c = mapATwithATP.get(c.Policy__r.District_Acct_Code__c).Id;
            }
        }
        ATP.add(c);
       
    }
    update ATP;
}

I'm not getting any error but the child is not updating with new parent record. Can anyone please suggest any changes in my code if I missed anything.
ANUTEJANUTEJ (Salesforce Developers) 
Hi sksfdc,

Have you tried checking if the values you are getting if they are proper and if the map that we have prepared if is correct?

Regards,
Anutej
sksfdc221sksfdc221
Yes Anutej.
In the query in line 15, I'm getting around 10-15 records which is working perfectly.

But when these records got inserted, the Account Transfer Policy is not getting updated to another parent id (Account Transfer) when the current parent district field doesn't match. 

Out of those 15 records, one will be having the same district value as child record and that record has to be the parent of this Account Transfer policy record. But this trigger is not working in that direction and I'm not getting any error either.