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
Joana LorenJoana Loren 

Display Related Contact's Field Values

Hi guys,

Need your help with this. How do I display the contact's Firstname, Lastname and Department if I have this query. Any help would be greatly appreciated. =)

List<Account> acctsWithContacts = [SELECT Name, (SELECT FirstName, LastName, Department FROM Contacts)
                                    FROM Account
                                    LIMIT 2];

for(Account cts : acctsWithContacts) {
    System.debug('Account Name: ' + cts.Name);
    System.debug('Contact Name: ' + cts.Contacts.FirstName + cts.Contacts.LastName);
    System.debug('Contact Department: ' + cts.Contacts.Department);
}
Best Answer chosen by Joana Loren
N M Kalesha Vali 7N M Kalesha Vali 7
Hi Lj,

Using relationship queries, you can display contact's Firstname, Lastname and Department.

Check this code.

List<Contact> con=[SELECT LastName, FirstName, Department, Account.Name FROM Contact LIMIT 2];
for(Contact c:con){    
    System.debug('Account Name:' +c.account.name);
    System.debug('Contact Name: ' +c.Lastname +', ' +c.Firstname);
    System.debug('Contact Department: '+c.department);
}

ThanQ
Kalesha Vali

 

All Answers

ManojSankaranManojSankaran

Hi,

Use this code to get the values

List<Account> acctsWithContacts = [SELECT Name, (SELECT FirstName, LastName, Department FROM Contacts)
                                    FROM Account
                                    LIMIT 100];


for(Account acc : acctsWithContacts){

for(contact cts : acc.contacts) {
    System.debug('Account Name: ' + acc.Name);
    System.debug('Contact Name: ' + cts.FirstName); //I'm getting error in this part
    System.debug('Contact Name: ' + cts.LastName);
    System.debug('Contact Name: ' + cts.Department); 
}
}

Mark it as answer if it solves your issues. 

Thanks

Manoj S

Joana LorenJoana Loren
Hi ManojSankaran, 

Thank you so much. Such a great help.
N M Kalesha Vali 7N M Kalesha Vali 7
Hi Lj,

Using relationship queries, you can display contact's Firstname, Lastname and Department.

Check this code.

List<Contact> con=[SELECT LastName, FirstName, Department, Account.Name FROM Contact LIMIT 2];
for(Contact c:con){    
    System.debug('Account Name:' +c.account.name);
    System.debug('Contact Name: ' +c.Lastname +', ' +c.Firstname);
    System.debug('Contact Department: '+c.department);
}

ThanQ
Kalesha Vali

 
This was selected as the best answer