Is there a more efficient way to determine the name field of an sobject other than iterating through all the fields obtained via DescribeSOBjectResult?
Often, the name field is simply Name
but in some occasions with standard objects it is not. For example, Case's name field is CaseNumber
.
Here is the apex method I'm using, but seems inefficient to loop through all the fields:
public String getNameField( SObjectType sobjectType ) {
DescribeSObjectResult objDescribe = sobjectType.getDescribe();
Map<String, SObjectField> fieldsMap = objDescribe.fields.getMap();
for ( SObjectField fieldToken : fieldsMap.values() ) {
DescribeFieldResult fieldDescribe = fieldToken.getDescribe();
if ( fieldDescribe.isNameField() ) {
return fieldDescribe.getName();
}
}
return 'Name'; // default
}
Name
field first and only check all fields if that isn't it. More efficient (on average) but not very elegant...