SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.


Telegram logo   Join our Telegram Channel

Saturday, 10 February 2018

Salesforce Lightning Tutorial - Part 3 | Delete Records from Server

This is the third post in Lightning Tutorial Series and in this post, you'll learn about how to delete the records displayed using a lightning component. In this post, I'll be extending the code used in my first and second post so, if you are just starting or need to learn only about deleting records only do have a look at my previous posts or at least the code by having a look at my blog posts starting from here or my github repository code in update branch here.

Let's start by looking at our code files one by one and doing changes to add a delete feature to our component. 

1. Apex Controller

As you know, till now we had only two methods in our Apex Controller getContactList - used to fetch contact list from server and saveContactList - which was used to save the records from our lightning component to salesforce. Let's have a look at the below code now:-

As you can see above that I have added one more method in our controller namely -  deleteContactList which is responsible for deleting the contact list by getting the ids of contacts which we have to delete. So, as you can see, the deleteContactList method has a single parameter i.e. a list of contact ids and then it is using those list of contact ids to fetch the contacts from the database. I have initialized a map of key and value pairs both of type string and named it resultMap as done previously in the saveContactList method. As I am using the delete keyword to delete the contacts, it only accept an SObject or a SObject List that's why I have done a SOQL query to fetch the contacts related to the ids passed in the method. If you don't want to do the SOQL query, you can pass the list of contacts in the parameter as I have done in save method. But it will be heavier to pass more data to server that's why I have limited it to list of ids only. A more better approach is to use Database.delete method which we'll learn in upcoming tutorials. I have surrounded this query within a try catch so that it can catch any kind of exception and formed a result map in both the cases with key - value pairs of my choice and returned that resultMap as a response.

2. Lightning Component

We are done with the apex controller so let's move on to the lightning component in which we have to do very little changes to make our component capable of deleting record. Let's have a look at the code below:-

As you can see, in the recordView form, I have added a lightning:input tag with the following attributes:-
  1.  type="checkbox"
  2. value="{!contact.Id}" ( As the input tag is under aura:iteration with eachrecord referred by var contact )
  3. label="Mark for Deletion"
  4. aura:id="deleteContact"
  5. checked ( has a type boolean and will be true if checkbox is checked. No need to define and give an initial value to this )
So, each record will display a checkbox with label as - Mark for Deletion that means you want to mark this contact for deletion or not ? and finally we add a button that will delete all the contacts that are marked for deletion on click of a delete button that I have added in the lightning card actions section with variant as destructive, label as delete and will call the controller method deleteContacts on clicking of this button.

3. Lightning Controller

Moving on to our lightning controller, as my button is calling the deleteContacts controller method on click, so I have to define the same in my controller. Here is the code for the lightning controller:- 


You can see above that the last function is deleteContacts that is only calling the helper's removeContacts method as all the server related work, I prefer to do in helper so here also on clicking of delete button all the operations take place in helper.

4. Lightning Helper

Moving on to out lightning helper now, let's have a look at the code first and then discuss things one by one:- 


As you can see above, I have added one method namely - removeContacts at the last which is responsible for deleting the marked contacts. First of all this method is getting the component which has an aura:id of deleteContact. If component.find() finds a single component with the aura:id given then it returns that component, otherwise it returns an array of components. So we have initialized an empty array namely idsToDelete which will store the ids that we have to pass to our apex controller to delete the contacts. Then we are checking that whether the returned value of our component.find or the contactsToDelete variable is array or not. So, in javascript we can always get the length of array using [].length and if the length is undefined that means that I have a single component (single contact record) not an array.

If I have a single contact record, the else condition will be executed and I'll check that whether my checked attribute is true or false and if it's true I'll add that component to the list of ids ( array ) which is to be passed to apex controller for deletion and if I have multiple contact records, I'll traverse through the array and do exactly the same thing. This was the whole logic and the rest part is same as in saveContacts method, I have initialized a toast, and then a deleteAction which is calling the deleteContactList apex controller's method. I am passing the idsToDelete array to the method's param contactIds . In the callback function I am checking the state, if the state is success and the dataMap has also the status of success, then fire a success toast and reload the page using window.location.reload and if the state is success but status is error, then we'll fire the error toast event with the exception or error message displayed from dataMap. Otherwise if the state is not success, then I have simply displayed an alert - error in getting data. Finally I have added this action to the global action queue using $A.enqueueAction().

Congratulations..!! You have added the functionality to delete the record in your lightning component too and your final component looks like this:-


Tired of reading or just scrolled down..!! Don't worry, you can watch the video too.


If you liked this post then do follow, subscribe, comment your views or any feedback and share it with everyone in your circle so that they can also get benefit by this. Hope to see you next time too when we'll learn how to create new records using our lightning component and custom ui instead of calling standard create record global event. For the whole code at one place, please refer to my github repository here. You can fork this repo and do your own changes. However please switch to delete branch to get the code specified here and not the future changes. Otherwise, directly go to the delete branch by clicking here.

Let's move on to Lightning Tutorial Part 4 now in which you'll learn how you can create a new record using your own custom lightning component and save the record to salesforce.

Happy Trailblazing..!!

18 comments:

  1. Appreciate your work.! Nice & easy way to learn LEX Dev.

    ReplyDelete
    Replies
    1. Thank you so much for your appreciation... :-)

      This really motivates me to do more for the community.

      Delete
  2. Rahul excellent work buddy..

    ReplyDelete
    Replies
    1. Happy to see that you liked it Ershad :-) Do share it in your network so that others can get benefit too.

      Delete
  3. Hi you are doing great work . please post articles on Apex Integrations and Callouts .

    ReplyDelete
    Replies
    1. Hi, Thanks for your suggestion. Please add it here too:- https://sfdcstop.blogspot.com/p/what-do-you-want-us-to-post-next.html Do share these tutorials in your network too :-)

      Delete
  4. Nice job Rahul. Following all your blogs. It helped me to learn a lot.

    ReplyDelete
    Replies
    1. Good to know that it helped Ankit. Make sure to share it in your network too :-)

      Delete
  5. Nice job Rahul, Following all your blogs/videos. It help me to learn a lot. Really appreciate all your effort.

    ReplyDelete
    Replies
    1. Good to know that it helped Ankit. Make sure to share it in your network too :-)

      Delete
  6. Replies
    1. Thanks buddy :-) share it among your peers too.

      Delete
  7. Superb work,
    but I have one concern if unselect the checkbox it will be display message please select checkbox.How to do please sugget me.

    ReplyDelete
    Replies
    1. Hi Krishna,

      You just need to check if idsToDelete array is empty before firing the delete action. Just add a check like:- if(idsToDelete.length==0) { fire a toast with message:- please select a checkbox }

      Delete
  8. Hi Rahul,
    superb article, but i have one concern if not select checkbox it will display alert message.How to do please suggest me.

    ReplyDelete
    Replies
    1. Thanks Krishna :-) Make sure to share it among your network too. Please see my comment above for your query.

      Delete