0

I want a Trigger to work as: While Inserting Account only one Contact should be created and after updating Account Name, its related Contact Name also gets updated. But while the trigger is working, two contacts are getting created.Could you please help me where I make a proper corrections so that only One contact gets created.

Trigger=>>

trigger AccountUpdate on Account (after insert,after update) {
    list <Contact> con= new list <Contact>();
    if(trigger.IsAfter){
        if(Trigger.IsInsert){
            for(Account acc:trigger.new){
                for (integer i=0 ; i<1; i++)    {
                    Contact c=new Contact();
                    c.LastName=acc.Name;
                    c.AccountId=acc.Id;
                    con.add(c);
                }
                insert con;
            }
        }else{
            Set<id> AccountIds = new Set<id>();
            for(Account a: trigger.new)
            {
                if(a.Name != trigger.oldmap.get(a.id).Name){
                    AccountIds.add(a.id);
                }
            }
            List<Contact> con=[select id, LastName,Accountid from Contact where accountid in: Accountids];
            for(Contact c:con)
            {
                c.LastName = trigger.newmap.get(c.accountid).Name;
            }
            update con;
        }
    }
}

1 Answer 1

0

Why do you need this for loop as it would only execute once

for (integer i=0 ; i<1; i++)    {
      Contact c=new Contact();
      c.LastName=acc.Name;
      c.AccountId=acc.Id;
      con.add(c);
 }

You can have the above code inside the Account for loop and have your insert con statement outside the for loop.

You must log in to answer this question.

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