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
jonpilarski1.3914448382645588E12jonpilarski1.3914448382645588E12 

How to see Account field in Contact trigger logic

Hi !

I have a simple test method which creates an Account and a Contact. A trigger on Contact which sets a field based on the Account's BillingState. Problem is when the trigger fires the Billing state evelautes to null. I cannot understand as to why. Here is test method setting these up. When I query contact object in test method I can see the BillingState, however.

test method:

static testMethod void validate() {
    
        Test.startTest();
        
        account[] accounts = new account[]{
        new account(name='highschool',BillingState='CA',BillingPostalCode='92100') };

        insert accounts;

        contact[] contacts = new contact[] {
        new contact(LastName='Sand10',TargetX_SRMb__Student_Type__c='New Freshman',accountId=accounts[0].id)};

        insert contacts;
        Test.stopTest();

        List<contact> con = [select id, LastName, FirstName,TargetX_SRMb__Student_Type__c,TargetX_SRMb__College__c,account.BillingState, account.billingPostalCode,Territory_Assignments__c from Contact];
        
        for(Contact e: con) {
   
        System.debug('Last name.......... '+e.lastname+'  State '+e.account.BillingState);   // this actually DOES return BillingState
}

In Contact trigger logic:

...
if(String.isNotBlank(c.TargetX_SRMb__Student_Type__c) ){
     system.debug('lastname in trigger: '+c.lastname+' state is '+c.account.billingState);    // this shows null for BillingState
        //look at territory state
        if(String.isNotBlank(c.Account.BillingState)){
              system.debug('not blank');                                    // never get here
.....   
Thanks,
Jon
bob_buzzardbob_buzzard
Triggers don't retrieve the full object graph, so any related objects won't be populated - all you'll have is the related object id. If you want to access fields from a related object, you'll need to query this back from the database youself before continuing with your code.