In order to create the form, we should know below three adapters. The output of one adapter will be the input for another.
getRecordCreateDefaults
generateRecordInputForCreate
createRecord
getRecordCreateDefaults
This wire adapter is used to get default information and data which is needed to create a record.
To create a UI that lets a user create a record, first get information about which fields are required. This adapter’s response contains the default field values for a new record of the object type specified in {apiName}. It also contains object metadata and the corresponding layout for Create mode. In the Salesforce user interface, an admin with “Customize Application” permission can mark a field as required in a layout. When you’re building a UI, to determine which fields to mark as required in a layout for create and update, use the ObjectInfo.fields[fieldName].required property.
Syntax
import { getRecordCreateDefaults } from 'lightning/uiRecordApi';
@wire(getRecordCreateDefaults, { objectApiName: string })
propertyOrFunction;
This returns data and error.
generateRecordInputForCreate
Generates a representation of a record (Record Input) that can be used to create a record using createRecord(RecordInput).
Syntax
import { generateRecordInputForCreate } from 'lightning/uiRecordApi';
generateRecordInputForCreate(record,ObjectInfo): RecordInput
It has two parameters:
record—(Required) A Record object that contains source data. To get data to build the Record object, use the getRecordCreateDefaults or getRecord.
objectInfo—(Optional) The ObjectInfo corresponding to the apiName on the record. If provided, only fields that are createable=true (excluding Id) are included in the response.
It returns a Record Input object with its data populated from the given record. Returns all fields whose values are not nested records.
createRecord(recordInput)
Creates a record.
Syntax
import { createRecord } from 'lightning/uiRecordApi';
createRecord(recordInput): Promise<Record>
Return type- A Promise object that resolves with the created record. The record contains data for the fields in the record layout.
You can now, go to go with an example, lets create an LWC component and copy-paste the below example:
LWC_createAccount.html
<template>
<lightning-card title="Account Information" icon-name="standard:record">
<div class="slds-var-m-around_medium">
<template if:true={recordInput}>
<lightning-input label="Name"
onchange={handleFieldChange}
data-field-name={nameField}></lightning-input>
<lightning-input type="number"
label="Account Number"
onchange={handleFieldChange}
data-field-name={accountNumberField}></lightning-input>
<lightning-input type="tel"
label="Phone"
onchange={handleFieldChange}
data-field-name={phoneField}></lightning-input>
<div class="slds-var-m-top_x-small">
<lightning-button label="Create Account"
variant="brand"
onclick={createAccount}
></lightning-button>
</div>
</template>
<template if:true={error}>
<c-error-panel errors={error}></c-error-panel>
</template>
</div>
</lightning-card>
</template>
LWC_createAccount.js
import { LightningElement, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import {
createRecord,
getRecordCreateDefaults,
generateRecordInputForCreate
} from 'lightning/uiRecordApi';
import { reduceErrors } from 'c/ldsUtils';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ACCOUNT_PHONE from '@salesforce/schema/Account.Phone';
import ACCOUNT_NUMBER from '@salesforce/schema/Account.AccountNumber';
export default class LdsGenerateRecordInputForCreate extends LightningElement {
//Bind UI fields
phoneField=ACCOUNT_PHONE.fieldApiName;
nameField = NAME_FIELD.fieldApiName;
accountNumberField=ACCOUNT_NUMBER.fieldApiName;
error;
recordInput;
//Step1: Get accountCreateddefaults using getRecordCreateDefaults adptor
@wire(getRecordCreateDefaults, { objectApiName: ACCOUNT_OBJECT })
accountCreateddefaults({ data, error }) {
//If accountCreateddefaults return success
if (data) {
//Step2: call generateRecordInputForCreate to create the input
//for creation and keep in recordInput
//generateRecordInputForCreate has two parameters
//1. record=data.record
const record=data.record;
//2. AccountObjectInfo to filter only createable field in response
const AccountObjectInfo=data.objectInfos[ACCOUNT_OBJECT.objectApiName];
// Creates a record input with default field values
this.recordInput = generateRecordInputForCreate(record,AccountObjectInfo);
//set error undefined in case of success
this.error = undefined;
} else if (error) {// if return failed
//set recordInput undefined in case of failure
this.recordInput = undefined;
this.error = error;
}
}
//Function called to capture the input field
handleFieldChange(event) {
this.recordInput.fields[event.target.dataset.fieldName] =
event.target.value;
}
//Function is called from Create Account button from LWC template
createAccount() {
//call createRecord to create account and pass recordInput
createRecord(this.recordInput)
.then((account) => {
//Create showtoastevent to display success msg
const stEvent = new ShowToastEvent({
title: 'Success',
message: 'Account created, with id: ' + account.id,
variant: 'success'
});
//fire the event
this.dispatchEvent(stEvent);
})
.catch((error) => {
console.log('This is error :'+error.body.message);
//Create showtoastevent to display error msg
const errorEvent = new ShowToastEvent({
title: 'Error creating record',
message: reduceErrors(error).join(', '),
variant: 'error'
})
//fire the event
this.dispatchEvent(errorEvent);
});
}
}
lWC_ldsForm.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>49.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Deploy the component and add to the lightning App builder.
No comments:
Post a Comment