+ Start a Discussion
HTANIRSHTANIRS 

trigger on opportunity to check contact role already exists

Hi Friends,

I have created a trigger on Opportunity to insert a contact role based on Account in Opportunity.
This is working fine when I create a account--> contact --> opportunity. But when I am converting a lead to account--> contact--> opportunity, 2 contact roles are getting created which is duplicate.
 
trigger updateContactRole on Opportunity (after insert, after update) {
    
    System.debug('-- Inside Opportunity Contact Role Trigger---');
    
    List<OpportunityContactRole> newContactRoleList = new List<OpportunityContactRole>();
    Map<Id, Id> opportunityAccountMap = new Map<Id, Id>();
	Map<Id, List<Id>> mapOpportunityContact = new Map<Id, List<Id>>();
	Map<Id, List<Id>> mapOpportunityContactRole = new Map<Id, List<Id>>();
	
	for(Opportunity opp : trigger.new) {
		if(opp.AccountId != null) {
			opportunityAccountMap.put(opp.AccountId, opp.Id);
		}
	}
	
	// get contacts from opportunity account 
	for(Contact cont: [SELECT Id, AccountId FROM Contact WHERE accountId IN: opportunityAccountMap.keySet()]) {
		List<Id> contactIds = new List<Id>();
		if(mapOpportunityContact.containsKey(opportunityAccountMap.get(cont.AccountId))) {
			contactIds = mapOpportunityContact.get(opportunityAccountMap.get(cont.AccountId));
		}
		contactIds.add(cont.Id);
		mapOpportunityContact.put(opportunityAccountMap.get(cont.AccountId), contactIds);
	}
	
	
	// get contacts from opportunity contact role. 
	for(OpportunityContactRole contRole: [SELECT Id, OpportunityId, ContactId FROM OpportunityContactRole 
											WHERE OpportunityId IN: opportunityAccountMap.values()]) {
		List<Id> oppContactIds = new List<Id>();
		if(mapOpportunityContactRole.containsKey(contRole.OpportunityId)) {
			oppContactIds = mapOpportunityContactRole.get(contRole.OpportunityId);
		}
		oppContactIds.add(contRole.ContactId);
		mapOpportunityContactRole.put(contRole.OpportunityId, oppContactIds);
	}
	
	
	for(Id oppId : mapOpportunityContact.keySet()) {		
		// opp account contacts
		List<Id> contactRoles = new List<Id>();
        if(mapOpportunityContactRole.containsKey(oppId)) {
            contactRoles = mapOpportunityContactRole.get(oppId);
        }
		
		for(Id contId :  mapOpportunityContact.get(oppId)){
			if(!contactRoles.contains(contId)){
				OpportunityContactRole myContactRole = new OpportunityContactRole();
				myContactRole.ContactId = contId;
				myContactRole.OpportunityId = oppId;
				newContactRoleList.add(myContactRole);
			}
		}		
	}
    
    try {
        if(newContactRoleList.size()>0) {
            insert newContactRoleList;
        }
    }

    catch(Exception e) {
        System.debug(e);
    }
}

Kinldy review my code and let me know what condition I need to change to check and create contact role.

Thanks in advance.