How to efficiently determine the `name` field of an sobject for dynamic query?
Elegant? Perhaps not, but checking 'Name'
first and only iterating as a fallback plan should be more efficient. With every custom object and most standard objects, this shortcut will cut out the looping and additional describes entirely.
My natural inclination is to start with a positive condition:
public static String getNameField(SObjectType sObjectType)
{
Map<String, SObjectField> fields = sObjectType.getDescribe().fields.getMap();
if (fields.containsKey('Name') && fields.get('Name').getDescribe().isNameField())
{
return 'Name';
}
// iteration logic
return 'Name'; // fallback if iteration fails
}
It may be more elegant, however, to use a negative condition and DRY on the return 'Name'
front.
public static String getNameField(SObjectType sObjectType)
{
Map<String, SObjectField> fields = sObjectType.getDescribe().fields.getMap();
if (!fields.containsKey('Name') || !fields.get('Name').getDescribe().isNameField())
{
// iteration logic
}
return 'Name';
}
A little late to the party, but SOQL could help here too:
SELECT QualifiedApiName
FROM FieldDefinition
WHERE EntityDefinition.QualifiedApiName IN :listOfSObjectNames
AND IsNameField = TRUE
It does consume one query but that is probably more efficient than looping through describes.