Monday, April 22, 2013

Access all the fields of a related object instantly after insert.

Hi guys, few days back while writing test code for my class I found a weird problem with an awesome solution.

The scenario was, I have inserted an Account 'My Company' and on next line inserting Contact associating it with this Account 'My Company' by just providing an Account id of an Account 'My Company'.

Now, I was expecting when I debug an Contact.Account.Name I will get 'My Company' but was surprised to see 'Null' because, I have already linked my Contact to an Account. I was getting Account Id of that Account in debug then why I can't access Account Name or any other Account field except Id.

To check this out, just paste the below code in your developer console:

 Account objAccount = new Account( Name = 'My Company',  
                                   Website = 'www.mycompany.com'  
                                   );  
 insert objAccount;
   Contact objContact = new Contact( FirstName = 'Praful',                                    LastName = 'Gadge',                                    AccountId = objAccount.Id                                    );   insert objContact;
    //objContact.Account = objAccount;
   system.debug('----objContact.AccountId----'+objContact.AccountId);   system.debug('----objAccount.Name----'+objAccount.Name);   system.debug('----objContact.Account.Name----'+objContact.Account.Name); 

After digging for many hours we got an answer that we have only assigned AccountId to an Contact.AccountId but all other fields of that Account are not yet connected/related to Contact. To connect all fields of a Contact to the Account we can directly associate an object to the related object, like:

objContact.Account = objAccount;

Now we can access all the fields of an Account. To check this uncomment a commented line in the above code.

It means we can associate a whole object to a related object to access all its fields instantly after an insert DML.