Activity Forums Salesforce® Discussions How to get all the field names of an object using SOQL?

  • PRANAV

    Member
    March 21, 2018 at 8:58 am

    Hi Kapil,

    The below code snippet will help you

    Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    Map <String, Schema.SObjectField> fieldMap = schemaMap.get('Account').getDescribe().fields.getMap();
    for(Schema.SObjectField sfield : fieldMap.Values())
    {
    schema.describefieldresult dfield = sfield.getDescribe();
    system.debug('@@@API Name : '  + dfield.getname());
    system.debug('####Label Name : ' + dfield.getLabel ());
    }

    From this you will get the API Name as well as Label Name. For another sObject replace Account with your sObject.

    Hope this helps you.

  • Adarsh

    Member
    March 21, 2018 at 11:23 am

    Hi Kapil,

    you may use this,

    String ObjId = stdController.getId();
    DescribeSObjectResult describeResult = Id.valueof(ObjId).getSObjectType().getDescribe();
    List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );
    String query =' SELECT Account.Name,' +String.join( fieldNames, ',' ) +' FROM ' +describeResult.getName() +' WHERE ' +' id = :ObjId ' +' LIMIT 1 ';
    List<Contact> records = Database.query( query );

    Hope it helps 🙂

  • Parul

    Member
    September 18, 2018 at 1:44 pm

    Hi Kapil,

    Try the follwing code

    Map <String, Schema.SObjectType> schemaMapofAllSobject = Schema.getGlobalDescribe();
    Map <String, Schema.SObjectField> MapofdesiredObject = schemaMap.get('Contact').getDescribe().fields.getMap();
    for(Schema.SObjectField sObjectfield : MapofdesiredObject.Values())
    {
    schema.describefieldresult dfield = sObjectfield.getDescribe();
    system.debug(‘@@@API Name : ‘  + dfield.getname());
    system.debug(‘####Label Name : ‘ + dfield.getLabel ());
    }

    Note -: Here We use Contact as our sObject.

    Thanks

  • shariq

    Member
    September 20, 2018 at 11:35 pm

    Hi,

    Use standard schema class to get all fields of sobject, it also returns the properties of fields.

    Map <String, Schema.SObjectType> mapSobjects = Schema.getGlobalDescribe();
    Map <String, Schema.SObjectField> fieldMap = schemaMap.get(‘sobject__c’).getDescribe().fields.getMap();

    Hope this helps.

  • Parul

    Member
    September 21, 2018 at 3:57 am

    Adding more point:

    You not only get the sobject name, fields but also its properties. You can use properties in your logic.

Log In to reply.

Popular Salesforce Blogs