You need to sign in to do that
Don't have an account?

apex trigger from opportunity to opplineitem
Hi
I have an apex trigger that takes a contact from the contact roles on opportunity, and adds it to a look up field on the opportunity called opportunity_contact__c.
I also need this to then go to another lookup field on the oportunity line items, also called opportunity_contact__c. Can anyone help me with this? Trigger below:
Many Thanks
Conor
I have an apex trigger that takes a contact from the contact roles on opportunity, and adds it to a look up field on the opportunity called opportunity_contact__c.
I also need this to then go to another lookup field on the oportunity line items, also called opportunity_contact__c. Can anyone help me with this? Trigger below:
trigger MnCopyPrimaryContact on Opportunity (before update) { Set<Id> setOfIds = new Set<Id>(); for (Opportunity o : Trigger.new) { if(o.Id!=Null){ setOfIds.add(o.Id); } } OpportunityContactRole[] contactRoleArray= [select ContactID, isPrimary from OpportunityContactRole where OpportunityId IN :setOfIds order by isPrimary desc,CreatedDate]; for (Opportunity o : Trigger.new) { if (contactRoleArray.size() > 0) { o.Opportunity_contact__c = contactRoleArray[0].ContactID; }else{ o.Opportunity_contact__c = null; } } }
Many Thanks
Conor
Thanks so much for this, it does work for adding to opporrtunity line item. However I need the opportunity contact on both line item and opportunity. Is this possible.
Cheers
Conor
Logic is written to work for both Opportunity and OpportunityLineItem.
please try below code:
trigger MnCopyPrimaryContact 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 ;
}
}
}
Please mark as best answer if it helps you.
Thank You
Ajay Dubedi
The code adds the contact to the opportunity, but does not add to the opportunity line items also?
Thanks
Conor