4

I have tried this code but i am only getting particular object fields but not its parent fields. any suggestions what i am missing?

public with sharing class FilterCriteriaComponentcontroller {
public String selectedObject {get; set;}
public String selectedField {get; set;}

Public FilterCriteriaComponentcontroller()
{   
    this.selectedObject = selectedObject;
}


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));
        //fieldMap.get(fieldName).getDescribe().getLabel();
    }
    return fieldNames;
} 
}   

1 Answer 1

5

You can use the getReferenceTo() method on a field to find the parent object that the field is referencing, and then recursively do describe field calls on the parent object to build this out.

My below example will not work for polymorphic relationships though (What, Who fields on Task,Events) as I hard coded .get(0) on the reference list. But this will work for 98% of relationship fields in SFDC and you could update code to work with Polymorphic Fields no problem.

Hacked this real quick to show you:

String selectedObject = 'Contact';
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));
        System.debug(fieldMap.get(fieldName).getDescribe().getType());
        if(fieldMap.get(fieldName).getDescribe().getType() == Schema.DisplayType.REFERENCE)
        {
            System.debug('References Object == ' + fieldMap.get(fieldName).getDescribe().getReferenceTo().get(0));
            Schema.SObjectType parentSchema = fieldMap.get(fieldName).getDescribe().getReferenceTo().get(0);
            Map<String, Schema.SObjectField> parentFieldMap = parentSchema.getDescribe().fields.getMap();
            for(String parentField : parentFieldMap.keySet())
            {
                fieldNames.add(new SelectOption(parentField,parentField));
            }
        }
    }
System.debug(fieldNames);

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_fields_describe.htm#apex_Schema_DescribeFieldResult_getRelationshipName

http://corycowgill.blogspot.com/2011/01/building-dynamic-soql-select-all-query.html

You must log in to answer this question.

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