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
Murthy AlluriMurthy Alluri 

Sending DML statement and Call Out together

Hello, 
I am having a requirement first insert request record , second do the call out and update the same record.
I tried below approach as specified in salesforce knowledge articles, but still record is not saved in database so update is failing.
I followed below article but was not successful, please advise, is there any way we can make insert record and call out.

https://help.salesforce.com/apex/HTViewSolution?id=000003701
NagendraNagendra (Salesforce Developers) 
Hi,

I had a similar situation once. As per the documentation, Salesforce doesn't allow any DML operation before a callout in the same transaction. There seem to be two workarounds at the top.

Use @future annotation: - This is one way but I guess you don't want it.

The second way is using an internal callout to change the transaction before making the external callout. It is a bit tricky but it works well. The key here is to change the transaction before making the final callout.

Suppose, the developer clicks the button (let's name the transaction as T1) and then the developer expects some DML operation to happen.

Instead of using DML statements in the same class, create an another class (say handler class) as a Rest resource (with @RestResource annotation). This class should be able to deserialize the request into a proper format and then insert the same. Please note this will happen in a different transaction T2.

This is making callout within salesforce.
class ABC_controller{

Http h = new Http();
Httprequest req = new Httprequest();
req.setBody(//pass the serialized JSON string of the objects to be inserted);
req.setEndpoint(//from urlmapping of the other handler class);
h.send(req);
}
Send() method will hit the appropriate endPoint and that handler class will deserialize the JSON string using JSON.deserialize() and insert the same.

After this, the transaction will return from T2 to T1 again and then you can make your external web service callout normally.

Please mark this as solved if the information helps.

Regards,
Nagendra.P