Skip to content

Add Dynamic Related List on Record Page

Hello there,

In this blog, we will learn about how we can create a lightning component to show dynamic related list on the record page. For this, we will pass three things

  1. Child object’s API name,
  2. A dynamic list of fields of the child object,
  3. Relationship field created in the child object.

using the design resource.

Note: Using design resource we are exposing these three attributes to builder tool – Lightning App Builder

 

CodingMania - Student Saturday - Living The Trailhead

Step 1: Create a lightning component

<aura:component implements="force:appHostable,flexipage:availableForallPageTypes,force:hasRecordId,force:lightningQuickAction" access="global" controller="DynamicRelatedListController" >
    <!-- Attributes -->
    <aura:attribute name = "objectName" type = "String"/>
    <aura:attribute name = "fieldList"  type = "String"/>
    <aura:attribute name = "relatedField" type = "String"/>
    <aura:attribute name = "data" type="List"/>
    <aura:attribute name="columns" type="List"/>
    <!-- handler-->
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    <div style="height: 300px">
        <lightning:datatable
                keyField="Id"
                data="{!v.data}"
                columns="{!v.columns}"
                hideCheckboxColumn="true"/>
    </div>
</aura:component>

Step 2: Write below code in the design component

<design:component>
    <design:attribute name="objectName" label="Object API Name"  />
    <design:attribute name="fieldList" label="List Of Fields"  />
    <design:attribute name="relatedField" label="Relationship Fields"  />
</design:component>

Step 3: Write an apex class to get the records from the server side.

public class DynamicRelatedListController {
    
    @AuraEnabled
    public static CoulmnAndDataWrapper getFieldSet(String sObjectName, List<String> listOfFields, Id recordId, String relationshipField) {
        CoulmnAndDataWrapper cdw = new CoulmnAndDataWrapper();
        List<Columns> columns = new List<Columns>();
        String fieldsToFetch = '';
        
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
        Schema.SObjectType ctype = gd.get(sObjectName); 
        Map<String, Schema.SobjectField> fmap = ctype.getDescribe().fields.getMap();  
        
        // Generating a list of columns
        for(String f : listOfFields ){
            if(f== 'Name'){
                columns.add(new Columns(fmap.get(f).getDescribe().getLabel(), 'linkName' , 'url'));
            }
            else{
                columns.add(new Columns(fmap.get(f).getDescribe().getLabel(), f, String.valueOf(fmap.get(f).getDescribe().getType()).toLowerCase()));
            }
            if(fieldsToFetch != ''){
                fieldsToFetch += ',';
            }
            fieldsToFetch += f;
        }
        // Get the records of requested object
        List<sObject> listData = Database.query('Select Id, ' + fieldsToFetch + ' From ' + sObjectName + ' where '+ relationshipField + ' = :recordId ');
        
        cdw.columns = columns;
        cdw.listData = listData;
        return cdw;
    }
    
    class Columns{
        @AuraEnabled public String label;
        @AuraEnabled public String fieldName;
        @AuraEnabled public String type;
        
        public Columns(String label, String fieldName, String type){
            this.label = label;
            this.fieldName = fieldName;
            this.type = type;
        }
    }
    
    class CoulmnAndDataWrapper{
        @AuraEnabled public List<Columns> columns;
        @AuraEnabled public List<sObject> listData;
    }
    
}

Step 4: Write the below code in the Javascript Controller

({
    init: function(component, event, helper) {
        var listOfColumns = component.get("v.fieldList").split(",");
        //Call server side function to get the data
        var action = component.get("c.getFieldSet");
        action.setParams(
            { 
                sObjectName : component.get("v.objectName") ,
                listOfFields : listOfColumns,
                recordId:component.get("v.recordId"),
                relationshipField:component.get("v.relatedField")
            });
        action.setCallback(this, function(data){
           
            const dtColumns = data.getReturnValue().columns;
            const dtData = data.getReturnValue().listData;
            dtColumns.forEach(function(record){
                if(record.fieldName =='linkName'){
                  
                    record.typeAttributes = {label: {fieldName:'Name'}, target:'_blank'} ;
                }
            });
            component.set("v.columns",dtColumns);
            dtData.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                
            component.set("v.data",dtData);
            
        });       
        
        $A.enqueueAction(action);
        
    }
    
});

CodingMania - Student Saturday - Living The Trailhead second

 

Note: We learned how to create the dynamic lightning data-table with a dynamic list of fields and how to use design resource.

Published inCoding ManiaSalesforce Student Group

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *