Welcome back to the Visualforce to LWC series. In this article I will be discussing how to add records to a Standard or Custom object in Lightning. But first let’s see how we used to do that in Visualforce.
This is an example of creating records in the Lead object using Visualforce:
Accessing Salesforce Data in Lightning
There are several ways to access data in lightning web components:
- Record Form Base Components
- Lightning Data Service
The one I’ll be using today is lightning-record-form which is a part of the Record Form Base components. Let’s look at the same example done with a Lightning Component.
Line 4–5: By using lightning-record-form we can specify the layout needed to insert our record. We use the object-api-name to tell the component which Object do we need to perform the creation on. In this case it’s the Lead object.
record-id attribute is the ID of the record to be displayed.
mode attribute determines the user interaction allowed. There are 3 modes: edit, view and readonly, In this case we are on the edit mode which creates an editable form to add or update records .
onsuccess attribute specifies an action to be done when the Lead is inserted successfully. This action is done in the function called handleSuccess.
Line 2–5: Here we are Importing the fields that we need to be displayed on our component.
Line 8: Declaring a variable called recordId which will hold the ID of the record we will create.
Line 11: We create an array called fieldArr that will hold the fields we need to display and notice that we pass this array to the attribute called fields in the lightning-record-form.
Line 13–15: handleSuccess event handler captures the ID of the record inserted successfully in the variable we declared in Line 8 called recordId.
As you can see it’s pretty simple when it comes to lightning. We didn’t need to use Apex because lightning-record-form takes care of the server side, also notice that we didn’t need to add buttons because lightning-record-form provides Cancel and Save buttons automatically in edit forms. After Clicking Save you have the option to edit the record that you’ve just created by clicking on the pencil icon.
We can further manipulate lightning-record-form by changing the attributes. Let’s say we need to display all the fields in the lead object, instead of importing them one by one you can use this attribute layout-type=”Full” and remove the fieldArr since we don’t need it anymore. Let’s see this in action.
To learn more about lightning-record-form component check the Component Documentation.
Happy Learning :)!