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
sampathawaduge sameerasampathawaduge sameera 

Updating contacts from account

Hi,

I am trying to update contact's phone by querying the account , But it gives me following error

"A non foreign key field cannot be referenced in a path expression: Contacts"

try
{
    Account a=[select name,(select name from contacts ) from account];
    a.name='Dialog';
    a.contacts.phone=123;
    
    update a;
    update a.Contacts;
}
catch(DmlException e)
{
    System.debug(e.getMessage());
}
Best Answer chosen by sampathawaduge sameera
Rahul.MishraRahul.Mishra
Hi,

You are getting error because ac.contacts will return the list of contact and you are trying to access .phone from list<Contact>. To access the phone field you have iterate the returned contact list , below is the updated trigger for you:
 
trigger caseDelete on Case(after insert) {

try
{   List<Contact> lstContacts = new List<Contact>();
    Account a=[select name,(select name from contacts ) from account limit 1];
    a.name='Dialog';
    
    for (Contact con : a.Contacts) {
       lstContacts.add(new Contact(Id = con.Id, Phone = '123'));
    }
    
    update a;
    update lstContacts;
}
catch(DmlException e)
{
    System.debug(e.getMessage());
}

}

Marked Solved if it does help you.

All Answers

Rahul.MishraRahul.Mishra
Hi,

You are getting error because ac.contacts will return the list of contact and you are trying to access .phone from list<Contact>. To access the phone field you have iterate the returned contact list , below is the updated trigger for you:
 
trigger caseDelete on Case(after insert) {

try
{   List<Contact> lstContacts = new List<Contact>();
    Account a=[select name,(select name from contacts ) from account limit 1];
    a.name='Dialog';
    
    for (Contact con : a.Contacts) {
       lstContacts.add(new Contact(Id = con.Id, Phone = '123'));
    }
    
    update a;
    update lstContacts;
}
catch(DmlException e)
{
    System.debug(e.getMessage());
}

}

Marked Solved if it does help you.
This was selected as the best answer
Rahul.MishraRahul.Mishra
Use the following code if you want to update all account and contacts, above one was to update one account and all it's contact:
 
trigger caseDelete on Case(after insert) {

try
{   List<Contact> lstContacts = new List<Contact>();
    List<Account> lstAcc =[select name,(select name from contacts ) from account];
    List<Account> lstAccountToUpdate = new List<Account>();

   for(Account acc : lstAcc) { 
      acc.Name = 'Dialog';
      lstAccountToUpdate.add(acc);
      
    for (Contact con : acc.Contacts) {
       lstContacts.add(new Contact(Id = con.Id, Phone = '123'));
    }
  }  
    update lstAccountToUpdate;
    update lstContacts;
 }
    catch(DmlException e)
    {
        System.debug(e.getMessage());
    }
    
}