Create A Record In Salesforce Lightning Component With Error Handling

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

HOW TO CREATE A RECORD IN SALESFORCE LIGHTNING COMPONENT

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. 

Get...Set...Go....Kid 

Steps to follow :

STEP 1 :
Create a lightning component createRecord.cmp

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" 
                  type="list" 
      default="[
                {'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"/>
    
  <center>
      <h1 class="inlineTitle slds-p-top--large slds-p-horizontal--medium slds-p-bottom--medium slds-text-heading--medium" 
            style="font-size:20px">
            Custom Create Account
            <hr size="3" noshade=""></hr>
      </h1>
  </center>
    
   <h2 class="slds-section__title slds-theme--shade primaryPaletteBorder test-id__section-header-container"
        New Account Information
   </h2>
    
    <div class="slds-p-around_medium">
        <lightning:input name="Name" 
                         required="true" 
                         value="{!v.name}" 
                         label="Name" 
                         maxlength="255"/>
        
        <lightning:combobox name="Status" 
                            label="Status" 
                            value="inProgress" 
                            placeholder="Select Progress" 
                            options="{!v.options}" 
                            onchange="{!c.handleChange}"/>
        
        <lightning:input type="number" 
                         name="Annual Revenue"
                         label="Annual Revenue" 
                         value="{!v.annualRevenue}" 
                         formatter="currency"
                         fieldLevelHelp="Please enter in numbers"/>
        
    </div> 
    <center>
        <lightning:button variant="Brand" 
                          label="Save" 
                          title="Save" 
                          onclick="{!c.save}"/>
        <lightning:button variant="Neutral" 
                          label="Cancel" 
                          title="Cancel" 
                          onclick="{!c.cancel}"/>
    </center>
</aura:component>
--------------------------------------------------------

- 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="{!c.save}" and onclick="{!c.cancel}" actions.

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

createRecordController.js
--------------------------------------------------------
({    
  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("v.name");
        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');
        }
        else
        {
    //if everything is okey then make server call   
      var action = component.get("c.saveAccount"); 
         action.setParams({
           name : name
           accountType : type,
           revenue : annualRevenue
            }); 
     action.setCallback(this,function(response){
     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');
           $A.get("e.force:closeQuickAction").fire();
         }
       });
          $A.enqueueAction(action);
      }  
    },
    
    cancel : function(component, helper, event)
    {
        //Below line of code will close the modal popup
        $A.get("e.force:closeQuickAction").fire();   
    }
}) 
--------------------------------------------------------

- 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 here....as 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 :

createRecordHelper.js
--------------------------------------------------------
({
   //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");
        toastEvent.setParams(toastParams);
        toastEvent.fire();
    }
})
--------------------------------------------------------

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 :

createRecordController.apxc
--------------------------------------------------------

public class createRecordController {

    

@AuraEnabled

 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. 

OUTPUT :
--------------------------------------------------------

- 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.

WOHOOO !! YOU HAVE JUST COMPLETED CUSTOM CONFETTI IN SALESFORCE LIGHTNING COMPONENT EPISODE
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.) 😊 

<< PREVIOUS

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

9 comments:

  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?
    Thanks

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

      Best Regards,
      AJINKYA DHAS

      Delete
    2. Anonymous4/13/2020

      still waiting :)

      Delete
  2. Anonymous3/30/2020

    implements="force:lightningQuickActionWithoutHeader"

    what does it means??

    ReplyDelete
  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

    ReplyDelete
  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



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

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.