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
Trevor ViallTrevor Viall 

How do I check an object within an object?

This is probably a fairly simple question but, I am still fairly new. How do I check an object within an object? I am making a trigger on the Account object and one of the requirements is to check the contacts email and phone and compair it with the accounts email and phone. How exactly do I check this information while setting the trigger to account?

snippit of the code:

public with sharing class AccountTriggerHandler {
    public static void afterupdate(Map<Id, Account> oldRecs, list <Account> newrecs){        
        //Checks for changes in account
        Integer task =0;
        for (account a: newrecs){
            if (a.Email__c == (a.Contact__c).Email__c)
            {a.EmailCheck__c = true;
             task++;}
            if (a.Phone == (a.Contact__c).Phone)
            {a.PhoneCheck__c = true;
            task++;}
Best Answer chosen by Trevor Viall
David Zhu 🔥David Zhu 🔥
Account is one to many relationship to Contact Object. You may use the following code as reference.
 
public with sharing class AccountTriggerHandler {
    public static void afterupdate(Map<Id, Account> oldRecs, list <Account> newrecs){        
        //Checks for changes in account
        Integer task =0;

        Map<Id,Account> newAccountMap = new Map<Id,Account>([select id,(select phone,email from contacts) from account where Id in :oldRecs.keyset()]);

         for (account a: newrecs){
            List<Contact> contacts = newAccountMap.get(a.Id).contacts;
            if (contacts == null){
                continue;
            }
            for (Contact c : a.contacts) {
                if (a.Email__c == c.Email){
                    a.EmailCheck__c = true;
                    task++;
                }
                if (a.Phone == c.Phone){
                    a.PhoneCheck__c = true;
                    task++;
                }
            }
        }
    }
}