Activity Forums Salesforce® Discussions How to get all the fields of Sobject using Dynamic Salesforce Apex?

  • shariq

    Member
    September 19, 2018 at 7:57 am

    Hi,

    You can use the methods of schema class. Below is a snippet of code that you can use :

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

    Schema.SObjectType s = m.get('API_Name_Of_SObject') ;

    Schema.DescribeSObjectResult r = s.getDescribe() ;

    Map<String,Schema.SObjectField> fields = r.fields.getMap();

    Thanks

  • Avnish Yadav

    Member
    September 19, 2018 at 9:10 am

    Hello Anurag,
    Try this code
    `
    public class ControllerClassName
    {
    public List strList { get;set; }

    public void autoRun()
    {
    Map objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();

    strList = new List(objectFields.keySet());

    }
    }
    `
     
    Thanks.

  • Parul

    Member
    September 19, 2018 at 9:48 am

    You can use this Apex code with Vf page :

    <apex:page controller="GetSobjectDynamic" action="{!autoRun}">

    <apex:form>

    <apex:pageblock>

    <apex:pageblockTable value="{!strList}" var="obj">

    <apex:column value="{!obj}"/>

    </apex:pageblockTable>

    </apex:pageblock>

    </apex:form>

    </apex:page>

    ...........

    public class GetSobjectDynamic
    {
    public List<String> strList { get;set; }

    public void autoRun()
    {
    Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();

    strList = new List<String>(objectFields.keySet());

    } }

    Hope thsi will help you.

    Thanks

  • Aman

    Member
    September 29, 2018 at 4:48 pm

    Hi,

    Below is a snippet of code that you can use :

    Account account = [select Id, AnnualRevenue, Website from Account limit 1];

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

    Map<String, Object> queriedFieldValues = new Map<String, Object>();

    for (String fieldName: schemaFieldMap.keySet()) {

    try {

    queriedFieldValues.put(fieldName, account.get(fieldName));

    } catch (SObjectException e)    {

    // Intentional capture

    }

    }

    System.debug(queriedFieldValues);

    Thanks.

Log In to reply.

Popular Salesforce Blogs