We usually get the requirement to develop a lightning page for creating records in the Salesforce object. We have to create different components for creating a different kind of objects record. Instead of creating multiple components, we can utilize FieldSet to create dynamic pages. This post will explain dynamic record page creation using fieldset.
Fieldset is group of fields and used to add, remove and reorder fields. FieldSets are used to style forms and display those logical associations between fields. FieldSets are used to display fields.
Let us see how we can create the dynamic page using fieldset. Below steps are required to create a dynamic page
- Create an apex class to get fields from the fieldset
- Create a generic lighting component
- Test Component
1. Create an apex class to get fields from the fieldset
Let us create an apex class that will get fields detail based on the given fieldset and object. We will use Schema.DescribeSObjectResult, Schema.getGlobalDescribe and Schema.FieldSet to get field details. These will be used for describing sObject.
After getting object descriptions from the above-mentioned classes, we will prepare a list of field information. This list will be used in LWC component to create the page.
Code for getting field detail for a given object and fieldset
2. Create a generic lighting component
Create a re-usable LWC component that will use the above apex class and lightning-record-edit-form to generate layout. By default, it will display controls in 1 control per row, if you want to show 2 or 3 columns per row then use a lightning design system to generate multiple columns. slds-col slds-size_1-of-2 style will convert rows into 2 columns layout.
We need to get the object name, fieldset, or record id to display the page. So create public properties for these informations.
Public properties which are required are
- Record ID
- Object Name
- FieldSet Name
3. Test Component
To test the component, create a fieldset in 2 different objects. Add the above-created component on the record page or home page in lightning.