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
Aruna06Aruna06 

System.CalloutException: You have uncommitted work pending.

Hi all,

    I'm getting this error whenever I'm trying to save......After a research I came to know that  you cannot perform DML (insert, update, delete) prior to a callout ( http.send() )......I'm a newbie to the apex code......what should I do in my code to get rid of this.....Any help please

 

  public string main(string url)
    {
            Http h = new Http();    
            HttpRequest req = new HttpRequest();
            req.setEndpoint(url);
            req.setMethod('GET');
            req.setTimeout(60000);
            string result='';
            if(isValid==true)
            {
                HttpResponse res = h.send(req);
                result = res.getBody();
            }else{
                result = '<?xml version="1.0" encoding="ISO-8859-1"?><Widgets><BaseURL>http://click-pledge.v-empower.com/web/widgets/WidgetXml</BaseURL><Category FolderName="GoogleMaps" Name="GoogleMaps" Image="http://t2.gstatic.com/images?q=tbn:ANd9GcR2xHN7pAmAkALvFTvZkzbMzpqthnJIYGs9IRpPz9IlyMx8Zfu2Hl2QBeBe"><Widget Name="Facebook"><FieldLabel FieldType="Textbox" image="https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcR6N8xoTIVjKPjpdpvLZjzwrDEAIodzZTpD1ybS-XHZskxE1F0e">FacebookURL</FieldLabel></Widget></Image></Category></Widgets>';
                system.debug('------'+result);
            }           
            return result;
    }

 

public void Save()
   {
     widgetpro = new C_P_Widgets__c();
     system.debug('layoutnamename'+layoutname);
     widgetpro.Widget_type__c = layoutname;
     widgetpro.Widget_Category__c = Name1;   
      system.debug('Nammmmmme'+widgetpro.Widget_Category__c);  
      system.debug('Displayedvalueee'+layoutname);
      insert widgetpro;
 }       

 

bob_buzzardbob_buzzard

Assuming you can't restructure your code to do the callout before the DML, the solution is to carry out the callout asynchronously.  One way to do this is to create an @future method:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_future.htm

 

another would be to run a scheduled job that handles the callouts.  There's an example at:

 

http://peregrinusforce.com/2012/05/22/dml-callouts-in-sequence/

Rakesh Aggarwal.ax1406Rakesh Aggarwal.ax1406

You may want to split your DML operation and HTTPCallout into 2 functions. On click of your save button in VF Page, call apex code functions using actionFunction.. I had explained similar approach to avoid some governor limits. Let me know if this works or you need additional details.

 

http://www.rakeshaggarwal.com/2012/07/rule-your-apex-governor-limits-through.html

 

Rakesh Aggarwal

www.rakeshaggarwal.com