
LWC (Lightning Web Components) is a modern framework for building web components on the Salesforce platform. LWC allows developers to create reusable and performant UI components using HTML, CSS, and JavaScript.
One of the common use cases for LWC is to create forms to display and edit records from Salesforce objects. LWC provides various components to create forms, such as lightning-record-edit-form, lightning-record-view-form, lightning-input-field, lightning-output-field, etc.
However, sometimes we may encounter a situation where we have a form with many fields, some of which are required. If the user tries to save the record without filling in the required fields, the form will show an error message and prevent the submission. However, the user may not see the error message or the required fields if they are not in the visible area of the screen. The user may have to manually scroll up or down to find the missing fields and fill them in.
This can be a frustrating and confusing experience for the user, especially if they don’t know which fields are required or why the save is not working. It can also affect the user’s productivity and satisfaction.
To improve the user experience and usability of the form, we can implement a feature that will automatically scroll to the first required field that is empty when the user tries to save the record. This way, the user can easily see which field they need to fill in and complete the form faster and easier.
In this blog post, I will show you how to implement this feature in LWC using a simple example. I will use a form that displays and edits contact fields, such as name, email, phone, mailing address, etc. All of these fields are required. I will use SLDS (Salesforce Lightning Design System) to style the form and make it look consistent with Salesforce UI.
The Example Code
Here is the example code for the LWC component that implements the auto scroll feature:
<template> | |
<!-- Create a form to display the contact fields --> | |
<lightning-record-edit-form object-api-name="Contact" onsubmit={handleSubmit} onerror={handleError}> | |
<div class="slds-scrollable_y" style="height: 200px; overflow:scroll;"> | |
<!-- Use lightning-input-field components with required attribute to display the contact fields --> | |
<lightning-input-field field-name="Name" required></lightning-input-field> | |
<lightning-input-field field-name="Email" required></lightning-input-field> | |
<lightning-input-field field-name="Phone" required></lightning-input-field> | |
<lightning-input-field field-name="MailingStreet" required></lightning-input-field> | |
<lightning-input-field field-name="MailingCity" required></lightning-input-field> | |
<lightning-input-field field-name="MailingState" required></lightning-input-field> | |
<lightning-input-field field-name="MailingPostalCode" required></lightning-input-field> | |
<lightning-input-field field-name="MailingCountry" required></lightning-input-field> | |
</div> | |
<!-- Create a button to save the record --> | |
<div class="slds-m-top_medium"> | |
<lightning-button variant="brand" type="submit" name="save" label="Save"></lightning-button> | |
</div> | |
</lightning-record-edit-form> | |
</template> | |
import { LightningElement ,track} from 'lwc'; | |
export default class ContactForm extends LightningElement { | |
// Define a function to handle the form submission | |
handleSubmit(event) { | |
// Prevent the default behavior of the form | |
event.preventDefault(); | |
// Get the fields from the event detail | |
const fields = event.detail.fields; | |
// Get the form element from the template | |
const form = this.template.querySelector("lightning-record-edit-form"); | |
// Loop through the fields and check if any of them is empty | |
for (const [key, value] of Object.entries(fields)) { | |
if (!value) { | |
// Get the input element for the empty field | |
const input = this.template.querySelector( | |
`lightning-input-field[field-name=${key}]` | |
); | |
// Scroll to the input element and focus on it | |
input.scrollIntoView(); | |
input.focus(); | |
// Return from the function | |
return; | |
} | |
} | |
// Submit the form | |
form.submit(fields); | |
} | |
// Define a function to handle the form error | |
handleError(event) { | |
// Get the error message from the event detail | |
const message = event.detail.message; | |
// Show an alert with the error message | |
} | |
} |
How the Code Works
Let’s break down the code and see how it works.
The HTML Template
The HTML template contains a lightning-record-edit-form component, which is a wrapper component that provides an easy way to create forms for editing records. It handles the loading and saving of the record data, as well as the layout and validation of the fields.
The lightning-record-edit-form component has two attributes: object-api-name and onsubmit. The object-api-name attribute specifies the API name of the Salesforce object that we want to edit, which is Contact in this case. The onsubmit attribute specifies a handler function that will be invoked when the user submits the form, which is handleSubmit in this case.
Inside the lightning-record-edit-form component, we have a div element with a class of slds-scrollable_y and a style of height: 300px. This div element acts as a container for the form fields and makes them scrollable vertically. The height value can be adjusted according to your preference.
Inside the div element, we have several lightning-input-field components, which are used to display and edit the fields of the record. Each lightning-input-field component has two attributes: field-name and required. The field-name attribute specifies the API name of the field that we want to display and edit, such as Name, Email, Phone, etc. The required attribute specifies that the field is required and must have a value before submitting the form.
Below the div element, we have another div element with a class of slds-m-top_medium, which adds some margin to the top of the element. Inside this div element, we have a lightning-button component, which is used to create a button for saving the record. The lightning-button component has three attributes: variant, type, and label. The variant attribute specifies the style of the button, which is brand in this case. The type attribute specifies the type of the button, which is submit in this case. The label attribute specifies the text of the button, which is Save in this case.
The JavaScript Module
The JavaScript module contains a LightningElement class that extends from the base LightningElement class provided by LWC. The LightningElement class provides various methods and properties to interact with the template and handle events.
The LightningElement class has two methods: handleSubmit and handleError. These methods are used to handle the form submission and error events respectively.
The handleSubmit method takes an event parameter, which represents the form submission event. This method does three things:
- It prevents the default behavior of the form submission by calling event.preventDefault(). This prevents the page from reloading or navigating to another URL when submitting the form.
- It gets the fields from the event detail by accessing event.detail.fields. This returns an object that contains the field names and values that were entered by the user.
- It gets the form element from the template by using this.template.querySelector(“lightning-record-edit-form“). This returns a reference to the lightning-record-edit-form component in the template.
- It loops through the fields and checks if any of them is empty by using Object.entries(fields) and if (!value). This returns an array of key-value pairs for each field and checks if the value is falsy (such as null, undefined, empty string, etc.).
- If any field is empty, it gets the input element for that field by using this.template.querySelector(
lightning-input-field[field-name=${key}]
). This returns a reference to the lightning-input-field component in the template that matches the field name. - It scrolls to the input element and focuses on it by using input.scrollIntoView() and input.focus(). This scrolls the container element to make sure that
- the input element is visible and puts the cursor on the input element.
- It returns from the function by using return. This stops the execution of the function and prevents the form from being submitted.
- If all fields have values, it submits the form by using form.submit(fields). This passes the fields object to the lightning-record-edit-form component, which handles the saving of the record data.
- The handleError method takes an event parameter, which represents the form error event. This method does two things:
Conclusion
- In this blog post, I have shown you how to implement a feature that will automatically scroll to required fields in LWC forms. This feature can improve the user experience and usability of your forms, especially if they have many fields or limited space. You can use this feature for any Salesforce object or custom object that you want to create or edit using LWC forms.
- I hope you have found this blog post useful and interesting. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading! 😊
About the blog
SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:
Newsletter
Subscribe to our email newsletter to be notified when a new post is published.