3

I figured I'd learn Apex by trying to convert processes that I build to triggers in a sandbox.

I'm trying to pass some contact information onto the header of the Account when the Contact has been identified as the primary contact.

here's what I have so far:

trigger ContactStuff on Contact (before insert, after insert, after update) {    
List<Account> accList = new List<Account>();
for (Contact c : Trigger.new) {
    if(c.Primary_Account_Contact__c == true){
        Account a = new Account(
            Id               = c.Account.Id,
            Contact_Email__c = c.Email,
            Fax__c           = c.Fax,
            Full_Name__c     = c.FirstName + ' ' + c.LastName,
            Telephone__c     = c.Phone);
        accList.add(a);            
    }

}
update accList; 
}

I'm getting the following error:

Error:Apex trigger ContactOnCreate caused an unexpected exception, contact your administrator: ContactOnCreate: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: Trigger.ContactOnCreate: line 32, column 1

0

The Account.Id value is going to be null in the trigger context. You can't pull in parent fields. But in this case, you don't have to. Just use AccountId instead.

You should also:

  • make sure you only fire this trigger on your after events

    There are two types of triggers:

    • Before triggers are used to update or validate record values before they’re saved to the database.
    • After triggers are used to access field values that are set by the system (such as a record's Id or LastModifiedDate field), and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue. The records that fire the after trigger are read-only.
  • consider implementing a Handler Pattern
  • consider implementing a Service Layer
  • add error handling
| improve this answer | |
0

You are trying to access the Id field of the contact's parent Account. Without a query it is not possible to do so. However, the AccountId field is like a formula to the Account's field, and it is available for use without a query in your situation.

The error is thrown because since you are trying to access that field without the query, it is returning a null value to the created Account. And update operations need an Id.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.