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
Shatanik1Shatanik1 

Error: You have uncommitted work pending. Please commit or rollback before calling out

I have written the following code and I am getting the error  "You have uncommitted work pending. Please commit or rollback before calling out". I am new to salesforce, so am unable to understand what the error is for. Kindly help

 

 

authSuccessBool=false;
        String token = ApexPages.currentPage().getParameters().get('oauth_token');
        System.debug('CompleteAuth Token===================================='+ApexPages.currentPage().getParameters().get('oauth_token'));
        if(token!=null)
        {
            String verifier = ApexPages.currentPage().getParameters().get('oauth_verifier');
            System.debug('CompleteAuth Verifier================================================='+ApexPages.currentPage().getParameters().get('oauth_verifier'));
            OAuth oa = new OAuth();
            authSuccess = oa.completeAuthorization(token,verifier);
              
            if(authSuccess!=null||authSuccess!=' ')
            {
                authSuccessBool=true;
            }
            this.message = oa.message;
        }
        else {
            message = 'Invalid request. Missing parameter oauth_token';
        }
        
        
         //--------------------------------------------------------
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            HttpResponse  res = new HttpResponse();
            String endpoint='https://docs.google.com/feeds/download/documents/Export?id=1ok94msdl7FDfo51R9cCSVqdRY6yRVO16byfv-GpvDOs&exportFormat=html';
            req.setMethod('GET');
            req.setEndpoint(endpoint);
            res=h.send(req);
            System.debug('====================='+res.getBody());
         //--------------------------------------------------------
        
        return null;
    }

bob_buzzardbob_buzzard

You can't make callouts, HTTP or otherwise, once you have made changes to the database. You either need to commit the transaction, make the callout prior to any database changes or move your callout to an @future method.

Shatanik1Shatanik1

Thanks for your suggestion.

Is there a way to explicitly commit any transaction

bob_buzzardbob_buzzard

Afraid not.  The transaction commits once your apex finishes.

Krishna Prasad K PKrishna Prasad K P

So just to confirm, if  I do as below, Neither of the statements will throw an exception, right?

 

1. Do Http Callout

2. Do record update based on callout result.

 

Thanks,

Krishna

 

 

 

 

bob_buzzardbob_buzzard

As long as no changes have been made to the database prior to step 1, then that is correct.

Amit VaidyaAmit Vaidya

Hi Bob,

 

Thanks for sharing this information.. Moving callout to an @future(callout=true) is working fine for me.

I want to update one field on Opportunity before going call to webservice. Is there anyother way thorugh which we can do it synchronously?

 

Can we separate out the DML transaction and webservice callout in two parts so that the DML transaction is completed before the Web Service Callout occurs? 

 

Can we call webservice through visualforce in this case?

 

Please let me know about this.

 

Thanks,

Amit

bob_buzzardbob_buzzard

If you are using VF, you can have two separate action methods, one to update the record and the other to execute the web service.  You'll have to orchestrate the calls from the page, using flags and javascript.

Amit VaidyaAmit Vaidya

Thank you for your reply Bob.

 

Can you please provide me any algorithm or any example code to accomplish this from the page, using flags or javascript? 

 

Your inputs will be helpful.

 

Thanks,

Amit

Célio XavierCélio Xavier
I was getting the same error, however, I decided to update the account before the callout, as I needed to concatenate some values, I followed this strategy, below is a simple example:
 
public static void updateAccount(Id recordId, String City, String PostalCode, String Country, String Street, String State_Province, String AddressType, String Complement, String Neighborhood, String Number_Address){
		
        String Number_Address_nm = Number_Address.replaceAll('[^0-9]', '');
        String PostalCode_nm = PostalCode.replaceAll('[^0-9]', '');
        String acId = [SELECT Id FROM Account WHERE Id =: recordId LIMIT 1].Id;  
        
        Account ct = new Account();
        ct.Id = acId;
        ct.BillingCity = City;
        ct.BillingCountry = Country;
        ct.BillingPostalCode = PostalCode_nm;
        ct.BillingState = State_Province;
        ct.BillingStreet = AddressType + ' ' + Street + '   Nº: ' + Number_Address_nm + '  ' + Complement + '   BAIRRO: ' + Neighborhood ;

        update ct;      
    }
    
    @future(callout=true)
    public static void Call_API(Id recordId, String City, String PostalCode, String Country, String Street, String State_Province, String AddressType, String Complement, String Neighborhood, String Number_Address){        
            ChangeAddressAPI.CallChangeAddressAPI(recordId, City, PostalCode, Country, Street, State_Province, AddressType, Complement, Neighborhood, Number_Address); 
    }
}