How to Use Field Sets in Lightning?

How to Use Field Sets in Lightning?

On July 21, 2025, Posted by , In LWC Essentials,Salesforce Technical Questions, With Comments Off on How to Use Field Sets in Lightning?
How to Use Field Sets in Lightning

Question:

I have been trying to create a Salesforce Lightning input form based on fields from a field set. Since an Aura-enabled Apex method cannot return an entire field set directly, I attempted to convert it into a JSON string and pass it to the Lightning component. While this approach works, it does not feel like the correct or best practice.

What is the proper way to display fields from a field set in Lightning?

Component:

< aura:component controller="ns.myController" >
  < aura:handler name="init" value="{!this}" action="{!c.getForm}" />
    <div class="fields">        
        <form aura:id="myForm">
        </form>
    </div>    
< /aura:component>

Clientside controller:

getForm : function(component) {
    var action = component.get("c.getFieldSet");  
    var self = this;
    var inputOutput = 'input';
    action.setCallback(this, function(a) {
        var jsonFieldset = JSON.parse(a.getReturnValue());
        for(var x=0,xlang=jsonFieldset.length;x<xlang;x++){
            fieldDef = jsonFieldset[x]; 
            this.createField(component,fieldDef.label,inputOutput+fieldDef.type,fieldDef.name,fieldDef.required);
        }
    });
    $A.enqueueAction(action);
},

createField : function(component,fieldName,fieldType,fieldId,fieldRequired) {
    $A.componentService.newComponentAsync(this,
       function(newField){                                                                        
            myForm = component.find('myForm');
            var body = myForm.get("v.body");  
            body.push(newField);                                
            myForm.set("v.body",body);
        },
        {
            "componentDef": "markup://ui:"+fieldType,
            "localId": "fieldId",
            "attributes": {
                "values": { label: fieldName,
                           displayDatePicker:true,
                           required:fieldRequired
                          }
            }
        }
    );
}

Serverside controller:

static Map<String,String> auraTypes {get; set;}

public static Map<String,String> getAuraTypes() {
    if(auraTypes!=null) {
        return auraTypes;
    }
    else {
        auraTypes = new Map<String,String>();
        auraTypes.put('BOOLEAN','Checkbox');
        auraTypes.put('DATE','Date');
        auraTypes.put('DATETIME','DateTime');
        auraTypes.put('EMAIL','Email');
        auraTypes.put('NUMBER','Number');
        auraTypes.put('PHONE','Phone');
        auraTypes.put('STRING','Text');            
    }
    return auraTypes;
}


@AuraEnabled    
public static String getFieldSet() {
    String result = '';
    List<Schema.FieldSetMember> fieldset =  SObjectType.Kandidaat__c.FieldSets.formulier.getFields();
    for(Schema.FieldSetMember f : fieldset) {
        if(result!=''){
            result += ',';
        }
        String jsonPart = '{';
        jsonPart += '"label":"'+f.getLabel()+'",';
        jsonPart += '"required":"'+(f.getDBRequired() || f.getRequired())+'",';
        jsonPart += '"type":"'+getAuraTypes().get((f.getType()+'')) +'",';
        jsonPart += '"name":"'+f.getFieldPath()+'"';
        jsonPart += '}';
        result +=jsonPart;
    }
    return '['+result+']';
}

Answer:

The best approach to using field sets in Lightning is to retrieve the field set’s metadata in Apex, pass it to the Lightning component in a structured format (such as a wrapper class), and dynamically generate the input fields.

Master Salesforce with expert-led salesforce online training at CRS Info Solutions—join our demo session now!!!

One effective solution involves using a wrapper class in Apex to represent field set members. This allows Lightning components to process the metadata easily.

1. Create a Wrapper Class

A wrapper class is used to structure field set metadata so it can be easily processed in Lightning components. It encapsulates details like field labels, API names, types, and required attributes, making the data more accessible. This approach allows for dynamic form generation without hardcoding field details.

public class FieldSetMember {
    @AuraEnabled public Boolean DBRequired { get; set; }
    @AuraEnabled public String fieldPath { get; set; }
    @AuraEnabled public String label { get; set; }
    @AuraEnabled public Boolean required { get; set; }
    @AuraEnabled public String type { get; set; }

    public FieldSetMember(Schema.FieldSetMember f) {
        this.DBRequired = f.getDBRequired();
        this.fieldPath = f.getFieldPath();
        this.label = f.getLabel();
        this.required = f.getRequired();
        this.type = '' + f.getType();
    }
}

