Lightning Component – How to display Objects and its fields

To display Objects and its fields in a lightning component, follow the simple steps:

First of all, create an apex class called “ObjectsFieldsList” which will act as our controller. The “getallobjects” method returns the list of sObjects.

The “getAllFields” takes sObject as parameter and returns its fields.

public class ObjectsFieldsList{
    @AuraEnabled
    public static List<string> getAllObjects(){
List<string> SObjectList = new List<string>();

for(Schema.SObjectType objTyp : Schema.getGlobalDescribe().Values()){
   String name = objTyp.getDescribe().getName();
   // Exclude all the unwanted Sobjects e.g. History, Share etc..

 if(!name.containsignorecase('history') && !name.containsignorecase('tag')&&
    !name.containsignorecase('share') && !name.containsignorecase('feed')){      
      SobjectList.add(name);
      System.debug( 'Name : ' + name);
  }

}
        return SObjectList;
}
     @AuraEnabled
    public static List<String> getAllFields(String fld){
        List<String> fieldList = new List<String>();
Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
Schema.SObjectType sobjType = gd.get(fld); 
Schema.DescribeSObjectResult describeResult = sobjType.getDescribe(); 
Map<String,Schema.SObjectField> fieldsMap = describeResult.fields.getMap(); 
    for(string str: fieldsMap.keySet()){
				fieldList.add(fieldsMap.get(str).getDescribe().getLabel());                
            }
    return fieldList;      
}
}

Next create a component called as “DisplayObjects” and update the following code

<aura:component controller="ObjectsFieldsList" implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes" access="global">
	  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
       
   <div class="slds-col">     <lightning:combobox aura:id="SobjectList" name="SobjectList" label="Select Object"
                            placeholder="Select Object" onchange="{!c.getfields}"
                            value=""
                          /></div>

    <div class="slds-col"> <lightning:combobox aura:id="FieldsList" name="FieldsList" label=""
                            placeholder="" value="" diabled="true" /></div>
    
</aura:component>

Finally update the below controller code:

({
    // Load expenses from Salesforce
    doInit: function(component, event, helper) {
        // Create the action
        var action = component.get("c.getAllObjects");
        // Add callback behavior for when response is received
        var opts=[];
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log(response.getReturnValue());
            if (state == "SUCCESS") {
               var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
            }
                 component.find("SobjectList").set("v.options", opts);
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        // Send action off to be executed
        $A.enqueueAction(action);
    },
    getfields: function(component, event, helper) { 
    var action = component.get("c.getAllFields");
       var userObj=component.find("SobjectList").get("v.value");
        action.setParams({
            "fld": userObj
        });
          // Add callback behavior for when response is received
        var opts=[];
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log(response.getReturnValue());
            if (state == "SUCCESS") {
               var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
            }
                 component.find("FieldsList").set("v.options", opts);
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        // Send action off to be executed
        $A.enqueueAction(action);
    }
})

In the component, we are creating a initialization method which calls the above controller as soon as component loads.

The doInit function in the controller calls the “getAllObjects” method from our apex class. The apex class acts as the server side controller.

The objects list returned by the apex class is parsed by the doInit function. It is than assigned to the drop down using the Id attribute.

The on change function on object drop down calls the “getAllFields” method of the apex class. The fields list returned by apex class is populated in the fields drop down.

In this way, you can display objects and its fields in a lightning component. Likewise you can also display record types or other properties of an object.

Now just add the component to a tab and see your results. To see how to add the lightning component to a tab, follow this link.

Lightning Component - How to display Objects and its fields

Also read: http://initaura.com/lightning-component-how-to-filter-records-based-on-user-input/

Leave a Reply

Your email address will not be published.

Scroll to top