1

This question already has an answer here:

I set up a Process Builder to activate when an Lead reaches a certain sales stage. Then the Process Builder will send two variables to an invocable method within my apex class. On the Lead object, once I go to save my change I get the error

An Apex error occurred: System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.

So I came across this on help.salesforce.com:

You can't make callouts, HTTP or otherwise, once you have made changes to the database. It's true that you cannot make callouts with pending transactions in the request context. So your only way out is to make the callout in a separate context.

You cannot perform a DML operation prior to a callout or Http. All the DML operations should be invoked only after you are done with callouts.So, make a webservice callout first and then save the request.*

So I need to make a separate context/class? How do I send a HttpRequest once an Object has been updated?

public class ProcessHandlerShowAccounts 
{
    public class AccountParameter
    {
        @InvocableVariable(required=true)
        public Id accountId;
        @InvocableVariable(required=true)
        public String name;
    }
    @InvocableMethod(label='handle' description='Send the Accounts variables passed from Process Builder to the webservice')
    public static void handle(AccountParameter [] accountParameters) 
    {
    webServiceCallOut(accountParameters[0].accountId,accountParameters[0].name);

    }
    public static void webServiceCallOut(ID n, String a){
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://Accounts'
                    +'?sfdcid='+n+'?operation='+a);

        String username = 'nameishi';
        String password ='123';
        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);

        //Create a new Http object to send the request object
        //a response object is generated as a result
        HTTPResponse res = http.send(req);
        System.debug(res.getBody());
    }
}

marked as duplicate by glls, David Reed, sfdcfox apex May 30 '18 at 20:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • @glls Thank you for the link I did not find that question existed. It worked. – nameishi May 30 '18 at 19:40
-1

You can do the HTTP call out from a trigger using @future method

  • Yeah I wish I found @glls question sooner. – nameishi May 30 '18 at 19:40

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