3

Thanks for reading my question.

I am looking to create a trigger on the OpportunityContactRole which is unfortunately not supported (I'm curious as to why, if anybody has insight on that, but that is not the question I cam to ask). The solution I have found with Google is to create a VisualForce page embedded on the Opportunity and Contact page layouts that executes a custom controller with a future method. The suggested work-around code looks like this:

VisualForce page:

<apex:page standardController="Opportunity" extensions="OppHelper" action="{!rollupOppContacts}" /> 

Controller:

public with sharing class OppHelper {
public Opportunity opp;
public OppHelper( ApexPages.StandardController stdController ) {
    opp = ( Opportunity )stdController.getRecord();        
}
public void rollupOppContacts(){
    OppHelper.rollupOppContactsFuture( opp.Id );    
}
@future public static void rollupOppContactsFuture( Id oppId ) {
    Contact[] contactList = [ SELECT Id, Some_field__c FROM Contact
                         WHERE Id IN ( SELECT ContactId FROM OpportunityContactRole
                                     WHERE OpportunityId = :oppId ) ];
    Opportunity opp = [ SELECT Id, Some_rollup_score__c FROM Opportunity WHERE Id = :oppId ];
    opp.Some_rollup_score__c = 0;

    for( Contact contact : contactList ) {
        opp.Some_rollup_score__c = contact.Some_field__c;
    }
    update opp;
}

}

(Source)

Why is the @future method necessary in this case? Will the edit/detail page only load after the controller has finished processing the code otherwise? How much of a delay could I expect? If I move the action out of the tag and execute it in the body of the VisualForce page (albeit, still with no visible body) will it still cause a delay?

I just want to understand the exact tradeoffs I'm making between page load time / instantaneity of the code results.

2

I believe DML Requests are not encouraged on page load, hence the future. (The page will load fine, @future just starts an asynch thread of execution) What this code seems to be doing is merely updating a trigger maintained roll up field on Opportunity everytime it is accessed.

To be able to make it behave like a trigger, you'd need to create a VF Page to replace the standard OCR Edit page, get rid of the related list and replace it with your custom VF Page. Then in your custom save you can plugin behaviour which you want to inject after execution of an insert / update.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.