1

i have written a trigger on account to create contact automatically but it is working fine in the case of updating only,while inserting in account i am getting the following error this is my code:

trigger ContactsupdateAccountphone on Account (after insert,after update) {
    contact con=new contact ();
    list<contact> conlist=new list<contact>();

    if(trigger.isafter && trigger.isinsert ){

        for(account acc1:trigger.new){
            con.accountid=acc1.id;
            con.lastname=acc1.name;
            con.phone=acc1.phone; 
            conlist.add(con);
        }
        if(conlist != null && conlist.size()>0){
        insert conlist;
     }
    map<id,account> mapac=new map<id,account>();
    set<id> setac=new set <id>();  
    for(account a:trigger.new){
        setac.add(a.id);
        mapac.put(a.id,a);
    }
    list<contact> lcon=[select id,lastname,phone,accountid from contact where accountid =: setac];
    for(contact c:lcon){
        if(mapac.containsKey(c.accountid)){
            c.LastName=mapac.get(c.accountid).name;
            c.Phone=mapac.get(c.AccountId).phone;
            c.AccountId=mapac.get(c.AccountId).id;
        }
        conlist.add(c);  
    }
    system.debug('The trigger.Old value '+trigger.Old);
    system.debug('The trigger.new value '+trigger.new);
    system.debug('The trigger.Oldmap value '+trigger.Oldmap);
    system.debug('The trigger.newmap value '+trigger.newmap);
    if(conlist != null && conlist.size()>0){
        update conlist;
    }
}
}

this is my error:

Error: Invalid Data. Review all error messages below to correct your data. Apex trigger ContactsupdateAccountphone caused an unexpected exception, contact your administrator: ContactsupdateAccountphone: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 0032800000DpHmuAAF: Trigger.ContactsupdateAccountphone: line 36, column 1

  • from line map<id,account> mapac=new map<id,account>(); to below all code . wrap inside if condition if(trigger.isafter && trigger.isUpdate ) – Ratan Paul Feb 4 '16 at 16:46
  • N.B. if(conlist != null && conlist.size()>0) is unnecessary; if list is empty, DML does nothing – cropredy Feb 4 '16 at 22:32
2

You can avoid duplicate Id errors by using Map<Id, SObject> instead.

Map<Id, Contact> insertedContacts = new Map<Id, Contact>(/*records*/);
insertedContacts.put(alreadyMappedContact.Id, alreadyMappedContact);
update insertedContacts.values();
| improve this answer | |

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.