+ Start a Discussion
TBouscalTBouscal 

"Can't use a static reference for sObject fields"

How do I access the value of an account field from a Case trigger?  This code produces the above error when I type it in but still saves.  When the test runs the debug message shows the case.accountid field has a value but the case.account.id does not.
 
public static testmethod void testSuccess(){
        Account myAcct = createAccount();
        Contact myCont = createContact(myAcct);
        Case myCase = createCase(myAcct,myCont);
        System.debug('*** Case.Accountid = ' + myCase.accountid + ' Case.Account.Id=' + myCase.Account.Id);
        myCase.Status='Closed';
        update myCase; 
        
    }

 
Best Answer chosen by TBouscal
Glyn Anderson 3Glyn Anderson 3

AccountId is a field on the Case record, so "myCase.AccountId" will have a value in the trigger - records in a trigger have all their field values, as if you queried the record and selected all the fields.

Account is a parent relationship on Case.  If you were to query the Case record and select Account fields using the Account parent relationship, you would access them using syntax like "myCase.Account.Id".  "myCase.Account" is a reference to the parent Account record that is returned by the query.  BUT, in a trigger, you only get the Case record, not any of its related records.  So you can't access fields across parent relationships unless you query the records on your own.

I like to use a technique where I query the additional fields I need into a collection called "relatedData".  Then whenever I need something across a relationship, it's in there.

<pre>
public trigger MyCaseTrigger on Case ( before update )
{
    Map<Id,Case> relatedData = new Map<Id,Case>
    (   [   SELECT  Id, Account.Id, Account.Name, RecordType.DeveloperName,
                    (   SELECT  AccountId, Roles
                        FROM    AccountContactRelations
                    )
            FROM    Case
            WHERE   Id IN :Trigger.new
        ]
    );

    for ( Case myCase : Trigger.new )
    {
        Case myRelatedData = relatedData.get( myCase.Id );
        System.debug( '>>> ' + myCase.AccountId + '  ' + myRelatedData.Account.Id );
    }
}
</pre>