Thanks,Kevtrigger trgMnCopyPrimaryContact on Opportunity (before update) {
for (Opportunity o : Trigger.new) {
OpportunityContactRole[] contactRoleArray =
[select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate];
if (contactRoleArray.size() > 0) {
o.Opportunity_contact__c = contactRoleArray[0].ContactID;
}else{
o.Opportunity_contact__c = null;
}
}
}
Please try below code.
trigger trgMnCopyPrimaryContact on Opportunity (before update)
{
Set<ID> setOpp = new Set<ID>();
for (Opportunity o : Trigger.new)
{
setOpp.add(o.id);
}
List<OpportunityContactRole> lstOppContRole = [ select Id , ContactID, isPrimary ,OpportunityId
from OpportunityContactRole
where OpportunityId in :setOpp
ORDER BY isPrimary DESC, createdDate
];
Map<ID,OpportunityContactRole> MapOppWiseOppContRole = new Map<ID,OpportunityContactRole>();
for(OpportunityContactRole oppContRole : lstOppContRole )
{
if( MapOppWiseOppContRole.containsKey( oppContRole.OpportunityId ) == false )
{
MapOppWiseOppContRole.put( oppContRole.OpportunityId , oppContRole );
}
}
for ( Opportunity o : Trigger.new )
{
if( MapOppWiseOppContRole.containsKey( o.id ) )
{
OpportunityContactRole oppContRole = MapOppWiseOppContRole.get( o.id );
o.Opportunity_contact__c = oppContRole.ContactID;
}
else
{
o.Opportunity_contact__c = null ;
}
}
}
Let us know if that wll help you