0
//write trigger on contact when we edit contact. the contact name comes along with account name 
trigger ContactNameWIthAccountName on Contact (before update) {
    List<Contact> listOfContact = [SELECT Id,lastName,  AccountId FROM Contact WHERE AccountId != null AND Id IN : Trigger.new] ;

    for(Contact s : listOfContact)
    {
        Contact  a = new Contact();
        
        a.lastName  = s.lastName+'-'+ s.AccountId;
        
       listOfContact.add(a);
    }
        update listOfContact;
}
1
  • This trigger should not be querying the contacts nor should you be trying to explicitly update; you already receive them in Trigger.new and Trigger.newMap and since this is before update any changes you make to these records will automatically be persisted. Also, as mentioned by Pavlo, you will get the name updated every time the contact is updated (for whatever reason). You need to ensure this is only done when specific conditions are met (e.g. the last name or account ID change). – Phil W Nov 2 '20 at 9:26
0

https://trailhead.salesforce.com/en/content/learn/modules/apex_triggers/apex_triggers_intro

please use in your case

for(Contact s : Trigger.new) {
    s.LastName = s.LastName + '-' + s.AccountId;
}

but another problem - each time contact is edited, AccountId will be appended to LastName

Thanks

0

The error message is very clear. You cannot add items to or remove items from a collection that is feeding a loop.

The following is wrong (and basically what you have):

for(Object thing :myList){
    myList.add('new thing'); // <= Can't do this
}

Get rid of that, and just modify the loop control variable directly. That'd get you past your initial error, but there are other problems

  • While the AccountId field displays the name of the related Account in the UI, that's just Salesforce being helpful. In reality, what's stored in this field is the Id of the Account (i.e. 001000000000123, as the field name of AccountId should lead you to believe), not the name. If you want the name, you'll need to query for it
  • The purpose of Before triggers is to modify the values of the records before they are committed to the database. That means that as long as you're operating on the object instances contained within Trigger.new or Trigger.newMap, you do not need to use DML

Probably the biggest issue though is that there's almost no reason to create a trigger for this (unless you're specifically trying to practice writing triggers and unit tests).

You could get the same information onto your Contact by creating a simple formula field. If you really need to mangle Contacts' last names by adding the account name, you could use a workflow rule with a field update.

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.