Lightning Series 3 – Building a Simple Lightning App to View, Edit and Delete Records

In our previous series, we have talked about searching and inserting new records using lightning components. In this blog, we gonna talk about how we can view, edit and delete the records in lightning experience.

VIEW, EDIT AND DELETE RECORD FROM THE LIST OF RECORDS DISPLAYED IN TABLE

StaffView

We need to create below three elements to build the complete functionality:

  1. Apex Class
  2. Lightning Component
  3. JS controller

Apex Class:

Below apex class has different methods invoked based on the action required from user like viewing, updating and deleting the records.  @AuraEnabled enables you to access this method in lightning component.

/************************************************************

Name: CreatestaffRecord
Type: Apex Class  
Purpose: Apex Class  for  lightning component 
CreatestaffRecordController.cmp
***********************************************************/
public with sharing class CreateStaffRecord {
    
    @AuraEnabled
    public static void updateRecord(Staff__c staff){
        try{
            update staff;
        }catch(DMLException e){
            throw new AuraHandledException(e.getDMLMessage(0)); 
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage()); 
        }       
    }  
    
    @AuraEnabled
    public static Staff__c deleteRecord(Staff__c staff){
        try{
            if(staff != null){
                delete staff;
            }
        }catch(DMLException e){
            throw new AuraHandledException(e.getDMLMessage(0)); 
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage()); 
        }  
        return staff;
    }
}

Lightning Component:

Let’s hit on the ground and create a component to view, edit and delete a record of  Staff.

Please click here to view the code:

JS Controller:

StaffRecordViewController.js

({
    doInit : function(component){
        
        // Get a reference to the getWeather() function defined in the Apex controller
        var action = component.get("c.getStaffRecord");
        action.setParams({
            "staffId": component.get("v.recordId")
        });
        // Register the callback function
        action.setCallback(this, function(response){
            // Set the component attributes using values returned by the API call
            if (response.getState() == 'SUCCESS') {
                var staff=response.getReturnValue();
                
                component.set("v.staff", staff);
                component.set("v.isEditMode", false);
            }
        });
        // Invoke the service
        $A.enqueueAction(action);
    },
    
    handleStaffEvent : function(component, event) {
        var recId = event.getParam("recordId");
        // set the handler attributes based on event data
        component.set("v.recordId", recId);

        var action = component.get('c.getStaffRecord');
        
        action.setParams({"staffId": recId});
        
        action.setCallback(this, function(response){
            
            if (response.getState() == 'SUCCESS') {
                
                
                var staff=response.getReturnValue()
                component.set("v.staff", staff);
                
                component.set("v.isEditMode", false);
            }
        });
        $A.enqueueAction(action);   
       
    },
    editStaff : function(component){        
        component.set("v.isEditMode",true);
    },
    cancelPage : function(component){        
        component.set("v.isEditMode",false);
    },    
    saveStaff : function(component, event, helper){
        // Get a reference to the updateRecord() function defined in the Apex controller
        //getting the staff information
        var staff = component.get("v.staff");       
        
        //Make field required from front end (Not from DB)
        if(staff.Last_Name__c==''){
            alert('Missing Last name');
            return false;
        }
        
        
        var action = component.get("c.updateRecord");
        action.setParams({
            staff : staff
        });
        // Register the callback function
        action.setCallback(this, function(response){
            var state = response.getState();
            
            // Set the component attributes using values returned by the API call
            if (state == "SUCCESS") {
                    
                component.set("v.staff", staff);
                
                component.set("v.isEditMode", false);
               
            }else if(state == "ERROR"){
                //errors coming from DB thrown by controler catch blocl
                let errors = response.getError();
                let message;
                // Retrieve the error message sent by the server
                if (errors && Array.isArray(errors) && errors.length > 0) {
                    message = errors[0].message;
                }
                
                alert(message);
            }
        });
        // Invoke the service
        $A.enqueueAction(action);
    },
    
    delStaff : function(component, event, helper){
        // Get a reference to the updateRecord() function defined in the Apex controller
        //getting the staff information
        var staff = component.get("v.staff");        
        var action = component.get("c.deleteRecord");
        action.setParams({
            staff : staff
        });
        
        // Register the callback function
        action.setCallback(this, function(response){
            // Set the component attributes using values returned by the API call
            if (response.getState() == 'SUCCESS') {
                component.set("v.staff", staff);
                component.set("v.isEditMode", false);
            }
        });
        
        
        // Invoke the service
        $A.enqueueAction(action);
        alert("Record is deleted.");
        
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
            "url": "/a00/o"
        });
        
        urlEvent.fire();
    }
})     
    

Author:

Ajomon Joseph AJOMON JOSEPH
Senior Salesforce Architect
In Connect me on LinkedIn
twitter Follow me on Twitter @apexcoder
blogger Subscribe to my blog https://apexcoder.com
email Email me ajomon@apexcoder.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s