function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lisa HorneLisa Horne 

Trigger to add Contact Role Record to Opportunity

The Contact Role object can not have fields added to it.  In order to get around this I have created a custom object  with an Object Name= OpportunityContactRoles and gave it a child relationship to the opportunity object.  The custom object has the two fields that are on the Contact Role object, ContactID and Object Name Parts (same as Role), but also has additional fields on it.

What I would like to have happen is every time a Contact name and Parts has been entered into the custom object and saved, a new  standard Contact Role is automatically created on the opportunity with the same Contact name and Role (Parts).  Can anyone help me with a trigger and class for this?  So far I have this but I know it's not even close.


trigger new_Contact_Role_to_Standard on Contact Role
{
   for(Contact Role c : Trigger.New)
   {
        OpportunityContactRole o = new OpportunityContactRole;
        o.ContactId = set the contact id here;
        o.OpportunityId = set the Opportunity id here;
        insert o;
   }
}
Best Answer chosen by Lisa Horne
Boom B OpFocusBoom B OpFocus
try this:  I assume that your custom object is called Contact_Role__c

trigger New_Contact_Role_to_Standard on Contact_Role__c {
List<OpportunityContactRole> lstOCRs = new List<OpportunityContactRole>();
for (Contact_Role__c cr : trigger.new) {
if ((cr.Contact_Name__c != null && cr.Parts__c != null) &&
     (trigger.isInsert || (trigger.isUpdate && trigger.oldmap.get(cr.Id).Contact_Name__c == null || trigger.oldmap.get(cr.Id).Parts__c == null))) {
OpportunityContactRole ocr = new OpportunityContactRole();
ocr.OpportunityId = cr.Opportunity__c;
ocr.ContactID       = cr.Contact_Name__c;
ocr.Role                = cr.Parts__c;

lstOCRs.add(ocr);
}
}
update lstOCRs;

}

All Answers

Boom B OpFocusBoom B OpFocus
try this:  I assume that your custom object is called Contact_Role__c

trigger New_Contact_Role_to_Standard on Contact_Role__c {
List<OpportunityContactRole> lstOCRs = new List<OpportunityContactRole>();
for (Contact_Role__c cr : trigger.new) {
if ((cr.Contact_Name__c != null && cr.Parts__c != null) &&
     (trigger.isInsert || (trigger.isUpdate && trigger.oldmap.get(cr.Id).Contact_Name__c == null || trigger.oldmap.get(cr.Id).Parts__c == null))) {
OpportunityContactRole ocr = new OpportunityContactRole();
ocr.OpportunityId = cr.Opportunity__c;
ocr.ContactID       = cr.Contact_Name__c;
ocr.Role                = cr.Parts__c;

lstOCRs.add(ocr);
}
}
update lstOCRs;

}
This was selected as the best answer
Lisa HorneLisa Horne
Thank you!  Would you by chance be able to help me with a test class for this?

Thanks!
Lisa HorneLisa Horne
Thanks! Would you be able to help me with a test class for this?