22

I have this exception related to my previous question:

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

When clicking preview as an admin the Visualforce page is executed but a case is not created. It throws the exception.

Visualforce Page

<apex:page controller="Controller" action="{!init}" showHeader="false" sidebar="false">
    <center>
        <apex:pageBlock title="Request Listener"></apex:pageBlock>          
    </center>
</apex:page>

Controller :

PUBLIC with sharing class Controller
{   
    PUBLIC String fromNumber      = ApexPages.currentPage().getParameters().get('From');
    PUBLIC String toNumber        = ApexPages.currentPage().getParameters().get('To');
    PUBLIC String body            = ApexPages.currentPage().getParameters().get('Body');   
    PUBLIC PageReference init()
    {           
        System.debug('From Phone Number :' +fromNumber);
        System.debug('To phone NUmber :' + toNumber);
        System.debug('Message Body :' + body);
                       
        TwilioRestClient Client = TwilioAPI.getDefaultClient();                                                   
            SYSTEM.DEBUG('FROM AND To  Number is NOT NULL');         
            String formattedNumber='+919876543210';    
            IF(body != NULL)
                body = body;
            ELSE
                body = '';
            Case c = NEW Case (Subject = formattedNumber,Description = body,Origin = 'Phone');
            INSERT c;                 
            
            Map<String,String> params1 = new Map<String,String>
            {
               'To'   => fromNumber,
               'From' => '+1908280****',
               'Body' => 'Conformation to customer'
            };
            TwilioMessage message = client.getAccount().getMessages().create(params1); /* Valid conformation SMS sent to the Customer.*/                                   
        return null ;
    }
}
0

1 Answer 1

8

One of the main reason of this exception is that you are doing some CRUD operation (create,read,update,delete) in your code in same context of running code, means you are doing some DML operation and then doing call out in single run.

You have to break thread with @future annotation.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .