Add Delete Row Dynamically In Salesforce Lightning

By | March 24, 2021

In this blog, we will discuss how to Add Delete Row Dynamically In Salesforce Lightning Component. We shall take an example of adding account records in Salesforce using Add Delete Row functionality.

Similarly, we have created 1 sample lightning component using which user can create multiple records as per requirement by Adding or Deleting new rows on UI. Also make ‘Account Name’ as mandatory field.

  • Step 1: Go to the Developer Console ->> File ->> New ->> Apex Class: AuraController.apxc
    • Create apex class i.e. AuraController
    • Create AuraEnabled method i.e. saveAccountList which take single parameter to hold account list. Refer below code snippet.
public class AuraController 
{   
    @AuraEnabled
    public static void saveAccountList(List<Account> accList) 
	{        
        Insert accList;
    }
}
  • Step 2: Go to the Developer Console ->> File ->> New ->> Lightning Component: AuraComponent.cmp
    • Declare attribute of type account array to store multiple account and name it as ‘accountList’.
<aura:component controller="AuraController" Implements="force:appHostable,flexipage:availableForRecordHome,force:hasRecordId">
    <aura:attribute name="accountList" type="Account[]"/>
    <lightning:card>
        <div class="slds-m-around--xx-large">
            <div class="slds-float_right slds-p-bottom_small">
                <h1 class="slds-page-header__title">Add Row 
                    <lightning:buttonIcon iconName="utility:add"  size="large" variant="bare" alternativeText="Add" onclick="{!c.addRow}"/>
                </h1>
            </div>
            <div class="container-fluid">        
                <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
                    <thead>
                        <tr class="slds-text-title_caps">
                            <th scope="col">
                                <div class="slds-truncate">Sr. No</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Account Name">Account Name</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Phone">Phone</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Fax">Fax</div>
                            </th>  
                            <th scope="col">
                                <div class="slds-truncate" title="Website">Website</div>
                            </th>  
                            <th scope="col">
                                <div class="slds-truncate" title="Action">Action</div>
                            </th>
                        </tr>
                    </thead>   
                    <tbody>      
                        <aura:iteration items="{!v.accountList}" var="acc" indexVar="index">
                            <tr>
                                <td> 
                                    {!index + 1}
                                </td>
                                <td>
                                    <lightning:input name="accName" type="text" maxlength="50" value="{!acc.Name}" />
                                </td>
                                <td>
                                    <lightning:input name="accPhone" type="phone" maxlength="10" value="{!acc.Phone}" />
                                </td>
                                <td>
                                    <lightning:input name="accFax" type="text" value="{!acc.Fax}" />
                                </td>
                                <td>
                                    <lightning:input name="accWebsite" type="text" value="{!acc.Website}" />
                                </td>
                                <td>
                                    <a onclick="{!c.removeRecord}" data-record="{!index}">
                                        <lightning:icon iconName="utility:delete" size="small" alternativeText="Delete"/>
                                        <span class="slds-assistive-text">Delete</span>
                                    </a>
                                </td> 
                            </tr>
                        </aura:iteration>
                    </tbody>
                </table>
                <div class="slds-align_absolute-center slds-p-top_small">
                    <lightning:button variant="brand" label="Submit" title="Brand action" onclick="{!c.saveAccounts}" />
                </div>
            </div>
        </div>
    </lightning:card>
</aura:component>

Lightning JS Controller: AuraComponentController.js

See code comment

({
    addRow: function(component, event, helper) {
        //get the account List from component  
        var accountList = component.get("v.accountList");
        //Add New Account Record
        accountList.push({
            'sobjectType': 'Account',
            'Name': '',
            'Phone': '',
            'Fax': '',
            'Website ': '', 
            
        });
        component.set("v.accountList", accountList);
    },
    
    removeRecord: function(component, event, helper) {
        //Get the account list
        var accountList = component.get("v.accountList");
        //Get the target object
        var selectedItem = event.currentTarget;
        //Get the selected item index
        var index = selectedItem.dataset.record;
        //Remove single record from account list
        accountList.splice(index, 1);
        //Set modified account list
        component.set("v.accountList", accountList);
    },
    	
    saveAccounts: function(component, event, helper) {      
        if (helper.validateAccountRecords(component, event)) {
            //Call Apex method and pass account list as a parameters
            var action = component.get("c.saveAccountList");
            action.setParams({
                "accList": component.get("v.accountList")
            });
            action.setCallback(this, function(response) {
                //get response status 
                var state = response.getState();
                if (state === "SUCCESS") {
                    //set empty account list
                    component.set("v.accountList", []);
                    alert('Accounts saved successfully');
                }
            }); 
            $A.enqueueAction(action);
        }
    },
})

Lightning JS Helper: AuraComponentHelper.js

See code comment

({
    validateAccountRecords: function(component, event) {
        //Validate all account records
        var isValid = true;
        var accountList = component.get("v.accountList");
        for (var i = 0; i < accountList.length; i++) {
            if (accountList[i].Name == '') {
                isValid = false;
                alert('Account Name cannot be blank on '+(i + 1)+' row number');
            }
        }
        return isValid;
    },
})

Output:

Create Account Record:

Create Account Record
Create Account Record

Created Account Records:

Created Records in Account Object
Created Records in Account Object

We hope you may find this Blog resourceful and helpful. If you still have concerns and need more help, please contact us at salesforce@greytrix.com

About Us
Greytrix – a globally recognized and one of the oldest Sage Development Partner and a Salesforce Product development partner offers a wide variety of integration products and services to the end users as well as to the Partners and Sage PSG across the globe. We offer Consultation, Configuration, Training and support services in out-of-the-box functionality as well as customizations to incorporate custom business rules and functionalities that require apex code incorporation into the Salesforce platform.

Greytrix has some unique solutions for Cloud CRM such as Salesforce Sage integration for Sage X3Sage 100 and Sage 300 (Sage Accpac). We also offer best-in-class Cloud CRM Salesforce customization and development services along with services such as Salesforce Data MigrationIntegrated App developmentCustom App development and Technical Support to business partners and end users.
Salesforce Cloud CRM integration offered by Greytrix works with Lightning web components and supports standard opportunity workflow. Greytrix GUMU™ integration for Sage ERP – Salesforce is a 5-star rated app listed on Salesforce AppExchange.

The GUMU™ Cloud framework by Greytrix forms the backbone of cloud integrations that are managed in real-time for processing and execution of application programs at the click of a button.

For more information on our Salesforce products and services, contact us at salesforce@greytrix.com. We will be glad to assist you.

Related Posts: