Create A Record In Salesforce Lightning Component With Error Handling

Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid


In the previous EPISODE, we discussed how we can use application events in salesforce lightning component.
In this EPISODE we are going to discuss easy but most requested topic i.e. how to perform DML operations in salesforce lightning component.

Before starting...let me give you some idea about DML operations in salesforce lightning component.

DML operations in salesforce ?

Consider an example of a standard salesforce object model present in your org, where we create records, update records and delete records as well. In the same way, sometimes we need to perform these operations with custom lightning components as well. Hence, in that case, we will perform these operations from our custom lightning component itself. Excited Kid ?? 

So let's get started.....

What's today's recipe  (Component Blueprint ) ?

Today we are going to create a lightning custom record form with Account object fields like Name (text), Type (picklist), Annual Revenue (Currency) fields and two buttons in the bottom Save and Cancel.

Blueprint of today's recipe is here :
Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid

So today will create a lightning component as a quick action on account record itself (you can use as per your need). Then from that quick action, we are going to create new account records with these three fields (you can add as per your need)

Cool right along with with your favourite Success !! toast message. 


Steps to follow :

STEP 1 :
Create a lightning component createRecord.cmp

<aura:component controller="createRecordController" implements="force:lightningQuickActionWithoutHeader">
 <!-- attributes to capture account fields -->
  <aura:attribute name="name" type="String"/>
  <aura:attribute name="type" type="String"/>
  <aura:attribute name="annualRevenue" type="Currency"/>
 <!-- Picklist options attribute -->
  <aura:attribute name="options" 
                {'label': 'Prospect', 'value': 'Prospect'},
                {'label': 'Customer - Direct', 'value': 'Customer - Direct'},
                {'label': 'Customer - Channel', 'value': 'Customer - Channel'},
                {'label': 'Channel Partner / Reseller', 'value': 'Channel Partner / Reseller'},
                {'label': 'Installation Partner', 'value': 'Installation Partner'},
                {'label': 'Technology Partner', 'value': 'Technology Partner'},
                {'label': 'Other', 'value': 'Other'}                               ]" 
  description="Below attribute will define picklist values if you want dynamic values then you can query that from the database and set those values"/>
      <h1 class="inlineTitle slds-p-top--large slds-p-horizontal--medium slds-p-bottom--medium slds-text-heading--medium" 
            Custom Create Account
            <hr size="3" noshade=""></hr>
   <h2 class="slds-section__title slds-theme--shade primaryPaletteBorder test-id__section-header-container"
        New Account Information
    <div class="slds-p-around_medium">
        <lightning:input name="Name" 
        <lightning:combobox name="Status" 
                            placeholder="Select Progress" 
        <lightning:input type="number" 
                         name="Annual Revenue"
                         label="Annual Revenue" 
                         fieldLevelHelp="Please enter in numbers"/>
        <lightning:button variant="Brand" 
        <lightning:button variant="Neutral" 

- As you can see in the above code controller="createRecordController" is our apex or server-side controller which will help us to insert the data in the database.

- Next, is implements="force:lightningQuickActionWithoutHeader" it is used to tell the quick action that whenever I will use this lightning component in the quick action then I don't want salesforce standard quick action header and footer. As we are designing our own 😊.

- Then we have defined the aura:attribute to capture the three fields of Account object.

- Then we defined the picklist and its values/option so that we can use that in our picklist, as mentioned in the description you can use dynamic picklist values by fetching it from the database.

- Then we defined header, then fields and at the bottom, we have defined the Save and Cancel button as well.

STEP 2 :
As you can see we have some methods also in this .cmp or markup file like on lightning:combobox we have onchange="{!c.handleChange}", on lightning:button we have onclick="{!}" and onclick="{!c.cancel}" actions.

