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
SurjenduSurjendu 

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

How do i resolve this...This is my code...I am sending an XML to an endpoint n number of times(its in a for loop)...Cant i do that?

public PageReference saveUsers() {
String[] listOfSelectedUsers = getUsers();
String domainId = System.currentPageReference().getParameters().get('ex');
for(String presentVar: listOfSelectedUsers)
{

Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://84.40.30.147/cm/spws');
req.setMethod('POST');

TestExtranet__c extranet = [select Extranet_Name__c from TestExtranet__c where id = :domainId];
Lead lead = [select id,firstname,lastname,email from Lead where id = :presentVar];
String requestXML = buildXMLRequest('createUser',extranet.Extranet_Name__c,lead.id,lead.firstname,lead.lastname,lead.email);

req.setBody(requestXML);
HttpResponse res = h.send(req);
XmlStreamReader reader = res.getXmlStreamReader();
boolean errorExists = parseResponseForError(reader);
if(!errorExists)
{
Extranet_User_Mapping__c mapping = new Extranet_User_Mapping__c();
mapping.Extranet_Id__c = domainId;
mapping.Leads__c = presentVar;
insert mapping;
}else
{

}


}
PageReference userConfPage = new PageReference('/apex/userConfirmation?ex='+ System.currentPageReference().getParameters().get('ex'));
return Page.userConfirmation;
}


Best Answer chosen by Admin (Salesforce Developers) 
Ron HessRon Hess
i think you can do 10 callouts in a single class, and you must do these before calling insert.

so, make the loop collect up a list of  Extranet_User_Mapping__c objects, then insert them after you have completed the callouts

All Answers

Ron HessRon Hess
i think you can do 10 callouts in a single class, and you must do these before calling insert.

so, make the loop collect up a list of  Extranet_User_Mapping__c objects, then insert them after you have completed the callouts
This was selected as the best answer
cheenathcheenath

You can do a query before callout, but you can not do update/insert/delete
before callout. So move your insert call outside the loop.
Also, you can only make 10 callouts.


MiddhaMiddha
Is there any specific reason for doing this. Do we have any other workaround to make an insert call before a callout?
johncusackjrjohncusackjr

Hi,

 

If we do the following scenario we get the same error message: You have uncommitted work pending. Please commit or rollback before calling out

 

1. Create a savepoint.

2. We delete objects.

3. Rollback

4. Callout

 

Even though we rolled back, we still get the same error. We're trying to determine if the user has delete permission on the object, before calling out. Is there are workaround for this issue? Is the errror message wrong or is this a bug?

 

Thanks,

John

Scott.MScott.M

This restriction is a real pain and extremely short sighted espcially considering there is no method to force a commit.

goabhigogoabhigo

Hi Ron,

Please suggest me how to get over from this error message.

 

Here is my class:

 

public class SingleSmsController {
 
    private ApexPages.StandardController con;
    private PageReference smsPR=null;
    private String url;
    private String mobileNo;
    private Integer status;
    private String msgStatus;
    private SMS__c smsObj;
     
    public SingleSmsController(ApexPages.StandardController controller) {
        con=controller;
    }
  
    public PageReference sendAction() {
    try{
        smsPR = con.save();
        smsObj=[SELECT Id,To_Lead__r.MobilePhone,To_Contact__r.MobilePhone,Mobile_No__c,Message__c,Message_Status__c,MessageID__c from SMS__c Order By Id DESC][0];
        if(smsObj.To_Lead__c != null) 
            mobileNo = smsObj.To_Lead__r.MobilePhone;
        else if(smsObj.To_Contact__c != null) 
            mobileNo = smsObj.To_Contact__r.MobilePhone;
        
        url='http://gateway.onewaysms.com.my:10001/api.aspx?apiusername=xxx&apipassword=xxx'+            '&mobileno='+mobileNo+'&senderid=lavaprotoco&languagetype=1&message=RM0.00'+ EncodingUtil.urlEncode(smsObj.Message__c, 'UTF-8') +'';
        
        System.debug('### URL: '+ url);
        status = Integer.valueOf(getContent(url));
        if(status > 0) {
            // 'status' contains the MT ID
            smsObj.MessageID__c = String.valueOf(status);
            msgStatus = 'Success-Sent';
        }
        else if(status == -600)
            msgStatus = 'Failed-Insufficient balance';
        else
            msgStatus = 'Failed';
        
        System.debug('### Status Number: '+ status);
        System.debug('### Status String: '+ msgStatus);
        
       }
       catch(Exception e) {
           msgStatus = 'Failed';
           //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,e.getMessage()));
       }
       smsObj.Message_Status__c = msgStatus;
       smsObj.Mobile_No__c = mobileNo;
       update smsObj;
       
       return smsPR;
     }

     public String getContent(String url) {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        return res.getBody();
    }
}

 

This is of high priority Ron. Please help me.

 

 

 

 

 

 

 

 

 

 

KanouKanou

after you do the insert, update or delete, excute the next code for reload.

        PageReference pageRef = ApexPages.currentPage();
        pageRef.setRedirect(true);
        return pageRef;

 

GuyClairboisGuyClairbois

Hi all,

I ran in to the same error, but not in a VisualForce page but in an APEX trigger.

