9

I have created an API But struggling in converting String to Schema.SObjectField as If there is any possible way to cast string into Schema.SObjectField field type for example Account.example__c to Schema.SObjectField.

And if not can we seprately bind and concate them.

2
  • Is 'Account.example__c' the string you're trying to convert?
    – Nick C
    Commented Sep 20, 2017 at 8:03
  • Yep it could be of any type as in generic For example object/customobject.examplefield__c Commented Sep 20, 2017 at 8:04

3 Answers 3

11

You could try:

String testString = 'Account.example__c';

List<String> splitString = testString.split('\\.');

Schema.SobjectField theField = Schema.getGlobalDescribe().get(splitString[0]).getDescribe().fields.getMap().get(splitString[1]);

This obviously has no error handling in it, but hopefully it gets you started.

Or breaking this down to understand it:

String testString = 'Account.example__c';

List<String> splitString = testString.split('\\.');

// store the object/field names
String objectName = splitString[0];
String fieldName = splitString[1];

// get the SObjectType

Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectName);

// get the fields on the object

Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();

// The key to the map is the api name of the field

Schema.SobjectField theField = fieldMap.get(fieldName);
7

Yo can use Schema.getGlobalDescribe() method to retrieve Map of field of Sobject and then get desired field by name from this Map. Important, that keys for sobject names and sobject field names are stored in lower case.

String fieldName = 'Account.OwnerId';
List<String> parts = fieldName.split('\\.');
Map<String, SObjectField> fieldsMapByName = Schema.getGlobalDescribe().get(parts.get(0).toLowerCase()).getDescribe().fields.getMap();
SObjectField desiredSobjField = fieldsMapByName.get(parts.get(1).toLowerCase());
2

Schema.getGlobalDescribe() is super slow, instead, You can use Type.forName method:

String testString = 'Account.Id';
List<String> splitString = testString.split('\\.');
String objectName = splitString[0];
String fieldName = splitString[1];
    
SObjectType objectType = ((SObject)Type.forName(objectName).newInstance()).getSObjectType();
SObjectField objectField = objectType.getDescribe().fields.getMap().get(fieldName);
1
  • This originates from this previous Q&A which has various other interesting points within it.
    – Phil W
    Commented Feb 25, 2022 at 15:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .