function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Harshwardhan Singh KarkiHarshwardhan Singh Karki 

how to get the Id of custom field in apex(dynamically)?

Ex: Let Custom Object - A__c  have Picklist Field (Custom Field) - P__c , so how to get Id of P__c in apex ?
VinayVinay (Salesforce Developers) 
Hi Harshwardhan,

You can try using Tooling API.  Something like below.
ToolingAPI toolingAPI = new ToolingAPI();
 
// Query CustomObject object by DeveloperName (note no __c suffix required)
List<ToolingAPI.CustomObject> customObjects = (List<ToolingAPI.CustomObject>)
     toolingAPI.query('Select Id, DeveloperName, NamespacePrefix From CustomObject Where DeveloperName = \'Test\'').records;
 
// Query CustomField object by TableEnumOrId (use CustomObject Id not name for Custom Objects)
ToolingAPI.CustomObject customObject = customObjects[0];
Id customObjectId = customObject.Id;
List<ToolingAPI.CustomField> customFields = (List<ToolingAPI.CustomField>)
     toolingAPI.query('Select Id, DeveloperName, NamespacePrefix, TableEnumOrId From CustomField Where TableEnumOrId = \'' + customObjectId + '\'').records;
 
// Dump field names (reapply the __c suffix) and their Id's
System.debug(customObject.DeveloperName + '__c : ' + customObject.Id);
for(ToolingAPI.CustomField customField : customFields)
     System.debug(
          customObject.DeveloperName + '__c.' +
          customField.DeveloperName + '__c : ' +
          customField.Id);

https://andyinthecloud.com/2014/01/05/querying-custom-object-and-field-ids-via-tooling-api/
https://salesforce.stackexchange.com/questions/17327/how-to-get-the-entity-id-for-a-custom-field-in-apex

Also check below limitation for apex describe information should also give Field ID's

https://ideas.salesforce.com/s/idea/a0B8W00000GdiFcUAJ/apex-describe-information-should-also-give-field-ids

Please mark as Best Answer if above information was helpful.

Thanks,
usman Mustafviusman Mustafvi
In Apex, you can dynamically retrieve the Id of a custom field (such as a picklist field) by using the following method:
Use the DescribeFieldResult class to retrieve the field's metadata.
Copy code
Schema.DescribeFieldResult fieldResult = A__c.P__c.getDescribe();
Use the getId() method to retrieve the Id of the field.
Copy code
Id fieldId = fieldResult.getId();
You can also use the getName() method to retrieve the name of the field as a string.
Copy code
String fieldName = fieldResult.getName();
So the complete code will look like this:
Copy code
Schema.DescribeFieldResult fieldResult = A__c.P__c.getDescribe(); Id fieldId = fieldResult.getId();
Please keep in mind that you need to replace A__c with the actual name of your custom object and P__c with the actual name of your picklist field.
Also, you can use this approach to get the Id of any custom field, not just picklist fields, on any custom object