function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
NarenKNarenK 

Getting all field names of a object

Hi All,

 

I want to get all fieldnames of a object in apex. How can I do this?

 

For example for User object I want to get all its field names like AboutMe, AccountId , Email etc.

 

Any help on this really appreciated.

 

Regards,

Naren

Best Answer chosen by Admin (Salesforce Developers) 
Navatar_DbSupNavatar_DbSup

Hi,

 

try the below code sample:

 

public class Describer
{
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
public List<Pair> lstfieldname{get;set;}
public List <Pair> fields {get{return lstfieldname;} set{lstfieldname =value;}}
public List <SelectOption> objectNames{public get; private set;}
public String selectedObject {get; set;}

// Intialize objectNames and fields

public Describer() {
objectNames = initObjNames();
fields = new List<Pair>();
}
// Populate SelectOption list -

// find all sObjects available in the organization

private List<SelectOption> initObjNames() {
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;
}

// Find the fields for the selected object

public void showFields() {
//fields.clear();
system.debug('$$$$$' + selectedObject);
Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
system.debug('#######' + dfield );
Pair field = new Pair();
field.key = dfield.getname();
system.debug('#######4444' + field.key);
field.val = dfield.getType () + ' : ' + dfield.getLabel ();
lstfieldname.add(field);
}
}


public class Pair
{
public String key {get; set;}
public String val {get; set;}
}
}


<apex:page Controller="Describer">
<apex:form id="Describe">
<apex:pageBlock id="block2" >
<apex:pageblockbuttons location="top" >
<apex:commandButton value="Get Describe Object Fields" action="{!showFields}"/>
</apex:pageblockbuttons>
<apex:pageblocksection >
<apex:selectList value="{!selectedObject}" size="1">
<apex:selectOptions value="{!objectNames}"/>
</apex:selectList>
</apex:pageblocksection>
<apex:pageblocksection id="fieldList" rendered="{!not(isnull(selectedObject))}">
<apex:panelBar items="{!fields}" var="fls">
<apex:panelBarItem label="{!fls.key}">{!fls.val}</apex:panelBarItem>
</apex:panelBar>
</apex:pageblocksection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

All Answers

Navatar_DbSupNavatar_DbSup

Hi,

 

try the below code sample:

 

public class Describer
{
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
public List<Pair> lstfieldname{get;set;}
public List <Pair> fields {get{return lstfieldname;} set{lstfieldname =value;}}
public List <SelectOption> objectNames{public get; private set;}
public String selectedObject {get; set;}

// Intialize objectNames and fields

public Describer() {
objectNames = initObjNames();
fields = new List<Pair>();
}
// Populate SelectOption list -

// find all sObjects available in the organization

private List<SelectOption> initObjNames() {
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;
}

// Find the fields for the selected object

public void showFields() {
//fields.clear();
system.debug('$$$$$' + selectedObject);
Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
system.debug('#######' + dfield );
Pair field = new Pair();
field.key = dfield.getname();
system.debug('#######4444' + field.key);
field.val = dfield.getType () + ' : ' + dfield.getLabel ();
lstfieldname.add(field);
}
}


public class Pair
{
public String key {get; set;}
public String val {get; set;}
}
}


<apex:page Controller="Describer">
<apex:form id="Describe">
<apex:pageBlock id="block2" >
<apex:pageblockbuttons location="top" >
<apex:commandButton value="Get Describe Object Fields" action="{!showFields}"/>
</apex:pageblockbuttons>
<apex:pageblocksection >
<apex:selectList value="{!selectedObject}" size="1">
<apex:selectOptions value="{!objectNames}"/>
</apex:selectList>
</apex:pageblocksection>
<apex:pageblocksection id="fieldList" rendered="{!not(isnull(selectedObject))}">
<apex:panelBar items="{!fields}" var="fls">
<apex:panelBarItem label="{!fls.key}">{!fls.val}</apex:panelBarItem>
</apex:panelBar>
</apex:pageblocksection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

This was selected as the best answer
NarenKNarenK

Hi Jain,

 

Thank you very much for your post. It solved my problem.

 

Regards,

Naren

rajesh k 10rajesh k 10
Hi,
       I displayed all custom objects with in the pageblocktable.One of column name is Cretated date.How to retrieve all custom objects related created dates with in the pageblocktable column(Meanes created date column).

help me....
Narasimha Reddy 16Narasimha Reddy 16
Hi Navatar_DbSup,

