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
SLockardSLockard 

Querying All Contacts from One Account

Hi, I can' t get a simple SOQL query to work, which tries to get all the contacts from a certain account.

Here is my sample code:

 

trigger triggerDNC on Contact (before update) 
{
    //Assign the context before and after the change into a Map
    Map<Id,Contact> newContactMap = Trigger.newMap;
    Map<Id,Contact> oldContactMap = Trigger.oldMap;

    //Loop through the map
    for(Id contactId:newContactMap.keySet())
    {
         Contact myNewContact = newContactMap.get(contactId);
         Contact myOldContact = oldContactMap.get(contactId);
		 
		 // myNewContact.Account.Name DOESNT WORK HERE ?
		 
		 List<Contact> cons= 
              [SELECT Contact.Name, Contact.Phone, Contact.DoNotCall, Contact.Account.Name FROM Contact
                   WHERE Contact.Id!= :myNewContact.Id
                   AND Contact.Account.Id = :myNewContact.Account.Id]; // this doesnt filter out correctly
                         
               for (Contact con: cons) 
               {
                   // con.Account.Name WORKS HERE !!?
               }
                
               update cons;
	} 
}

 I can't access myNewContact.Account.Name or myNewContact.Account.Id, so I can't find a way to get only the contacts from the same account as the one in the trigger.

Any help / feedback would  be greatly appreciated .. thanks.

Best Answer chosen by Admin (Salesforce Developers) 
sornasorna

Instead of using Contact.Account.Id, use Contact.AccountId in both the places... Because trigger.newmap and oldmap will only have access to contact fields and cross object fields like account.id or account.name will be null....

All Answers

sornasorna

Instead of using Contact.Account.Id, use Contact.AccountId in both the places... Because trigger.newmap and oldmap will only have access to contact fields and cross object fields like account.id or account.name will be null....

This was selected as the best answer
SLockardSLockard

Thank you for the quick response. I knew it would be such an easy fix, but I'm new and didn't know that about trigger.newMap.