0

hope you are all well.

I have do have one question : I need to create a custom object that collects data from an external web service. According to a picklist value from this object, I need to set a field of this object with data I collect from a web-service, after it is updated. So for that I do a REST callout and retrieve the information and I created an after update trigger to do the field setting. Then, I do not know how to do : because if I use a call the callout method from the trigger, I do have an error. So I thought to use @future(callout=true) on the callout method but with that I am not allowed to get a value (has to be void).

Could someone knows how to handle it?

Thanks a lot!

2

As you've found out already, we can't make callouts directly from triggers. Instead, we need to make the callout from a new (and asynchronous) transaction.

That's typically done with either @future or a class that implements the queueable interface.

In any case though, it's simply not possible to get the result of your callout into the initial trigger run (the one where you decided that the callout needed to happen). The asynchronous code that actually performs the callout will need to be responsible for updating appropriate record data in Salesforce as well (which will end up causing your trigger to run again, so be careful not to get yourself into an infinite loop).

In simple cases (just take the callout result and update data, no real logic involved), as long as you have the record Id, you can perform the update without a query by setting the record Id in the SObject constructor like so.

Account myAcctToUpdate = new Account(
    Id = givenId,
    Name = nameFromCallout,
    Phone = phoneFromCallout
);

update myAcctToUpdate;

Even if you do need more complex logic (and therefore need to query for the data you'll be using), since you're in a separate transaction, the governor limits are reset (a separate set of limits from those used by the trigger that started this whole process). Further, since this is an asynchronous transaction, you can use up to 200 SOQL queries (instead of the normal 100).

| improve this answer | |

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.