Activity Forums Salesforce® Discussions Can we use fieldSet in the lightning component? if yes then how?

  • Laveena

    Member
    October 4, 2019 at 7:17 am

    Hi Piyush,

    This component can be used to display child records or all the records of an object. See below component code.

    <c:LightningTable
    sObjectName="Opportunity"
    fieldSetName="opportunitytable"
    parentFieldName="AccountId"
    parentRecordId="00190000016cYL6AAM"/>

    As you can see in the above component we have 4 attributes. These attributes can control the behaviour of the component. sObjectName : Name of the object which you want to query records from. (Required) fieldSetName: Name of the fieldset which will be used for the columns in the table. (Required) parentFieldName: If you want to display only child records of a parent then this should be specified. (Optional) parentRecordId: Parent record Id if you are displaying child records of a parent. (Optional) LightningTable is a parent component which is working as a table wrapper. This parent component is using a LightningCell component to display each cell of the row based on the data type. You can add more data types into the code as per your requirement. I am providing you all the code related to these components so you can update it as per your business use case. Fieldset is used to add/remove columns dynamically to the table.

    <aura:component controller="LightningTableController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="sObjectName" type="String"/>
    <aura:attribute name="fieldSetName" type="String"/>
    <aura:attribute name="fieldSetValues" type="List"/>
    <aura:attribute name="tableRecords" type="List"/>
    <aura:attribute name="parentFieldName" type="String"/>
    <aura:attribute name="parentRecordId" type="String"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <div class="slds">
    <table class="slds-table slds-table--bordered">
    <thead>
    <tr>
    <aura:iteration items="{!v.fieldSetValues}" var="field">
    <th> {!field.label}</th>
    </aura:iteration>
    </tr>
    </thead>
    <tbody>
    <aura:iteration items="{!v.tableRecords}" var="row">
    <tr>
    <aura:iteration items="{!v.fieldSetValues}" var="field">
    <td>
    <c:LightningCell record="{!row}" field="{!field}"/>
    </td>
    </aura:iteration>
    </tr>
    </aura:iteration>
    </tbody>
    </table>
    </div>
    </aura:component>

    LightningTableController [APEX Class]
    public class LightningTableController {

    @AuraEnabled
    public static String getFieldSet(String sObjectName, String fieldSetName) {
    String result = '';
    try{
    SObjectType objToken = Schema.getGlobalDescribe().get(sObjectName);
    Schema.DescribeSObjectResult d = objToken.getDescribe();
    Map<String, Schema.FieldSet> FsMap = d.fieldSets.getMap();
    system.debug('>>>>>>> FsMap >>> ' + FsMap);
    if(FsMap.containsKey(fieldSetName))
    for(Schema.FieldSetMember f : FsMap.get(fieldSetName).getFields()) {
    if(result != ''){
    result += ',';
    }
    String jsonPart = '{';
    jsonPart += '"label":"' + f.getLabel() + '",';
    jsonPart += '"required":"' + (f.getDBRequired() || f.getRequired()) + '",';
    jsonPart += '"type":"' + (f.getType()) + '",';
    jsonPart += '"name":"' + f.getFieldPath() + '"';
    jsonPart += '}';
    result += jsonPart;
    }
    }
    catch(Exception e){
    result += e.getLineNumber() + ' : ' + e.getMessage();
    }
    return '['+result+']';
    }

    @AuraEnabled
    public static String getRecords(String sObjectName, String parentFieldName, String parentRecordId, String fieldNameJson){

    List<sObject> lstResult = new List<sObject>();
    String result = '[]';
    try{
    List<String> fieldNames = (List<String>) JSON.deserialize(fieldNameJson, List<String>.class);
    Set<String> setFieldNames = new Set<String>();
    String query = 'SELECT ' + String.join(fieldNames, ',') + ' FROM ' + sObjectName;
    if(parentFieldName != NULL && parentFieldName != '' && parentRecordId != NULL){
    query += ' WHERE ' + parentFieldName + '= '' + parentRecordId + ''';
    }
    for(sObject s : Database.query(query)){
    lstResult.add(s);
    }
    if(lstResult.size() > 0) {
    result = JSON.serialize(lstResult);
    }
    }
    catch(Exception e){
    result += e.getLineNumber() + ' : ' + e.getMessage();
    }
    return result;
    }
    }

    LightningTableController.js
    ({
    doInit : function(component, event, helper) {
    helper.doInit(component, event, helper);
    }
    })

    LightningTableHelper.js
    ({
    doInit : function(component, event, helper) {
    helper.getTableFieldSet(component, event, helper);
    },

    getTableFieldSet : function(component, event, helper) {
    var action = component.get("c.getFieldSet");
    action.setParams({
    sObjectName: component.get("v.sObjectName"),
    fieldSetName: component.get("v.fieldSetName")
    });

    action.setCallback(this, function(response) {
    var fieldSetObj = JSON.parse(response.getReturnValue());
    component.set("v.fieldSetValues", fieldSetObj);
    //Call helper method to fetch the records
    helper.getTableRows(component, event, helper);
    })
    $A.enqueueAction(action);
    },

    getTableRows : function(component, event, helper){
    var action = component.get("c.getRecords");
    var fieldSetValues = component.get("v.fieldSetValues");
    var setfieldNames = new Set();
    for(var c=0, clang=fieldSetValues.length; c<clang; c++){ if(!setfieldNames.has(fieldSetValues[c].name)) { setfieldNames.add(fieldSetValues[c].name); if(fieldSetValues[c].type == 'REFERENCE') { if(fieldSetValues[c].name.indexOf('__c') == -1) { setfieldNames.add(fieldSetValues[c].name.substring(0, fieldSetValues[c].name.indexOf('Id')) + '.Name'); } else { setfieldNames.add(fieldSetValues[c].name.substring(0, fieldSetValues[c].name.indexOf('__c')) + '__r.Name'); } } } } var arrfieldNames = []; setfieldNames.forEach(v => arrfieldNames.push(v));
    console.log(arrfieldNames);
    action.setParams({
    sObjectName: component.get("v.sObjectName"),
    parentFieldName: component.get("v.parentFieldName"),
    parentRecordId: component.get("v.parentRecordId"),
    fieldNameJson: JSON.stringify(arrfieldNames)
    });
    action.setCallback(this, function(response) {
    var list = JSON.parse(response.getReturnValue());
    console.log(list);
    component.set("v.tableRecords", list);
    })
    $A.enqueueAction(action);
    },

    createTableRows : function(component, event, helper){

    }
    })

    Thanks

  • Satyendra

    Member
    August 10, 2021 at 1:36 pm

    could you please provide the sample code of LightningCell component(<c:LightningCell record="{!row}" field="{!field}"/>)
    Thanks in Advance

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos