+ Start a Discussion

Help with Apex trigger with Callout

Hi there, I created a trigger that would send an external post request when an opportunity stage was updated to "Closed Won" and for some reason my http request is not posting.  I was wondering if there is a mistake in my code.  Any help would be greatly appreciated.


Here is the Class (I hardcoded the URL for now).


public class OpportunityUpdateURL {
public static void hitTheServer(Opportunity[] opp) {
for (Opportunity o:opp){
HttpRequest req = new HttpRequest();
req.setEndpoint ('http://url.com/events?type=customer_won&advocate[email]=steve@influitive.com&advocate[name]=Steve%20Organ&params[Opportunity Amount]=1000');
req.setMethod ('POST');





trigger updateOpptyCustomerWons on Opportunity (after update) { 

    //make a set to hold opportunity ids that we need
    Set<Id> opptyIds = new Set<Id>();
    for(Opportunity o : trigger.new)
        //check to see if stage field has been changed
        if(o.StageName != trigger.oldMap.get(o.Id).StageName){

        //get any opptys that have been edited
        List<Opportunity> opptys = [SELECT Id,StageName FROM Opportunity WHERE StageName = 'Closed Won' AND Id IN :opptyIds];
        for(Opportunity o : opptys){
            Opportunity[] opp = Trigger.new;



I also added a remote site for my URL.


Thanks so much,



Ok so there is an update.  After adding the following code to my class:


Http http = new Http();
HTTPResponse res = http.send(req);


I get the following error when I meet the condition for trigger to run the callout:


Developer script exception from XXXX : updateOpptyCustomerWons : updateOpptyCustomerWons: execution of AfterUpdate caused by: System.CalloutException: Callout from triggers are currently not supported. Class.OpportunityUpdateURL.hitTheServer: line 11, column 1 Trigger.updateOpptyCustomerWons: line 24, column 1



Hi Steve,


To solve Your problem You need to add the line below, just before the hitTheServer method:


@future (callout=true)


It will cause that external callout which is unsopprted on triggers will be processed asynchronously, just after the regular trigger transaction finishes.



Hope it will help ya.


Best regards