thanks for your code
AngulixAngulix
Hi Navatar_DbSup, 
Very good piece of code, it makes a little very handy schema browser and brings so much as tutorial ! Many thanks for this. 
 
PandeiswariPandeiswari
Hi.

Thanks for the code. I would like to display the field data type as "Lookup" instead of "Reference". Is there way to do this.
AngulixAngulix
Hi Pandeiswari, 
Maybe this is what you're looking for. Change the line 
field.val = dfield.getType () + ' : ' + dfield.getLabel ();
with
if ( dfield.getType () == 'REFERENCE' ) {
    field.val = 'LOOKUP : ' + dfield.getLabel ();
} else {
    field.val = dfield.getType () + ' : ' + dfield.getLabel ();
}

 
PandeiswariPandeiswari
Hi Francoizix,

Thanks for your response. I tried this way. Issue is datatype is displaying as "REFERENCE" for all below default salesforce fields also. 
AccountId
Created By ID
Owner ID
Reports To ID
Master Record ID
Record Type ID
Last Modified By ID

I want to have to replace REFERNCE as lookup other than like above fields.

 
Revati BhavsarRevati Bhavsar
Hello Navatar_DbSup,
I have a trigger which fires when an applicant enters his details and saves the record.
I want to access all the fields entered by the applicant and the corresponding values of those fields.
Is there a way to do this by using a map?
 
shardul singh 23shardul singh 23
can anyone help me with the apex class to print list of fields 
Arpi Jakab 8Arpi Jakab 8
Map<String, Schema.SObjectField> schemaFieldMap = [CLASS_NAME].sObjectType.getDescribe().fields.getMap();
for (String field : schemaFieldMap.keySet())
System.debug(field);
Nikhil Kumar SrivastavaNikhil Kumar Srivastava
Execute this in anonymous window
Schema.DescribeSObjectResult a_desc = Account.sObjectType.getDescribe(); 
//for the Account object, you can replace that with any object you have, standard or custom
Map<String, Schema.SObjectField> a_fields = a_desc.fields.getMap();

for(Schema.sObjectField fld:a_fields.values()){ 
               system.debug(fld);
}
Check the result in Debug ​

Regards
Nikhil
ashu 6112ashu 6112
Hi Nikhil,

Your comment is working fine, but I am getting all the standard and custom fields, as we want only custom fields, how can we get that.

Thanks
gitguygitguy

That code seems only to show the fields that are /visible/ to the user/profile.  If, for instance, a field is not visible to all profiles, then the field seems invisible to describe().

I've also noticed this using the REST api's describe and force cli's "field list" command. 

The only way I've found to see ALL an objects fields regardless of visibility is through the SF UI.

Does anyone know of another way or a permission I can enable to see invisible fields?

Manish TendulkarManish Tendulkar
Method to loop through all fields of a standard or custom object and check if a field called Location__c exists or not in that object :- There are two ways to achieve this :-
Way 1 :-
// Get describe result for all objects
Map<String, Schema.SObjectType> allObjMap = Schema.getGlobalDescribe();

// Loop through all the objects        
for(String key : allObjMap.keySet())
{
    Map<String, Schema.SObjectField> fieldMap = allObjMap.get(key).getDescribe().fields.getMap();

    // Loop through all the fields and check if a custom field Location__c exists or not in this object
    for(String fieldName : fieldMap.keySet())
    {
        if(fieldName == 'Location__c')
        {
            System.debug(LoggingLevel.INFO, '#### Location__c field found, object name is ' + key);
        }
    }
}

Way 2 :- list of String of object names is ready which have to be looped through to check if a field named Location__c exists or not :- the name of this list of strings is objNameList :-
List<String> objNameList = new List<String>();
objNameList.add('Account');
objNameList.add('Company__c'); // add a custom object's API name to this list of strings
List<Schema.DescribeSObjectResult> describeObjList = Schema.describeSObjects(objNameList);
 
// Loop through all the objects       
for(Schema.DescribeSObjectResult describeObj : describeObjList)
{
    Map<String, Schema.SObjectField> fieldsMap = describeObj.fields.getMap();
    
    // Loop through all the fields and check if a custom field Location__c exists or not in this object
    for(String fieldName : fieldsMap.keySet())
    {
        if(fieldName == 'Location__c')
        {
            System.debug(LoggingLevel.INFO, '#### field Location__c is found by way 2 also in the object ' + describeObj.name);
        }
    }
}
Sachin Patil 57Sachin Patil 57
Hi all,
Can anyone help me in getting all the fields of sobjects without using the wrapper class