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
ElkayElkay 

Cross Object Trigger - AddError

Hi there,

I have an after insert trigger on child object the updates a field in parent object.  I am using Database.saveresult[] uResult = database.update(rAccList,false); to update the account records and in case of failure at the ID of failed accounts in a Map. Search for child object wherein account.Id is in the failed map and then use AddError. This functionality works fine, however this results in the failure of insertion of all child records where accountId is in the Map. Is there a way to get the Id of the child record that caused the validation failure in the parent object and then use addError only for that child record.

Thank you.
Elkay
ShashForceShashForce
Can you try something like this and check if it works for you? Test_custom__c is a child custom object and test__c is a custom field on parent Account, and I am updating the name of the child record into the custom field in account.

trigger accValidation on Test_Custom__c (before insert, before update, after insert, after update) {
    list<account> rAcclist = new list<account>();
    map<Id, test_custom__c> accCustomMap = new map<Id, test_custom__c>();
    for(test_custom__c t:trigger.new){
        //accIds.add(t.Lookup_to_Account__c);
        accCustomMap.put(t.Lookup_to_Account__c,t);
    }
    for(account a:[select Id, test__c from account where Id IN :accCustomMap.keySet()]){
        account ac = new account();
        ac.Id = a.Id;
        ac.test__c = accCustomMap.get(a.Id).name;
        rAcclist.add(ac);
    }
    database.saveresult[] uResult = database.update(rAcclist,false);
    for(database.saveresult sr: uResult){
        if(!sr.isSuccess()){
            trigger.newMap.get(accCustomMap.get(sr.getId()).Id).addError('testing');
        }
    }
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank