How to Add or Delete Dynamic Rows in Salesforce using Lightning Web Component

Introduction:

Lightning includes the Lightning Component Framework and some exciting tools for developers. Lightning makes it easier to build responsive applications for any device. Lightning includes these technologies:

Lightning components accelerate development and app performance. Develop custom components that other developers and admins can use as reusable building blocks to customize Communities, the Salesforce mobile app, and Lightning Experience. Lightning App Builder empowers admins to build Lightning pages visually, without code, using off-the-shelf and custom-built Lightning components. Make your Lightning components available in the Lightning App Builder so administrators can build custom user interfaces without code.Community Builder empowers admins to build communities visually, without code, using Lightning templates and components. Make your Lightning components available in Community Builder so administrators can build community pages without code. Using these technologies, you can seamlessly customize and easily deploy new apps to mobile devices running Salesforce.  In fact, the Salesforce mobile app and Salesforce Lightning Experience are built with Lightning components.

This guide teaches you to create your own custom Aura components and apps. You also learn how to package applications and components and distribute them in the AppExchange.

Don’t forget to check out: Inline Edit Support in Custom Component in Salesforce Lightning

Aura components are the self-contained and reusable units of an app. They represent a reusable section of the UI, and can range in granularity from a single line of text to an entire app. The framework includes a set of prebuilt components. For example, components that come with the Lightning Design System styling are available in the lightning namespace. These components are also known as the base Lightning components. You can assemble and configure components to form new components in an app. Components are rendered to produce HTML DOM elements within the browser.

A component can contain other components, as well as HTML, CSS, JavaScript, or any other Web-enabled code. This enables you to build apps with sophisticated UIs.

The details of a component's implementation are encapsulated. This allows the consumer of a component to focus on building their app, while the component author can innovate and make changes without breaking consumers. You configure components by setting the named attributes that they expose in their definition. Components interact with their environment by listening to or publishing events.

Step 1: Create a Lightning Component

Firstly we have to create a Lightning Component and for that go to setup->Developer console, At Developer, console Click on New to create a lightning component and use the code mentioned below:

<aura:component controller="AuraSampleController" Implements="flexipage:availableForRecordHome,force:hasRecordId">     
    <aura:attribute name="accountList" type="Account[]"/>      
    <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">#</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Name">Account Name</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Number">Account Number</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Phone">Phone</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" required="true" maxlength="50" label="Account Name" value="{!acc.Name}" />
                            </td>
                            <td>
                                <lightning:input name="accNumber" type="text"  maxlength="10" label="Account Number" value="{!acc.AccountNumber}" />
                            </td>
                            <td>
                                <lightning:input name="accPhone" type="phone" maxlength="10" label="Phone" value="{!acc.Phone}" />
                            </td>
                            <td>
                                <a onclick="{!c.removeRow}" 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.save}" />
            </div>
        </div>
    </div>
</aura:component>

Step 2: Create a Lightning Controller for the component

Now, we have created a component, firstly we have to handle the logic at the lightning level then we can move to apex side, for that we have to create a component controller by clicking on the controller in the panel in the right side and use the code mentioned below:

({
    addRow: function(component, event, helper) {
        helper.addAccountRecord(component, event);
    },     
    removeRow: function(component, event, helper) {
        var accountList = component.get("v.accountList");
        var selectedItem = event.currentTarget;
        var index = selectedItem.dataset.record;
        accountList.splice(index, 1);
        component.set("v.accountList", accountList);
    },     
    save: function(component, event, helper) {
        if (helper.validateAccountList(component, event)) {
            helper.saveAccountList(component, event);
        }
    },
})

Step 3: Create a helper class

Now create a helper class and call it in your controller. For that we need to click on the panel on the right side and use the code mentioned below:

({
    addAccountRecord: function(component, event) {
        var accountList = component.get("v.accountList");
        accountList.push({
            'sobjectType': 'Account',
            'Name': '',
            'AccountNumber': '',
            'Phone': ''
        });
        component.set("v.accountList", accountList);
    },     
    validateAccountList: function(component, event) {
        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 row number ' + (i + 1));
            }
        }
        return isValid;
    },     
    saveAccountList: function(component, event, helper) {
        var action = component.get("c.saveAccounts");
        action.setParams({
            "accList": component.get("v.accountList")
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.accountList", []);
                alert('Account records saved successfully');
            }
        }); 
        $A.enqueueAction(action);
    },
})

Step 4: Create an Apex class and define the method to create the record

Now the component which we have created will call lightning controller and then the controller will invoke Method that is written in apex class for that use the code mentioned below:

public with sharing class AuraSampleController {     
    @AuraEnabled
    public static void saveAccounts(List<Account> accList){
        Insert accList;
    }
}

Step 5: Create a Lightning Application

Which will host the component in the App.Lightning App has to created for the hosting purpose. For that Go to Developer Console->New Lightning Application and use the code mentioned below:

<aura:application extends="force:slds">
    <c:AddDeleteDynamic/>
</aura:application>

Step 6: Test the Application

We have successfully created the application and it’s time to test it. Save and Click on Update Preview to view your created Application. Your page will look something like this.

Popular Salesforce Blogs