Visualforce to LWC: Creating Records using Lightning Data Service
In my previous article I showed you how we used to create records in Visualforce and how can do it in Lightning Web Components using the lightning-record-form. We also agreed that there are 3 ways to access data in lightning:
- Record Form Base Components
- Lightning Data Service
- Apex
It’s important to note that Record Form Base Components is also a part of the Lightning Data Service. Lightning Data Service or LDS is the preferred and easiest way to work with salesforce data. LDS is built on top of the User Interface API, it provides security and maintains consistent, up-to-date data and metadata across multiple components.
Today I will be using LDS to create records in Lightning Web Components. We will create a component to insert a contact using the LDS function createRecord.
HTML:
Line 6–8: We use the lightning-input component to capture the data that should be inserted in the 3 fields (FirstName, LastName, Phone).
Line 12–13: Our lightning-button when clicked will trigger the createCon event handler.
Line 18: We’re using a variable called message to display a custom message if the contact is saved successfully or if an error occurs during the saving operation.
JS:
Line 2: We import the createRecord LDS function.
Line 10–11: This change handler is triggered whenever a change occurs in the lightning-input and what it does is basically capture the text entered in the lightning-input and stores it in a variable called firstName which we defined in line 5. The same happens for lastnameCH and phoneCH.
Line 20: createCon event handler will fire when we click the button.
Line 24: We invoke the LDS function that we imported in line 2, and we pass to it the apiName of the object and the fields array. When we invoke an LDS function imperatively, it returns a javascript promise (then , catch).
Lines 24–26: In the then method, we define what happens if the contact is created successfully.
Lines 26–27: In the catch method, we define what happens if the contact creation fails.
You can try this component in your own org! An example that would trigger the catch method is if you leave the last name field empty, because this field is required on the Contact object.
Please note that LDS functions allow you to work with single records only.