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 ;
}
}