How to get Salesforce Custom Field Ids in Apex

| By Webner

We can get the Ids of Salesforce Object’s custom fields in the Apex code using Tooling API. Following is the example code for the same:

String objectDevName = 'ObjectName';
ToolingAPI toolingAPI = new ToolingAPI();
List objectData = (List)toolingAPI.query('Select Id From CustomObject Where DeveloperName = \'' + objectDevName + '\'').records;
Map customFieldIds = new Map();
if (objectData!=null && !objectData.isEmpty()) {
ToolingAPIWSDL.sObject_x objectDetails = objectData[0];
Id objectId = objectDetails.Id;
List customFields = (List)toolingAPI.query('Select Id, DeveloperName From CustomField Where TableEnumOrId = \'' + objectId + '\'').records;
for(ToolingAPIWSDL.sObject_x fieldDetails: customFields){
customFieldIds.put(fieldDetails.DeveloperName, String.valueOf(fieldDetails.Id).substring(0, 15));

Leave a Reply

Your email address will not be published. Required fields are marked *