Visualforce to LWC: Creating Records using Apex in LWC
There are 3 ways to create records in Lightning Web Components:
I already talked about the first two in my previous articles. Now I’m going to be sharing with you how to create records in Lightning Web Components using Apex.
I’ll be using the same example of adding a new contact but this time using an Apex @AuraEnabled method.
APEX:
Line 3: The apex method will take 3 strings as an input (FName , LName, Phone) and we mark it as @AuraEnabled to make it accessible in lightning web components.
Line 5–10: Using the variables passed to the apex method to create a new contact.
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 handleCreateCon 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 apex method to be used as a javascript function.
Line 4–7: Declaring the variables we need to store our data.
Line 9–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 19: The handleCreateCon function will fire when we click the button.
Line 20–23: We call the apex method imperatively and pass the variables we created as an input to the apex method. Calling the apex function imperatively will return a javascript promise (then , catch).
Line 24–25: In the then method, we define what happens if the contact is created successfully. So in this case we set the message to ‘Contact Created’.
Lines 26–27: In the catch method, we define what happens if the contact creation fails. In this case we set the message to ‘Error Creating Contact’.
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.
By using apex you have the flexibility to work with multiple records, unlike when using Lightning Data Service functions and Record Form Base Components which allow you to work with single records only.