GetObjectName Invocable Apex Action

When building a flow, sometimes the need arises to perform logic based a record’s object type. Let’s say you have a flow that does the same thing and you want to drop it on a record page for three different objects. To do that, you’d need to know which object the flow is starting from then do the object-specific Lookups based on that. This is something that is easily done with Apex code, but is not so straightforward using Flows.

Luckily, we can leverage an invocable apex action that can be called by flow to accomplish exactly this. At a high-level, the action will allow us to pass in the Record ID into the flow and will return the record’s object API name.

In more detail, the Record Id passed into the GetObjectName invocable action from the flow is converted from a string into an ID in order to leverage the “.getSobjectType().getDescribe().getName();” method (which requires an ID type). This method returns the Object API Name as a String that can then be used in the flow in whichever way you choose, such as using a decision based on which API name is returned (Ex: If vReturnedObjectType = Contact, perform Logic A. Else if vReturnedObjectType = Lead, perform Logic B)

Leveraging the GetObjectName action in a flow is simple, by following the below steps:

1. Drop an action onto the flow canvas. When looking for the components find the component called “GetObjectName”:

2. Click the “Include” toggle and assign a record Id string into the recordIdStrings action input:

3. Check “Manually assign variables” to assign the output of the component (Object API Name as a string) to a flow variable. You can either assign it to an existing string variable in the flow, or create a new one to be used.

Below is the code you’d use for the action:

Apex Class:

global class GetObjectName {

 public static List<string> returnObjectName(List<string> recordIdStrings){
 // object Ids to return
 List<string> objectNames = new List<string>();
 // get record name
 Id recordId = Id.valueOf(recordIdStrings[0]);
 String objectName = recordId.getSobjectType().getDescribe().getName();
 // add object name to list
 // return
 return objectNames;

Test Class:

public class GetObjectNameTest {
 public static void testReturnObjectName(){
 //Create and insert lead record
 Lead testLead = new Lead();
 testLead.Status = 'Open';
 testLead.Salutation = 'Mr.';
 testLead.FirstName = 'Tim';
 testLead.LastName = 'Testin';
 testLead.Company = 'Test Company';
 insert testLead;
 //Return newly created lead record 
 List LeadList = new List();
 LeadList = [Select Id from Lead where FirstName = 'Tim' AND LastName = 'Testin' AND Company = 'Test Company' LIMIT 1];
 List IdList = new List ();
 For (Lead l: LeadList){
 List results = GetObjectName.returnObjectName(IdList);
 System.assertEquals('Lead', results[0], 'ERROR IN GetObjectNameTest.testReturnObjectName : sObject Name did not match');