You need to sign in to do that
Don't have an account?
Esti Leiser
Edit trigger to work after insert too
Hi! I have a trigger that runs when records are updated (before update). I want it to also run after insert, for new records, but I'm not sure how.
Here's the trigger:
Any ideas? Thanks!
PS: this code is not bulkified (I think), so I'd love to take care of that too!
Here's the trigger:
trigger AddPrimaryContactToOpp on Opportunity (before update) { // THIS TRIGGER WILL OVERWRITE ANY CONTACT DEFINED IN THE CUSTOM FIELD OPPORTUNITY_CONTACT__C ON THE OPPORTUNITY OBJECT. // SET THIS FIELD TO READ ONLY OR CHANGE THE FUNCTIONALITY BELOW TO AVIOD DATA BEING OVERWRITTEN BY MISTAKE... for (Opportunity o : Trigger.new) { // CREATE ARRAY OF ALL CONTACT ROLES ON THIS OPPORTUNITY. THE REASON WHY WE DONT PICK THE PRIMARY CONTACT ROLE ONLY // IS BECAUSE THE PRIMARY FLAG IS NOT SET WHEN LEADS ARE CONVERTED TO OPPORTUNITIES. ONLY WHEN CREATING OPPORTUNITIES // MANUALLY FROM THE CONTACT OBJECT THE IS PRIMARY CHECKBOX IS CHECKED... OpportunityContactRole[] contactRoleArray = [select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate]; system.debug('>>> contact role array is ' + JSON.serialize(contactRoleArray)); if (contactRoleArray.size() > 0) { // IF PRIMARY IS DEFINED THEN THIS WILL BE THE FIRST OBJECT. IF NOT THE FIRST ADDED CONTACT ROLE WILL BE ADDED... o.Contact__c = contactRoleArray[0].ContactID; } system.debug('>>> contact__c is ' + o.Contact__c); } }Adding before insert didn't work because the OCRs are not yet created. Adding after insert didn't work either - it gave an error.
Any ideas? Thanks!
PS: this code is not bulkified (I think), so I'd love to take care of that too!
All Answers
When I run it 'after insert' I get this error:
However, my test class is not passing anymore! Maybe it's because the test adds the opportunity and then the OCR, so the trigger runs before the OCR exists.
Here's the apex test. Any ideas?
When I tried running that test, I got this error on line 24:
I inserted that code, and the debug line is:
USER_DEBUG|[21]|DEBUG|->o1006V00000053Tu2IAE 00KV0000001VBZPMA4
Id idey=[select id,contact__c from Opportunity where id=:o1.id].contact__c;
system.AssertEquals(idey,C1.ID);