Dynamic retrieval of object label & field label
You can describe sObjects either by using tokens or the describeSObjects Schema method.
Apex Class
public with sharing class DescibeDemoController
{
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
public String selectedObject {get; set;}
public List<FieldWrapper> listField{get;set;}
public DescibeDemoController()
{
listField = new List<FieldWrapper>();
}
// find all sObjects available in the organization
public List<SelectOption> getListObejectName()
{
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()
{
listField.clear();
Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
FieldWrapper wObj = new FieldWrapper();
wObj.fieldName = dfield.getLabel ();
wObj.fieldAPIName = dfield.getname();
listField.add(wObj);
}
}
public class FieldWrapper
{
public String fieldName {get; set;}
public String fieldAPIName {get; set;}
}
}
<apex:page controller="DescibeDemoController">
<apex:form id="Describe">
<apex:pageBlock id="block2" >
<apex:pageblockbuttons location="top" >
<apex:commandButton value="Show Fields" action="{!showFields}" />
</apex:pageblockbuttons>
<apex:pageblocksection >
<apex:pageBlockSectionItem >
<apex:outputLabel >Object Name</apex:outputLabel>
<apex:selectList value="{!selectedObject}" size="1">
<apex:selectOptions value="{!ListObejectName}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
</apex:pageBlock>
<apex:pageBlock id="result" title="Field Detail for {!selectedObject}" rendered="{!if(listField.size > 0 ,true,false)}" >
<apex:pageBlockTable value="{!listField}" var="field" rendered="{!if(listField.size > 0 ,true,false)}">
<apex:column value="{!field.fieldName }" headerValue="Name" />
<apex:column value="{!field.fieldAPIName }" headerValue="API Name"/>
</apex:pageblockTable>
</apex:pageblock>
</apex:form>
</apex:page>
Related link
how can we order them by alphabets
ReplyDeleteuse .sort() method
DeleteHow can I display field values and display the Field names and values in LWC and not in VF page.
ReplyDelete