Blog Details

Using lightning-record-edit-form in LWC

Using lightning-record-edit-form in LWC

The lightning-record-edit-form component in Lightning Web Components (LWC) allows you to create a form for adding or updating Salesforce records. In this blog, we’ll explore how to use this component effectively, including detailed examples and explanations.

Purpose of lightning-record-edit-form
  • Record Interaction: Create a form that interacts with Salesforce records.
  • Field Display: Display fields with their labels and current values, allowing users to edit those values.
  • Client-side Validations: Implement client-side JavaScript validations for specific use cases.
  • Salesforce Validations: Create Salesforce validations to prevent records from being saved if they don’t meet certain criteria.
Use Cases
  • Edit Existing Records: Edit specified fields of an existing record (given the record ID).
  • Create New Records: Create a new record using specified fields.
Example: Creating a Contact Form

Suppose we want to create a form for adding contact records. We’ll specify the object-api-name attribute as Contact to indicate that we’re working with contact records. Inside the form, we’ll include lightning-input-field components to represent the fields we want to edit or create.

HTML (contactForm.html)

<template>
<lightning-card title="New Contact Form">
<div class="slds-p-around_medium">
<lightning-record-edit-form
object-api-name="Contact"
onsuccess={handleSuccess}
onerror={handleError}>

<lightning-messages></lightning-messages>

<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>

<div class="slds-m-top_medium">
<lightning-button variant="brand" type="submit" label="Save"></lightning-button>
</div>
</lightning-record-edit-form>
</div>
</lightning-card>
</template>

JavaScript (contactForm.js)

import { LightningElement } from 'lwc';

export default class ContactForm extends LightningElement {
handleSuccess(event) {
const newRecordId = event.detail.id;
console.log('New Contact created with Id: ' + newRecordId);
// You can display a success message, clear the form, or navigate to the newly created record
}

handleError(event) {
console.error('Error creating new Contact: ' + event.detail.message);
// Handle the error event when there is an error saving the record
}
}
Detailed Explanation
  1. Template Structure:
    • The HTML template includes a lightning-card component that contains a lightning-record-edit-form.
    • The object-api-name attribute specifies the Salesforce object (in this case, Contact).
    • lightning-messages displays any validation or error messages.
    • lightning-input-field components represent the fields to be edited or created.
    • A lightning-button is used to submit the form.
  2. JavaScript Logic:
    • The handleSuccess method is triggered when the record is successfully saved. It logs the new record ID and can be used to display a success message, clear the form, or navigate to the new record.
    • The handleError method is triggered if there’s an error saving the record. It logs the error message.
Additional Examples
Example 2: Editing an Existing Record

To edit an existing record, set the record-id attribute in the lightning-record-edit-form component.

 

<template>
<lightning-card title="Edit Contact">
<div class="slds-p-around_medium">
<lightning-record-edit-form
object-api-name="Contact"
record-id={recordId}
onsuccess={handleSuccess}
onerror={handleError}>

<lightning-messages></lightning-messages>

<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>

<div class="slds-m-top_medium">
<lightning-button variant="brand" type="submit" label="Save"></lightning-button>
</div>
</lightning-record-edit-form>
</div>
</lightning-card>
</template>

import { LightningElement, api } from 'lwc';

export default class EditContactForm extends LightningElement {
@api recordId; // The ID of the record to be edited

handleSuccess(event) {
console.log('Contact updated successfully');
}

handleError(event) {
console.error('Error updating Contact: ' + event.detail.message);
}
}
Implementing Client-Side Validations

You can implement client-side validations using standard JavaScript. For example, you might want to ensure that the email address is in a valid format before allowing the form to be submitted.

JavaScript (contactForm.js)

import { LightningElement } from 'lwc';

export default class ContactForm extends LightningElement {
handleSuccess(event) {
const newRecordId = event.detail.id;
console.log('New Contact created with Id: ' + newRecordId);
}

handleError(event) {
console.error('Error creating new Contact: ' + event.detail.message);
}

handleSubmit(event) {
event.preventDefault(); // Prevent the default form submission
const fields = event.detail.fields;

// Custom client-side validation
if (!this.isValidEmail(fields.Email)) {
// Display an error message or take appropriate action
console.error('Invalid email address');
return;
}

this.template.querySelector('lightning-record-edit-form').submit(fields);
}

isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
}

HTML (contactForm.html)

<template>
<lightning-card title="New Contact Form">
<div class="slds-p-around_medium">
<lightning-record-edit-form
object-api-name="Contact"
onsuccess={handleSuccess}
onerror={handleError}
onsubmit={handleSubmit}>

<lightning-messages></lightning-messages>

<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>

<div class="slds-m-top_medium">
<lightning-button variant="brand" type="submit" label="Save"></lightning-button>
</div>
</lightning-record-edit-form>
</div>
</lightning-card>
</template>

 

Conclusion

Using lightning-record-edit-form in LWC is a powerful way to create and update Salesforce records with minimal code. By understanding the structure and capabilities of this component, you can build efficient and user-friendly forms for your Salesforce applications. Implementing client-side validations further enhances the user experience by providing immediate feedback and ensuring data integrity.

 

Leave A Comment