Explanation: The FieldSetMember class is a wrapper for field set metadata, enabling the transfer of field information (e.g., label, required status, type) to Lightning components. It uses the Schema.FieldSetMember class to extract relevant details and exposes them via @AuraEnabled properties for use in the Lightning component.

2. Retrieve Field Set Members in Apex

To retrieve field set members in Apex, use the Schema class to get the field set metadata for a given object. Iterate through the field set members, extract relevant details like field path, label, and type, and store them in a wrapper class. This structured approach ensures the data is easily accessible for use in Lightning components.

public class FieldSetController {
    @AuraEnabled
    public static List<FieldSetMember> getFields(String objectName, String fieldSetName) {
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
        Map<String, Schema.FieldSet> fieldSets = targetType.getDescribe().fieldSets.getMap();
        List<FieldSetMember> fieldSetMembers = new List<FieldSetMember>();

        if (fieldSets.containsKey(fieldSetName)) {
            for (Schema.FieldSetMember f : fieldSets.get(fieldSetName).getFields()) {
                fieldSetMembers.add(new FieldSetMember(f));
            }
        }
        return fieldSetMembers;
    }
}

Explanation: The FieldSetController class retrieves field set metadata for a specified object and field set name using Schema methods. It then iterates through the field set members and returns them as a list of FieldSetMember objects, which are structured for use in a Lightning component.

3. Use the Controller in a Lightning Component

In the Lightning component, an attribute is defined to store the field set members retrieved from Apex. The component iterates over these fields dynamically to generate input elements based on their metadata. A handler triggers the Apex method on initialization to fetch the field set details.

<aura:component controller="FieldSetController">
    <aura:attribute name="fields" type="FieldSetMember[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.getForm}" />

    <div class="form">
        <aura:iteration items="{!v.fields}" var="field">
            <lightning:input label="{!field.label}" name="{!field.fieldPath}" required="{!field.required}" />
        </aura:iteration>
    </div>
</aura:component>

Explanation: The above code defines an Aura component that retrieves and displays fields from a field set using the FieldSetController Apex controller. It iterates over the fields attribute, dynamically rendering a lightning:input for each field with its label, name, and required properties.

4. Fetch Field Set Data in the Lightning Controller

In the Lightning controller, an Apex method is called to fetch field set metadata dynamically. The retrieved data is processed in the callback and assigned to a component attribute for rendering. This ensures that the form fields are generated dynamically based on the field set configuration.

({
    getForm: function(component) {
        var action = component.get("c.getFields");
        action.setParams({ objectName: "Account", fieldSetName: "MyFieldSet" });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.fields", response.getReturnValue());
            }
        });

        $A.enqueueAction(action);
    }
})

Explanation: The code defines a controller function getForm that invokes the Apex method getFields to fetch field set data for the “Account” object and “MyFieldSet”. Upon successful retrieval, it stores the field data in the component’s fields attribute for dynamic rendering.

Summing Up

To properly display fields from a field set in Salesforce Lightning, the best practice is to use an Apex controller that retrieves the field set metadata and passes it to a Lightning component. This can be done by creating a wrapper class in Apex to structure the field set data, which is then dynamically rendered in the component using standard input elements. This approach eliminates the need for complex workarounds like JSON serialization and ensures a clean, scalable solution for handling field sets in Lightning applications.

Accelerate Your Career with Salesforce Training in Mumbai

Are you ready to elevate your career in Mumbai’s thriving Salesforce ecosystem? At CRS Info Solutions, we offer Salesforce online training  that equips you with the skills to stand out. Our comprehensive program, led by experienced industry professionals, covers essential areas like Salesforce Administration, Development, and cutting-edge AI modules. With a focus on hands-on learning and real-time projects, you’ll gain practical expertise to tackle real-world challenges confidently.

Whether you’re embarking on your Salesforce journey or aiming to enhance your skill set, our tailored training programs are designed to meet your unique needs.  Salesforce training in Mumbai From mastering certification requirements to acing job interviews, we provide personalized guidance, in-depth course materials, and expert strategies for success.

Join our free demo session today and take the first step toward a prosperous Salesforce career in Mumbai!!!

Related Posts:

Salesforce Lightning Components Certification Training
A Beginner’s Guide to Lightning Data Service and JavaScript

Comments are closed.