Dynamic Lightning Record Edit Form using Field Set

In this tutorial, we will create a lightning component and in this component can control the fields to be shown using Record Edit Form and Field Set.

Step 1: Create a Field Set

Field Set Creation
Here we have created a FieldSet “Account_Field_Set”, we will use this field set to show fields in lightning component.

Step 2: Create an Apex Class

public class AccountFormController {
    
    /**
    * @description This Method will fetch the fields related to Account Fieldset
    * @author Abhimanyu Tanwar | 8/8/2019
    * @return List<FieldWrapper>
    */
    @AuraEnabled 
    public static List<FieldWrapper> retrieveAccountFields() {
        return getFieldSet('Account_Field_Set','Account');
    }
    
    /**
    * @description This Method will fetch the fields related to selected Fieldset
    * @author Abhimanyu Tanwar | 8/8/2019
    * @param String fieldSetName
    * @param String ObjectName
    * @return List<FieldWrapper>
    */
    private static List<FieldWrapper> getFieldSet(String fieldSetName, String ObjectName) {
        List<FieldWrapper> lstfieldWrapper = new List<FieldWrapper>();
        if (String.isNotBlank(fieldSetName) && String.isNotBlank(ObjectName)) {
            Schema.DescribeSObjectResult describeSObjectResult = Schema.getGlobalDescribe().get(ObjectName).getDescribe();
            Map<String,Schema.SObjectField> objFieldMap = describeSObjectResult.fields.getMap();
            Schema.FieldSet fieldSetObj = describeSObjectResult.FieldSets.getMap().get(fieldSetName);
            if (fieldSetObj != null) {
                for(Schema.FieldSetMember fieldSet : fieldSetObj.getFields() ) {
                    lstfieldWrapper.add( new FieldWrapper(
                        String.ValueOf(fieldSet.getLabel()),
                        String.ValueOf(fieldSet.getFieldPath()), 
                        (fieldSet.getDBRequired() || fieldSet.getRequired()),
                        objFieldMap.get(String.ValueOf(fieldSet.getFieldPath())).getDescribe().getInlineHelpText(),
                        objFieldMap.get(String.ValueOf(fieldSet.getFieldPath())).getDescribe().isHtmlFormatted() &&
                        objFieldMap.get(String.ValueOf(fieldSet.getFieldPath())).getDescribe().isCalculated()
                    ));
                }
            }
        }
        return lstfieldWrapper; 
    }
    
    public class FieldWrapper {
        @AuraEnabled public String fieldName {get;set;}
        @AuraEnabled public String fieldLabel {get;set;}
        @AuraEnabled public Boolean isRequired {get;set;}
        @AuraEnabled public String helpText {get;set;}
        @AuraEnabled public Boolean isHtmlFormatted {get;set;}
        
        public FieldWrapper(String fieldLabel,String fieldName,Boolean isRequired, String helpText, Boolean isHtmlFormatted ) {
            this.fieldLabel  = fieldLabel;
            this.fieldName   = fieldName;
            this.isRequired  = isRequired;
            this.helpText    = helpText;
            this.isHtmlFormatted = isHtmlFormatted;
        }
    }
}

Here we have a reusable method which “getFieldSet“, which will give a list of wrapper “FieldWrapper” on the basis of 2 parameters fieldsetName and ObjectName. fieldsetName will be the API Name of the FieldSet, from which you want to show the fields. ObjectName, which is the API Name of Salesforce Object on which this FieldSet is created.

And in the method “retrieveAccountFields” we are calling the above-mentioned method with the FieldSet name “Account_Field_Set” and the Object “Account“. You can use the same method and change the Object name and FieldSet name as per your requirements.

Step 3: Create a Lightning Component “AccountForm”

<aura:component controller="AccountFormController" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    
    <aura:attribute name="accountFieldSet" type="List" access="private"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <lightning:recordEditForm aura:id="recordEditForm"
                              recordId="{!v.recordId}"
                              objectApiName="Account"
                              density="comfy">
        <lightning:messages />
        <lightning:card>
            <lightning:layout multipleRows="true">
                <aura:iteration items="{!v.accountFieldSet}" var="field" >
                    <lightning:layoutItem size="12" smallDeviceSize="12" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-small">
                        <lightning:inputField aura:id="field" class="{!field.fieldName}" required="{!field.isRequired}" fieldName="{!field.fieldName}"/>
                    </lightning:layoutItem>
                </aura:iteration>
            </lightning:layout>
            <div class="slds-m-top_medium slds-align_absolute-center">
                <lightning:button variant="brand" type="submit" name="save" label="Save" />
            </div>
        </lightning:card>
    </lightning:recordEditForm>
</aura:component>

Here we will be storing the Field Set response in accountFieldSet attribute and iterate over it within lightning:recordEditForm created on Account Object. Therefore the features like required mark and help text will be automatically handled by lightning:recordEditForm.

Step 4: Create the Controller.js for Lightning Component

({
    doInit : function(component, event, helper) {
        var action = component.get("c.retrieveAccountFields");
        action.setCallback(this, function( response ) {
            var state = response.getState();
            if ( state === "SUCCESS") {
                var fieldsList = response.getReturnValue();
                component.set( "v.accountFieldSet",fieldsList);
            }
            else {
                console.log(response.getError());
            }
        });
        $A.enqueueAction(action);
    }
})

Step 5: Add the component to UI.

Field Set Form
We are all set, now you can add, remove the fields to FieldSet and the component will dynamically update with respect to the changes made in FieldSet.

Link to Git Repo

Was this post useful? If yes then please share.



Leave a Comment

All fields marked with an asterisk (*) are required


shares