Search code examples
salesforcevisualforceapex

How to get the field label names for the Selected Object objects instead of Field API Names in Visualfroce page?


public class Testing4 {

    public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

    public String selectedObject {get; set;}

    public String selectedField {get; set;}

    Public Testing4()
    {   
        selectedObject = 'account';
    }

    public List<SelectOption> getObjectNames() 
    {
        List<SelectOption> objNames = new List<SelectOption>();
        List<String> entities = new List<String>(schemaMap.keySet());
        entities.sort();
        for(String name : entities)
        {
            objNames.add(new SelectOption(name,name));
        }
        return objNames;
     }

     public List<SelectOption> getObjectFields() 
     {
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

            Schema.SObjectType ObjectSchema = schemaMap.get(selectedObject);

            Map<String, Schema.SObjectField> fieldMap = ObjectSchema.getDescribe().fields.getMap();


            List<SelectOption> fieldNames = new List<SelectOption>();
            for (String fieldName: fieldMap.keySet()) 
            {  
              fieldNames.add(new SelectOption(fieldName,fieldName));

            }
            return fieldNames;
      }       
}

How to get the field label names for the Selected Object objects instead of Field API Names in Visualfroce page?

Here i am getting All the field API names for the selected Object, but i need only Field Lables (not API names).


Solution

  • Try this to get Label Name from Salesforce Object Fields:

    Schema.getGlobalDescribe().get('ObjectName').getDescribe().fields.getMap().get('FieldName').getDescribe().getLabel();
    

    Your code:

    public List<SelectOption> getObjectFields() 
     {
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    
            Schema.SObjectType ObjectSchema = schemaMap.get(selectedObject);
    
            Map<String, Schema.SObjectField> fieldMap = ObjectSchema.getDescribe().fields.getMap();
    
    
            List<SelectOption> fieldNames = new List<SelectOption>();
            for (String fieldName: fieldMap.keySet()) 
            {  
              String fName = fieldMap.get(fieldName).getDescribe().getLabel();
              fieldNames.add(new SelectOption(fName, fName));
    
            }
            return fieldNames;
      }