+ Start a Discussion

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() {
        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;

        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
              system.debug('not blank');                                    // never get here
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.