0

I have contact object and one of its field is Account which is in lookup relationship.

In one of contact trigger i have used

for(Contact con: Trigger.New)
{
       //code
}

If I try to print con.Account.name it is showing null even though account has name. what would be the cause.

Actually can we access like con.Account.name??

Regards, Gayathri

2 Answers 2

2

No in trigger.New you can't access parent object fields directly. You need to query them to access..

for example.

Set<Id> accId = new Set<Id>();
for(Contact con: Trigger.New)
{
       accId.add(con.accountId);
}
List<Account> accList = [select id, name from account WHERE Id IN: accId ]; //access name from this list
4
  • I have tried that way as well I have queried and put that in map but it is not working
    – user27888
    Commented Feb 3, 2016 at 9:35
  • @user27888 what is not working her? share your updated code. Commented Feb 3, 2016 at 9:36
  • Based on Accountname and contact field's condition I have sending actionid to sap. Actionid not flowing to SAP if I add extra condition of Account name from map
    – user27888
    Commented Feb 3, 2016 at 9:39
  • @user27888 can you share your update code. Commented Feb 3, 2016 at 9:43
0

Alternatively, you can do the following:

List<Contact> lst_contacts = 
    [SELECT Id, Name, Account.Name
    FROM Contact
    WHERE Id IN :Trigger.new];

// Now access account field directly from the contacts
For (Contact myContact : lst_contacts) {
    System.debug('Account Name = ' + myContact.Account.Name);
}

But I personally prefer the first approach given by Tushar. In my experience, it is better to use collections rather than querying parent objects. But it is an option.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .