//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;
        update listOfContact;
  • 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
    Commented Nov 2, 2020 at 9:26

2 Answers 2



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



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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .