+ Start a Discussion
Chamil MadusankaChamil Madusanka 

Find Object name and object fields in APEX code

Hi All,

 

I have two questions.

 

  1. I want to find whether the object is in our organization or not. I want to do this in APEX controller. Is there any method to do that?
  2. After find the object I want to retrieve the fields name of that object. This also want to perform in APEX controller. Is there any method to do that? 

Thanks in Advance!

 

 

Best Answer chosen by Admin (Salesforce Developers) 
MiddhaMiddha

Here is the code:

 

SObjectType objToken = Schema.getGlobalDescribe().get('Account');
        DescribeSObjectResult objDef = objToken.getDescribe();
        Map<String, SObjectField> fields = objDef.fields.getMap(); 
        
        Set<String> fieldSet = fields.keySet();
        for(String s:fieldSet)
        {
            SObjectField fieldToken = fields.get(s);
            DescribeFieldResult selectedField = fieldToken.getDescribe();
            System.debug(selectedField.getName());
        }

 

All Answers

kiranmutturukiranmutturu

from the below map u can get  the list of sobjects 

 

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

 

The keys reflect whether the sObject is a custom object

 

once u find the object then its easy to get the list of fields 

 

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

Chamil MadusankaChamil Madusanka

Hi Kiran,

 

Thanks for quick reply. I got the object name using your first code. But I want to get object fields from that dynamic object. I want to put a object name variable for object name. And also I want to get all the fields in particular object.

 

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

 

How can I do that?

 

Thanks in Advance!

MiddhaMiddha

Here is the code:

 

SObjectType objToken = Schema.getGlobalDescribe().get('Account');
        DescribeSObjectResult objDef = objToken.getDescribe();
        Map<String, SObjectField> fields = objDef.fields.getMap(); 
        
        Set<String> fieldSet = fields.keySet();
        for(String s:fieldSet)
        {
            SObjectField fieldToken = fields.get(s);
            DescribeFieldResult selectedField = fieldToken.getDescribe();
            System.debug(selectedField.getName());
        }

 

This was selected as the best answer
Bhaskar2013Bhaskar2013

I have a similar problem

List<sObject> results=new List<sObject>();

     

if(strSOQL != null && strSOQL != ''){

        results = Database.query(strSOQL);

      }

 

How can I use the "results" LIST of objects to get filed names that are retuned. My method uses strSOQL  as input param.

 

Thanks in avance.

SarfrazSarfraz
Hi Chamil Madusanka,
for Step 1: ----
for(Schema.SobjectType object : Schema.getGlobalDescribe().values()){
   System.debug(''+object.getDescribe().getName());
}