[SalesForce] I have the label of an object’s field. I want to retrieve its API name

I have a map. the string is the label of a field of an object and the integer is the value that must go into this field of that object. But i don't know how to retrieve the API name of those fields from their labels. Please help!

Thanks in advance!

Best Answer

This is possible by pulling the describe information for all fields on the object, and then running over each entry, calling getLabel() and comparing it with the value you have.

Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap();

for(String key : M.KeySet())
{
  if(testLabel == M.get(key).getDescribe().getLabel())
  {
    // key might be the API name of the field you want
  }
}

You'll notice I said might in the comment. That's because not only can labels be changed at any time, but it's also possible to have two fields with the same label. For the latter reason alone I'd highly recommend looking for an alternative way to deal with fields in your application.

If the user is choosing a label from a picklist, maybe make the values the API names of the fields. These are always going to be unique and therefore less error prone.

Related Topic