These actions will be defined in .js controller file right ?? so let's create those at createRecordController.js file :

  handleChange: function (component, event) {
  // This will contain the string of the "value" attribute of the selected option
        var selectedOptionValue = event.getParam("value");
        component.set("v.type", selectedOptionValue);
  save : function (component, event, helper){
        //get all the inputs from form
        var name = component.get("");
        var type = component.get("v.type");
        var annualRevenue = component.get("v.annualRevenue");
        //Error handling: if any field is undefined
        if(name == undefined || type == undefined || annualRevenue == undefined)
         helper.showToast('Ooops !', 'Please fill up all the information', 'error');
    //if everything is okey then make server call   
      var action = component.get("c.saveAccount"); 
           name : name
           accountType : type,
           revenue : annualRevenue
     var state = response.getState();
 //if callback is Success then show toast message and close the modal popup
         if(state === "SUCCESS")
//pass parameters to helper showToast method  
  helper.showToast('Success !', 'Record Inserted Successfully', 'success');
    cancel : function(component, helper, event)
        //Below line of code will close the modal popup

- In the above code, every method is self-explanatory please read the comments above each method you will definitely understand what exactly every method is doing

- The major part which needs to be highlighted is the error handling we know a user can leave any fields blank here as on account only standard Name field is mandatory, but as its a custom lightning component we want Name as well as other fields also to be filled up by the user.

- Hence if the values are the undefined system will show a Red Toast message to the user. As well as Success Toast when the record is inserted successfully in the database.

- So the question here is, do we need to write two different toast message here? The answer is NO. Because as you can see, we have created helper method called a showToast method here. Where we are passing the parameters as an input, hence it's a completely dynamic method. 

STEP 3 :
Now let's see how we have created this helper method in createRecordHelper.js file :

   //dynamic toast message alert function
   //It will take dynamic input parameters from controller methods
   //We used this for displaying error and success 
    showToast : function(title, message, error) {
        let toastParams = {
            title: title,
            message: message// Error message
            type: error
        let toastEvent = $A.get("e.force:showToast");

As you can see dynamically we are passing the values to this helper method and just mapping that with toastParams as title, message, type.

- Also in our .js controller, We are passing the parameters to apex controller nameaccountTyperevenue and then sending it to the server-side controller. If you don't know how to make server calls please visit out Previous EPISODES.

Let's see how server-side controller/ Apex class handling these inputs and inserting the records in createRecordController controller.

- Create a new apex class called as createRecordController as below :


public class createRecordController {



 public static Account saveAccount(String name, String accountType, Decimal revenue)

        Account acc = new Account();
        acc.Name = name;
        acc.Type = accountType;
        acc.AnnualRevenue = revenue;
        insert acc;
        return acc;

- As you can observe here in apex controller we are accepting three as an input parameter. Then we have created a new account instance as we need to create a new record in the database.
Then we mapped all those three parameters and finally inserted the record with insert acc. 

And There you go...

STEP 4 :
- Now once the lightning component and apex controller was created then we need to add this lightning component on Account Object as a quick action.

- For that Go Setup --> Object Manager --> Account --> Button Links and Actions --> Create New Action 

- Create a new action as below screenshot

Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid


And now add this quick action in your Account layout.

Now go to your Account object and open any record you will see quick action button there called as Create Record like :


Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid


- Click on that action.

You will see something like this and now you can put your input values and check the component. 


- When you open quick action 

Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid

- Undefined field check With Toast

Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid

- Once user filled up everything correctly and saved the record Success toast and close popup.

Create A Record In Salesforce Lightning Component With Error Handling By SalesforceKid


After this, you can go to the account object and see the will be created in the Account List Successfully!! 🎊

Visit our youtube channel for preview and demonstration of our output :


Coooool !! In this easy way, you can create the records with a completely customised salesforce lightning component. I hope this will be very easy for you guys to understand step by step.

If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 


SalesforceKid On play google play store
Create A Record In Salesforce Lightning Component With Error Handling Create A Record In Salesforce Lightning Component With Error Handling Reviewed by on Rating: 5


  1. Anonymous3/30/2020

    Hi Ajinkya. Your episodes are awesome.. can you please also make a tutorial on how to edit and delete a records using component?

    1. Sure, That EPISODES gonna out soon....

      Best Regards,

    2. Anonymous4/13/2020

      still waiting :)

  2. Anonymous3/30/2020


    what does it means??

  3. This is a smart blog. I mean it. You have an excellent knowledge about this topic. Thanks for sharing such a great blogs to us. Mexico Import Data

  4. The thrust is always on the utilization of the natural resources of the country in a sustainable manner, protection of the environment along with ensuring national security. Salesforce training in India

  5. Could this be adapted toto on a lightning App Page?



Powered by Blogger.