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
Developer.mikie.Apex.StudentDeveloper.mikie.Apex.Student 

Account Name updated from clients trigger

I have a trigger, the trigger is designed to update the account name field as contacts are added. 

I would like it to be in the form:

Account with one contact called James peterson = Peterson, James Account

Account with contacts james peterson and ellie peterson = Peterson, james and Ellie, Peterson account.

I think I have my syntax off slightly. Please help! I just tried to add a contact to my account and I received this error message:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger ContactTrigger caused an unexpected exception, contact your administrator: ContactTrigger: execution of AfterInsert caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.LastName: Trigger.ContactTrigger: line 11, column 1



This is my trigger, your help is very much appreciated

Trigger:

trigger ContactTrigger on Contact (after insert,after update, after delete, after undelete) {
    Set<ID> setAccountIDs = new Set<ID>();
    for(Contact c : Trigger.new){
        setAccountIDs.add(c.AccountId);
    }
 
    List<Account> accounts = [Select ID, Name,(Select Name From Contacts)  From Account WHERE ID IN :setAccountIDs];
    for(Account a : accounts){
        String accName = '';
        for(Contact c : a.Contacts){
        accName +=' and'+c.LastName+', '+c.FirstName;                     
        }
        a.Name=accName;
    }
    update accounts;
 
}


king regards,

Mikie
Best Answer chosen by Developer.mikie.Apex.Student
ShaTShaT
Hi Mikie,

You need to query all the fileds which are required for assigning the values.

For Eg. If you need lastname you need to query lastname.

List<Account> accounts = [Select ID, Name,(Select Name , LastName ,FirstName From Contacts)  From Account WHERE ID IN :setAccountIDs];

if you need email - than add email in query

[Select ID, Name,(Select Name , LastName ,FirstName ,email From Contacts)  From Account WHERE ID IN :setAccountIDs];

Thanks
Shailu