Create form with lightning-record-edit-form and accordion component in Salesforce

Hello! Today I am gonna show how to create simple form with lightning-record-edit-form and accordion component available in LWC.

Config

Firstly we have to prepare object for our form. Of course you can use any of standard Salesforce object, but for my example I prepare my own custom object named “Custom User”.

Custom User object

Code for form with lightning-record-edit-form and accordion component

Secondly when you are decided about object and fields you want to use, you can start write code. So let’s create Lightning Web Component named ‘form’. After that copy code below to your component. Let’s start with JavaScript.

form.js

import { LightningElement, track } from "lwc";
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class Form extends LightningElement {
    @track activeSections = [];

    fields_per_section = [
        {
            label: "Personal data",
            fields: [
                "Name",
                "First_Name__c",
                "Last_Name__c",
                "Salutation__c",
                "Date_Of_Birth__c"
            ]
        },
        {
            label: "Address",
            fields: [
                "Street__c",
                "House_Number__c",
                "Postal_Code__c",
                "City__c"
            ]
        },
        {
            label: "Contact Info",
            sublabel: "",
            fields: ["Email_Address__c",
                "Phone_Number__c"]
        }
    ];

    handleCancel(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }

    handleSuccess() {
        const event = new ShowToastEvent({
            variant: 'success',
            title: 'Success!',
            message: 'Record has been created',
        });
        this.dispatchEvent(event);
    }
}
  • 7 line: in this line we define array od objects, each object contain name of your section and API names fields which you want to include in your section.
  • 35 line: here we define function which we use to clear from
  • 46 line: in this line we define function which is used to display success message after record save.

form.html

<template>
    <lightning-record-edit-form object-api-name="Custom_User__c" onsuccess={handleSuccess}>
        <lightning-messages>
        </lightning-messages>
        <lightning-accordion allow-multiple-sections-open class="example-accordion slds-grid slds-gutters"
            active-section-name={activeSections}>

            <template class="slds-col slds-size_1-of-2" for:each={fields_per_section} for:item="accordion_item">
                <lightning-accordion-section key={accordion_item.label} name={accordion_item.label}
                    label={accordion_item.label}>
                    <template for:each={accordion_item.fields} for:item="fieldFromSubsection">
                        <lightning-input-field key={fieldFromSubsection} field-name={fieldFromSubsection}>
                        </lightning-input-field>
                    </template>
                </lightning-accordion-section>
            </template>
        </lightning-accordion>

        <div class="slds-align_absolute-center">
            <lightning-button label="Cancel" title="Cancel" onclick={handleCancel} class="slds-m-left_x-small">
            </lightning-button>
            <lightning-button type="submit" variant="brand" label="Save" title="Save" class="slds-m-left_x-small">
            </lightning-button>
        </div>
    </lightning-record-edit-form>
</template>
  • 2 line: in this line we use <lightning-record-edit-form > component which does most of work for us, we just need to pass object prepared for form and optional onSuccess parameter
  • 5 line: here we use lightning-accordion component which divide our form into sections.
  • 8-17 lines: that’s where we do most of our work, in this lines we iterate over array of our sections and set up label of each section in < lightning-accordion-section > component, then iterate one more time, but over fields inside each section, and display all of them with <lightning-input-field > component
  • 20-23 lines: hre we define buttons to make actions on our form

Thirdly to test form you need to expose it in Salesforce. To do it you need to add some code to your meta file, in my case it looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
        <target>lightning__HomePage</target>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

Test

Finally we can test it. Let’s put you component somewhere in your org, in my case it is community and looks like this:

Form

Now put some custom data here and check if does it work:

Success Message
Salesforce Records

Awesome! Everything works excellent!

Conclusion

In conclusion that’s how you can build form with lightning-record-edit-form and accordion. However remember that you can customize this code in many ways, for example,
you can check this article where we do custom validation for similar component in Aura Components, which after small modifications you can use here.

Resources

5 1 vote
Article Rating
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
jagannath
jagannath
8 months ago

How to show field in two column like left side some field or right side some field ?

Ken
Ken
8 months ago

I was looking for an example of an edit form with a dynamic field list and this example looks like it covers it.

What I’m still trying to figure out is if the same lightning-record-edit-form can be used for both create and edit. I don’t know if that is possible. I haven’t found an example of it.

Close Menu
3
0
Would love your thoughts, please comment.x
()
x