Here's an example of a record form with field validation using code in Lightning Web Components (LWC) in Salesforce:
recordFormExample:
<template>
<lightning-card title="New Record Form" icon-name="standard:account">
<div class="slds-p-around_medium">
<lightning-record-edit-form object-api-name="Account" onsubmit={handleSubmit}>
<lightning-messages></lightning-messages>
<div class="slds-grid slds-wrap">
<div class="slds-col slds-size_1-of-2">
<lightning-input-field field-name="Name" required></lightning-input-field>
</div>
<div class="slds-col slds-size_1-of-2">
<lightning-input-field field-name="Industry" required></lightning-input-field>
</div>
<!-- Add more fields as needed -->
</div>
<div class="slds-m-top_medium">
<lightning-button type="submit" label="Save" variant="brand"></lightning-button>
</div>
</lightning-record-edit-form>
</div>
</lightning-card>
</template>
recordFormExample:
import { LightningElement } from 'lwc';
export default class RecordFormExample extends LightningElement {
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
// Perform additional custom field validation
if (!fields.Name || !fields.Industry) {
this.showError('Please fill in all required fields.');
return;
}
// Save the record
this.template.querySelector('lightning-record-edit-form').submit(fields);
}
showError(message) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: message,
variant: 'error',
})
);
}
}
recordFormExample:
.slds-p-around_medium {
padding: 1rem;
}
.slds-m-top_medium {
margin-top: 1rem;
}
This code demonstrates a basic implementation of a record form for creating a new Account record in Salesforce using LWC. The lightning-record-edit-form component is used to handle the record creation process. The lightning-input-field components are used to render the input fields for the Account Name and Industry.
In the handleSubmit method, additional custom field validation can be performed before submitting the form. In this example, it checks if the required fields (Name and Industry) have been filled in. If any required fields are missing, an error message is displayed using the ShowToastEvent and the form submission is prevented.
Please note that this is a simplified example, and you may need to modify it based on your specific requirements and field validations.
Make sure to include this component in your Lightning App or a parent component to see it in action.
I hope this helps you create a record form with field validation in LWC Salesforce!