we have a flow where the user can enter data to create a record of a custom object. That works fine. But requirement is that new record must be transmitted to an external system and user should get some messages whether transmission was successfull or not. This can be done with a synchronous callout, response contains the messages from external system.

Problem is that synchronous callouts don't work after inserting a record with DML. It leads to error "You have uncommitted work pending. Please commit or rollback before calling out": how to solve callout error? You have uncommitted work pending. Please commit or rollback before calling out

But if I use asynchronous callout (@future(callout=true)), how can I get the messages from external system?

  • Do you really need the response from external system in the same flow? – RedDevil May 8 '19 at 11:20
  • sure, user clicks a save-button and should see results from external system. – Obi_77 May 8 '19 at 11:36

If you are inserting a record through the object standard new button and making a callout in trigger then it wont work as you will get the error you mentioned.

I can think of 2 Options:

Option 1: Override new button and use lightning data service tags.

use lightning record edit form tag and you can show the sobject layout with just a single tag.

    <lightning-record-edit-form object-api-name="Contact">
        <lightning-input-field field-name="Name">
                label="Create new">

There is an onsubmit submit handler which gets called before the record is created in the object, you can use this to make the callout from apex and get the information you want.

   event.preventDefault();       // stop the form from submitting
   //make the callout and if this successful do the submit in the next step

If this is successful you can just invoke the save method of LDS as next step and save the data in the sObject.

Option 2:

Use a future/queueable callout from trigger and use Lightning:emapi to listen to a platform event which is fired when the record is updated in the future context based on response from external system.

The catch with this solution is you dont have control over async processing in salesforce so they may/may not get executed immediately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.