You need to sign in to do that
Don't have an account?
Populate OpportunityContactrole from custom field in Opportunity.
trigger Opportunity_NewBUBD on Opportunity (after insert, after update) { for (Opportunity o : Trigger.new) { if (trigger.isUpdate) { for (Integer i = 0; i < Trigger.old.size(); i++) { if (trigger.Old[i].BU_Business_Development__c != Null) { if (trigger.Old[i].BU_Business_Development__c != o.BU_Business_Development__c) { OpportunityContactRole [] oDWs = [select id from OpportunityContactRole where OpportunityId = :trigger.old[i].id and ContactId=:trigger.old[i].BU_Business_Development__c and Role = 'BU Business Development']; delete oDWs; } } Integer oDWs1 = [select count() from OpportunityContactRole where OpportunityId = :trigger.old[i].id and ContactId =:trigger.new[i].BU_Business_Development__c and Role = 'BU Business Development']; if (oDWs1 == 0 & o.BU_Business_Development__c != Null) { OpportunityContactRole OCR1 = new OpportunityContactRole (OpportunityId=o.id, ContactId =o.BU_Business_Development__c, Role = 'BU Business Development'); insert OCR1; } } } if (trigger.isInsert) { if (o.BU_Business_Development__c != Null) { OpportunityContactRole OCR1 = new OpportunityContactRole (OpportunityId=o.id, ContactId = o.BU_Business_Development__c, Role = 'BU Business Development'); insert OCR1; } } } }
- I would be very grateful on your views of the design of the apexcode?
- I believe that some of this code should be called using a function to facility the reuse of the code; can you provide some suggestions on this? (i.e. rows 26-30 and 38-42)
- I would like to use dynamic code utilising an array of fields that should be ‘monitored’ so that one piece of code can be used to populate the OpportunityContactRole for many fields. (This would need to have a variable for the Role and the fieldname.) Any ideas?
Hi Jason,
One quick suggestion, never use DML operation inside a loop unless unavoidable.
Create a list of the objects and pass this list to insert.
Reagrds,
Arun.
Thanks Aruk
I suspected that was the case although (despite reading the cook book a couple of times) I am still a little lost on how to apply this in a real world solution.
I would be grateful if you/someone could assist in recoding this (or atleast part of it) to demonstrate how to it applies to my solution.
Jason