Create a Basic Lightning Form
We will be creating a basic aura component, which takes some fields as input and creates an Account record with them.
The Apex Controller
In order to build this component, first we need to define an apex class which acts as an apex controller for our aura component. Here is the code for our apex class :
public class AccountSaveController { @AuraEnabled public static Id createAccount (Account acc) { insert acc; return acc.Id; } }
We defined a method called “createAccount” which accepts an Account as a parameter (by the “acc” parameter of the type Account), and then inserts this Account into the database with an insert operation. Once the Account is inserted, we are returning back the ID of the Account to the aura component.
The Aura Component Markup
Once we are done with the apex class, then we need to build a aura component and bind it to our apex class. Below is the code for our aura component :
<aura:component controller="AccountSaveController"> <aura:attribute name="acc" type="Account" default="{'sobjectType' : 'Account'}"/>
<div> <div> <lightning:input label="Account Name" value="{!v.acc.Name}"/> </div> <div> <lightning:input label="Account Description" value="{!v.acc.Description}"/> </div> <div> <lightning:input label="Account Year Started" value="{!v.acc.YearStarted}"/> </div> <center> <lightning:button label="Save" onclick="{!c.save}"/> </center> </div>
</aura:component>
We define an ‘Account’ Sobject type attribute called “acc” to store the information for the Account record. We can reference as many fields as we want from this attribute, but for now we are only inputting the Name,Description and Year Started standard fields.
Output:
The Javascript Controller
Then lastly in order to send data to our apex class from our aura component, we need to call the apex method from our javascript controller. Below is the code for the javascript controller:
({ save : function(cmp, event, helper) { var action = cmp.get("c.createAccount"); action.setParams({acc : cmp.get("v.acc")}); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { alert("From server: " + response.getReturnValue()); } else if (state === "ERROR") { var errors = response.getError(); alert(JSON.stringify(errors)); } }); $A.enqueueAction(action); } })
Let go through this code part by part.
1. We let the framework know what apex method to call by doing a “cmp.get(“c.<apex-method-name”>)”, which in this case is “createAccount”.
var action = cmp.get("c.createAccount");
2. Then we are passing the account attribute in the component markup to the apex class by using “action.setParams()”. NOTE : While passing arguments from your javascript to the apex class, make sure the parameter names are the same. That is, in the above example the parameter name in the apex class is ”acc”, we need to make sure that’s what we pass from the javascript as well and it’s case-sensitive too.
action.setParams({acc : cmp.get("v.acc")});
3. Then lastly, we define a callback for our apex call. The “response.getState()” value is used to determine if we got an error while inserting the Account record or not. What happens is that we get an exception in our apex class then we get the state value as “ERROR”, and if there is no exception then we get the state value as “SUCCESS”.
var state = response.getState(); if (state === "SUCCESS") { alert("From server: " + response.getReturnValue()); } else if (state === "ERROR") { var errors = response.getError(); alert(JSON.stringify(errors)); }
4. Then all we need to do now is put this component in an app and preview it, so create an app for this aura component :
<aura:application extends="force:slds"> <c:AccountSaveForm/> </aura:application>
And then you should be able to preview the component and check it out in action!
Exception Handling in Server Side (AuraHandledException)
The AuraHandledException is a standard apex exception which can be used to return a custom error message from your apex class to your aura component.
To implement this, let’s make some little changes in our last example :
public class AccountSaveController { @AuraEnabled public static Id createAccount (Account acc) { try { insert acc; } catch(exception e) { throw new AuraHandledException(e.getMessage()); } return acc.Id; } }
As you can see, we are now throwing an AuraHandledException if we get any exception while inserting the Account record into the database.
This makes sure that the error message returned to the user is in readable form, and we do not see unexpected errors.
Show toast message in aura component
Now, let’s make some changes in the javascript controller to show the error message as a toast message if we get any errors. And a success message if .everything is successful and the account record is created.
({ save : function(cmp, event, helper) { var action = cmp.get("c.createAccount"); action.setParams({acc : cmp.get("v.acc")}); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var toastEvent = $A.get("e.force:showToast"); toastEvent.setParams({ title: ‘Success’, type: ‘success’, message: ‘Id : ‘+response.getReturnValue() }); toastEvent.fire(); } else if (state === "ERROR") { var error = response.getError()[0].message; var toastEvent = $A.get("e.force:showToast"); toastEvent.setParams({ title: 'Error', type: 'error', message: errorMsg }); toastEvent.fire(); } }); $A.enqueueAction(action); } })
In order to show a toast message in an aura component, we can use the standard “e.force:showToast” application event. We just need to fire this event with the appropriate parameters and a toast message should be displayed in your aura component.
For the success messages, put the toast type as ‘success’ and for errors set it as ‘error’.
NOTE :
Since the toast is a standard application event, it does not work in a lightning application or if your aura component is hosted on a visualforce page. The standard toast will only work when the aura component is used on a lightning page in the lightning experience
Output on Success :
Output on Error :