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;
}
}
}