Sometimes we need to create a record and then update it with information provided by a Web Service. However,a Web Service Callout may not occur after a DML statement within the same transaction.To achieve the required action, the transaction must be separated into two parts so that the DML transaction is completed before the Web Service Callout occurs and one workaround like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <apex:page controller="WsCalloutTest" tabstyle="Account"> <apex:form > <apex:actionFunction action="{!firstcall}" name="firstcall" Rerender="statuses" status="Status1" oncomplete="WebServiceCall();"/> <apex:actionFunction action="{!WebServiceCall}" name="WebServiceCall" status="Status2" reRender="statuses, msg"/> <apex:outputPanel id="statuses"> <apex:actionStatus id="Status1" startText="...Inserting Record Into DB..." /> <apex:actionStatus id="Status2" startText="...Calling Web Service..." /> </apex:outputPanel> <apex:outputPanel id="msg"> <apex:pageMessages /> </apex:outputPanel> <div><input name="DoAction" class="btn" type="button" value="Do Action" onclick="firstcall();return false;"/></div> </apex:form> </apex:page> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class WsCalloutTest{ Contact myContact; public PageReference firstcall() { myContact = new Contact(name = 'Test Contact'); insert myContact; return null; } public PageReference WebServiceCall() { // Execute a call to a Web Service HttpRequest req = new HttpRequest(); req.setEndpoint('http://yourserviceurl.com?id=' + myContact.Id); req.setMethod('GET'); HttpResponse response = new Http().send(req); myContact.Name = 'Test Contact 2'; update myContact; //if the update is successfull ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'WebService Called on New Contact: ' + myContact.Name)); return null; } } |
No comments:
Post a Comment