3

When I google I find a lot of answers on how to get field label using field name.

For example:

SObjectType type = Schema.getGlobalDescribe().get('Account');
Map<String,Schema.SObjectField> mfields = type.getDescribe().fields.getMap();

Is it possible to do it like using a label to get the Field Name?

If I have a 'String Label' and I want to use this label to get the field Name from Some SObject. How should I do it?

Thanks for Helping!

1
  • labels can be duplicate whereas API name is unique Commented Aug 14, 2018 at 10:06

1 Answer 1

6

You can create a method like this, which will take ObjectName and FieldLabel as input and return the FieldAPI.

Note that, field label can be duplicate so you need to take special care for this.

public static String getFieldAPIName (String objectName, String fieldLabel)
{
    SObjectType type = Schema.getGlobalDescribe().get(objectName);
    Map<String,Schema.SObjectField> mfields = type.getDescribe().fields.getMap();
    for(String strField:mfields.keySet())
    {
        SObjectField fl = mfields.get(strField);
        if(fieldLabel == fl.getDescribe().getlabel())
        {
            return strField;
        }
    }
}

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