How to create primary contact in account contact role for an account without duplicates

1.2k Views Asked by At

Whenever I'm trying to insert a new multiple contact for single account using dataloader, one primary contact should be inserted in account contact role object.

If multiple contacts are there we should consider first contact which is going to be inserted considered as primary contact remaining should not be inserted only one primary contact should be there in Account Contact Role object. In the below code, I have tried, primary contact is not getting created for an account.

trigger AccountContactRole on Contact(After insert,After Update){
    list<AccountContactRole> acr=new list<AccountContactRole>();
    set<ID> getid=new set<ID>();
    Contact[] clist=trigger.new;
        for(Contact Con : clist) {
            if(con.AccountId!=Null) {
                getid.add(Con.AccountId);
            }
        }
        List<AccountContactRole> ac = [Select Id,AccountId,ContactId,IsPrimary from AccountContactRole Where AccountId in :getid and IsPrimary =True];
        set<ID>accountid=new set<Id>();
        for(AccountContactRole acv:ac) {
            accountid.add(acv.AccountId);
        }
        System.debug('Records on List are '+ac +' And Records are '+ac);
        for(Contact Cont: clist) {
            AccountcontactRole C = new AccountcontactRole();
            System.debug('Cont current value is'+Cont);     

            if(ac.isempty()) {
                if(getid.contains(Cont.AccountId)==false){
                C.contactId=Cont.Id;
                C.Role='Decision Maker';
                C.AccountId=Cont.AccountId;        
                C.Isprimary=true;
                acr.add(C);
            }
        }
    }

    Insert acr; 
0

There are 0 best solutions below