Building an efficient LWC form with combination of input and input-field using uiRecordApi


In this post we will see, how to create New& Edit form in single lightning web component, which is having both lightning-input and lightning-input-field tags.

In this approach i am using below things to create and edit the account record using LWC

  • Using uiRecordApi to create and update the record
  • Using combination of input and input-field for fast implementation
  • Update the field value with onchange event. we can use data-field on all fields for getting the field values
  • Differentiate the page type whether it is new or edit based on recordId
  • By creating the aura component will override the standard edit and new button

dynamicForm.html


<template>
<lightning-card title="Account Form">
<lightning-record-edit-form record-id={recordId} onload={handleLoad} object-api-name="Account"
onsuccess={handleSucess}>

<lightning-input-field data-field="Name" field-name="Name" onchange={handleFieldChange}>
</lightning-input-field>

<lightning-input-field data-field="Website" field-name="Website" onchange={handleFieldChange}>
</lightning-input-field>

<lightning-input-field data-field="Industry" field-name="Industry" onchange={handleFieldChange}>
</lightning-input-field>

<lightning-input label="AccountNumber" data-field="AccountNumber" value={accountRecord.AccountNumber}
onchange={handleFieldChange}>
</lightning-input>

<lightning-input label="NumberOfEmployees" data-field="NumberOfEmployees"
value={accountRecord.NumberOfEmployees} onchange={handleFieldChange}>
</lightning-input>

<lightning-input label="Site" data-field="Site" value={accountRecord.Site} onchange={handleFieldChange}>
</lightning-input>

<lightning-textarea label="Description" data-field="Description" value={accountRecord.Description}
onchange={handleFieldChange} ></lightning-textarea>

<lightning-button class="slds-m-top_small" variant="brand" name="save" label="Save" onclick={handleSubmit}>
</lightning-button>

</lightning-record-edit-form>
</lightning-card>

</template>


dynamicForm.js

import { LightningElement, api, track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { updateRecord } from 'lightning/uiRecordApi';
import { createRecord } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class DynamicForm extends NavigationMixin(LightningElement) {
@track accountRecord = {};
@api recordId;

//handle load method
handleLoad(event) {
//To get the value of form fields on edit form
if (this.recordId !== undefined) {
let fields = Object.values(event.detail.records)[0].fields;
const recordId = Object.keys(event.detail.records)[0];
this.accountRecord = {
Id: recordId,
...Object.keys(fields)
.filter((field) => !!this.template.querySelector(`[data-field=${field}]`))
.reduce((total, field) => {
total[field] = fields[field].value;
return total;
}, {})
};
}
}

//To add the input field value to list
handleFieldChange(e) {
this.accountRecord[e.currentTarget.dataset.field] = e.target.value;
}

//save method
handleSubmit() {
//To create reccord
if (this.recordId === undefined) {
let recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields: this.accountRecord }
createRecord(recordInput)
.then(result => {
this.accRecord = {};
this.recordId = result.id;

// Show success messsage
this.dispatchEvent(new ShowToastEvent({
title: 'Success!!',
message: 'Account Created Successfully!!',
variant: 'success'
}));
this.handleSucess();
})
.catch(error => {
this.error = JSON.stringify(error);
});
}

//To update the record
if (this.recordId !== undefined) {
updateRecord({ fields: this.accountRecord })
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account updated',
variant: 'success'
})
);
this.handleSucess();
})
.catch((error) => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body.message,
variant: 'error'
})
);
});
}
}

//Handle sucess method
handleSucess() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
});
}

}


dynamicForm.xml

<?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>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>


accountButtonOverride.cmp

<aura:component implements="lightning:actionOverride,force:appHostable,flexipage:availableForAllPageTypes,
force:hasRecordId" access="global" >
<c:dynamicForm recordId="{!v.recordId}"></c:dynamicForm>
</aura:component>   



GitHub : 


Demo :



No comments:

Post a Comment