Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks LaceySnr! you saved my day :) thanks :) –  Sam Mar 5 at 6:29
    
its just that in the M.get(key).getLabel(), its working when i use the getDescribe() method too. Like: –  Sam Mar 5 at 9:57
    
M.get(key).getDescribe().getLabel(); –  Sam Mar 5 at 9:58
    
Good point Sam! My bad, will edit the answer –  LaceySnr Mar 5 at 10:07

You need to map them first using the Schema and DescribeFieldResult classes:

Map <String, String> labelToAPIName = new Map <String, String> ();

Map<String, Schema.SObjectField> fieldsMap = Schema.SObjectType.YOURCUSTOMOBJECTAPINAME.fields.getMap();
for (Schema.SObjectField field : fieldsMap.values())
{
    labelToAPIName.put(field.getDescribe().getLabel(), field.getDescribe().getName());
}

String APINAME = labelToAPIName.get('YOURFIELDLABEL');

Refer to the following documentation:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_namespace_Schema.htm

in particular "DescribeFieldResult Class"

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.