[Apex][Salesforce] How to make a callout with a DML operation in a process builder

José Castro
Devsys
Published in
2 min readAug 30, 2018

For use an Apex Class in a Process Builder, you need to create one method with a this annotation (just one per class):

Note: Annotation is like a decorator for python

@InvocableMethod(label='name' description='I am')
public static List<Object> useMeInProcessBuilder(List<Object> data){
}

The Object, need to be the type that you want it, also the method need to be static. More info and considerations, here.

Then this method will be available in your process builder for use, make sure to use the object that you need.

With that in mind, for avoid this exception, when you try to make a callout :

You have uncommitted work pending. Please commit or rollback before calling out

You need to wrap up other method with this annotation:

@future(callout=true)
public static void IllDoACallout(<Primitive type> here){
}

The method needs to be static and doesn’t return anything. Also only accepts primitive types as an input (why?). This will run asynchronously, so every DML operation will be running in his context. (Also you can lock a record). More info about future, here.

So, inside of your method, you can perform any callout and any DML operation without triggered the exception before (Unless you make some nasty things inside, you’re adviced).

So how you link this together? Like this (example):

public class ProcessB {    public static Object calloutMethod(Object a){
//Http requests
return a;
}

public static void makeDMLOperation(Object b){
insert b;
}
@future(callout=true)
public static void makeTheCallout(Id objectId){
Object c = [SELECT Name FROM MyObject WHERE Id = :objectId];
ProcessB.makeDMLOperation(
ProcessB.calloutMethod(c));
}
@InvocableMethod(label='name' description='I am')
public static List<Object> callFromPB(List<Object> d){
for(Object obj: d){
ProcessB.makeTheCallout(obj.Id);
}
return d; // *
}
}
  • * You’re returning the same list from the input, remember that the method run asynchronously. If you want to return the value modified, you can create a copy of the element (because the element in the list is read-only) and make the callout ouside of this process.

I’ll added more updates on this, if I find a better way to do it.

--

--