+ Start a Discussion
jucuzoglujucuzoglu 

How do display a dynamic list of object fields

Using this code I can get a list of my objects

 

 

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

 

 

I can look through that list and get the Schema.SObjectType

 

Now I want to display the fields within that SObjectType in a manner similar to

 

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

 

The problem is in that last example Account is static, where I need to use a variable to designate the proper SObject Type since I will be looping through them.

hitzhitz

Hi,

 

see below code moght b this helps for u

 

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

for(String fieldName : fieldMap.keyset()){
    query = fieldName + ',' + query;
}

System.debug('---------------->> a ' + query);

jucuzoglujucuzoglu

The problem I have is trying to figure out how to call the object dynamicly.

 

For example in your code here:

 

Map<String, Schema.SObjectField> fieldMap = schemaMap.get('Account').getDescribe().fields.getMap();

 

 

You explicitly call the get method on the object

 

 

.get('Account')

 

However I may run a loop over several object types and the same line of code needs to grab the fields for each of the objects so using the code above it would continually descrive the code for the Account object. Are you aware of how to call the function dynamically?

 

 

 

vck01vck01

if we can observe .get('Account') .Here account is a string we are passing 

 

wo we can actually pass any string(valid obejct name ) to get the respective describe results

 

 

Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
String objectName='Contact';
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(ObjectName).getDescribe().fields.getMap();
Now it gets me the contact type.

 

 

Thanks,

Chaitanya

 

S_2013S_2013

Chaitanya,

 

Your code saved my day. Cant thank you enough!

 

Actually it is pretty simple but I really could NOT find this on any Apex docs.

 

This line is fairly common : Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap(); and is in the docs pretty well, but this flavour: Schema.SObjectType.get(objnameString) isnt mentioned anywhere or atleast i couldn't find it.

 

Thanks for your help.

 

S_2013

 

 

Abhishek Kumar SharmaAbhishek Kumar Sharma
Hi,
Map<String, Schema.SObjectField> mapOfFieldVsAPIName =Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();
System.debug('mapOfFieldVsAPIName --->'+mapOfFieldVsAPIName );

In above code 'Contact'   is object API Name. We have to provide API name of the object If your org contains a namespace than object name must be preceded by namespace likes this 'namespace__ObjectName'.

Thanks.