0

I have written a Trigger in which whenever I create an Account, new Contacts are created with the Last Name same as the Account Name. But now when I try to update the Account Name, Contact's last name remains unchanged. I want it to get updated whenever I update my Account Name. How do I achieve this?

Trigger

trigger Account1 on Account (after insert,after update) {
    list <contact> con=new list <contact>();    
    for(Account acc : trigger.new){
        contact c = new contact();
        c.LastName = acc.Name;
        c.AccountID = acc.ID;
        con.add(c);    
    }
    insert con;
}

1 Answer 1

1

This is because you are creating a new contact everytime a account is inserted or "UPDATED". Your after insert is fine, where you are creating new contacts everytime the account is inserted. The issue you have is in Update.

When you are making an update, you will have to first query all the existing contacts for that account and then update them all with the accounts last name.

Your code will keep creating new contacts even if you are updating an account.

You must log in to answer this question.

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