Any ideas/solutions/workarounds for that?

Tnx,

Guy

HarmpieHarmpie

Ran into this as well.

 

My scenario is :

1) Create a Savepoint

2) Do several DML (rolling back on exception)

3) Call @future method to do a callout

4) @future method does a DML-insert after making the callout

 

It seems that this @future method somehow remains inside the Database transaction created when I opened the savepoint, which is odd to start with. The limitation itself is quite odd too.

 

After removing the transaction (creation of savepoint and rollbacks) there was no problem anymore. Probably hard to implement, but I would definitely love to see a Database.commit() method!

juppyjuppy

I hit the same symptom - looked through my debug logs, removed all my database work entirely, made all sorts of changes to no avail, finally realised that it was my Savepoint that was the issue.

Removed the savepoint and all good!

Hope this helps others to get to a solution quicker than I did

jhennyjhenny

Anyone else notice batch apex classes that make callouts start receiving this error in sandboxes with spring release 12? Even without DML in the class it gives the error. I have a case open with SFDC but was curious if anyone else had this issue. Same code in a non spring 12 org works fine.

pmorellipmorelli
Yes, we have a bug with batch and callouts. We're working on it, hopefully fixed soon. I'll update when we're more definite on a release date.
jhennyjhenny

Thanks for the update

pmorellipmorelli

For people really stuck, you can file a case, post it here, there's a workaround we can enable from our side. It's temporary, and we're targeting the real fix for next week, so if you can live with it, that's probably best.

jimmy_sfjimmy_sf

This sounds like the same issue I'm hitting.  I'd appreciate your enabling the work around for me.

 

I posted a case #06941579 with repro and org details.

 

Thanks for your help. 

juan.cardonajuan.cardona

Hi

 

Got the same problem, and my develop´s stuck since them.

 

I posted a case too,  number # 06932545.

 

Thanks for your help.

 

 

NielsPostNLNielsPostNL

Please enable the workaround...case #06970637

 

Thanks in advance

pmorellipmorelli

the fix for this should be going out this afternoon PST, do you still want the workaround?

NielsPostNLNielsPostNL

We just checked the functionality we use it for and it is working fine. So I do not need the workaround anymore.

 

Thanks!

pmorellipmorelli

great to hear! Let me know if you see any further issues.

rikhilsuhas9rikhilsuhas9

hi ,
i made a webservice callout using batch apex and after getting response  i am doing update operation

 

.this is working fine for when i given scope parameter as 1 in the database.executebatch. however when i pass scope parameter  as10 it only updating 1 value and getting exception like "You have uncommitted work pending. Please commit or rollback before calling out..."   .

 

and am doing dml operation after the callout  & based on callout response result only .
please help me in this scenario.
thanks

GuyClairboisGuyClairbois

Hi,

Sounds like you're not handling this as a batch operation.

 

So in case of e.g. 3 callouts, instead of:

Callout - Update - Callout - Update - Callout - Update

you should do

Callout - Callout - Callout - Update (of 3 records at once)

 

The first line will work in case of 1 callout but not when there are more than 1.

So collect the results of the callouts in a List of objects but don't update them yet. Postpone that until you have all the callout results.

 

Guy

rikhilsuhas9rikhilsuhas9

Excellent  GuyClairbois .

Now am able to do 10 callouts and updating collection . thanks verymuch for your time. and i have a doubt here will it be handle 11 million records ? according to governor limits we can process 10000  dml rows   .

 

GuyClairboisGuyClairbois

I think the first bump you will hit is the number of callouts per transaction (which is 10). Also using callouts for such a big volume sounds like not the proper way of doing it. Maybe look into bulkifying the remote webservice or triggering the process from the other system so you can use the Bulk API which has less limits.

rikhilsuhas9rikhilsuhas9

Hi Guyclairbois  here am able to do update only for 10000 records after that governor limits com into action , actually batchapex should bypass governorlimits on dml rows  like callouts  i dont know why its giving above error?

 

and each batch am updating 10 records only?

 

 

thanks

 

GuyClairboisGuyClairbois

Could you post your code here? It's hard to judge what the exact issue is without viewing the code..

melango ConsLeague.ax1827melango ConsLeague.ax1827

I have similar issue. I had a particular code working and then with amendments which is not related to the callout and trying to test, I ended up with the above issue.

 

Inspite of reverting the code to the original working code from Production, I still have the same issue. Firstly, is there an option to come out of the issue.

 

Also, I have raised a case - 09600095 for any possible work around to be suggested.

 

Please help as I was working on a tight deadline for this weekend release.

 

Thanks much

Swamy PSwamy P
Hello folks,

Actually am facing the same issue. We are sending callouts and than we are doing DML's...again we are sending callout based on the scenario. I was trying to send all records in one time but my 3rd party people are not accepting because they are accepting only one record at a time. 

So first iam sending all requests one by one and also getting all responses for each and every request. So atlast i wanted to insert records based on the responses. 

For every request am getting response...so i just wanted to store the response in onel list, after completing that callout i wanted to do DMLs.
How can i achieve this?? will you suggest me??

In the mean while how you resolved your issue?? will you share your idea on my issue and your issue that how you resolved??