addDelete

Add and Delete rows by Lightning Web Component in table Salesforce

LWC

This blog will help to create a custom Lightning web component for Add and Delete Contact record.

addDeleteRow.html

<template>
 <lightning-card class="slds-m-around_medium" title="Contacts List">
    <div class="spinner">
        <template if:true={isLoading}>
             <lightning-spinner alternative-text="Loading" variant="brand" size="large">
             </lightning-spinner>
        </template>
    </div>
    <table class="slds-table">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Description</th>
            <th>cleanstatus</th>
        </tr>
        <template iterator:it={contacts}>
            <tr key={it.value.Name}>
                <td>
                    <lightning-input
                        type="text"
                        label="First Name"
                        value={it.value.FirstName}
                        data-record-id={it.index}
                        onchange={handleChange}
                        variant="label-hidden">
                    </lightning-input>
                </td>
                <td>
                    <lightning-input
                        type="text"
                        label="Last Name"
                        value={it.value.LastName}
                        data-record-id={it.index}
                        onchange={handleChange}
                        variant="label-hidden">
                    </lightning-input>
                </td>
                <td>
                    <lightning-input
                        type="Email"
                        label="Email"
                        value={it.value.Email}
                        data-record-id={it.index}
                        onchange={handleChange}
                        variant="label-hidden">
                    </lightning-input>
                </td>
                <td>
                    <lightning-input
                        type="text"
                        label="Description"
                        value={it.value.Description}
                        data-record-id={it.index}
                        onchange={handleChange}
                        variant="label-hidden">
                    </lightning-input>
                </td>  
                <td>
                    <lightning-combobox
                        label="CleanStatus"
                        value={it.value.CleanStatus}
                        options = {cleanstatus}
                        data-record-id={it.index}
                        onchange={handleChange}
                        variant="label-hidden">
                    </lightning-combobox>
                </td>
                <td> <lightning-button data-record-id= {it.index} label="Delete" onclick={deleteRow}></lightning-button></td>
            </tr>
          </template>
          <tr>
            <td> <lightning-button label="Add Row" onclick={addRow}></lightning-button></td>
            <td></td>
            <td> <lightning-button label="Save" onclick={saveContacts}></lightning-button></td>
            
         </tr>
           
        </table>
 </lightning-card>
    
    
</template>

addDeleteRow.js

import { LightningElement, wire } from 'lwc';
import CONTACT_OBJECT from '@salesforce/schema/contact';
import { getPicklistValues,getObjectInfo } from 'lightning/uiObjectInfoApi';

import CLEANSTATUS_FIELD from '@salesforce/schema/Contact.CleanStatus';
import updateContacts from '@salesforce/apex/ContactController.updateContacts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { CloseActionScreenEvent } from 'lightning/actions'; // this is use to close component



export default class AddDeleteRow extends LightningElement {
   contacts;
   cleanstatus; 
   isLoading = false;
    connectedCallback(){
        this.contacts = [{
            FirstName : null,
            LastName : null,
            Email : null,
            Description : null,
            CleanStatus : null
        }]

    }

    @wire(getObjectInfo,{objectApiName:CONTACT_OBJECT})
    objectInfo;

    @wire( getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: CLEANSTATUS_FIELD } )
    getStatusValue({error,data}){
        if(data){
            this.cleanstatus = data.values.map(objPL => {
                return {
                    label: `${objPL.label}`,
                    value: `${objPL.value}`
                }
            });
            console.log('this.cleanstatus==>> '+this.cleanstatus);
        }else if(error){
            console.error( JSON.stringify( error ) );  
        }
    }

    addRow(){
        let newContact = {
            FirstName : null,
            LastName : null,
            Email : null,
            Description : null,
            CleanStatus : null
        }

        if(this.contacts){
            this.contacts = [...this.contacts,newContact];
        } else{
            this.contacts = [newContact];    
        }

    }

    deleteRow(event){
        let indx = event.target.dataset.recordId;

        console.log('indx=== '+indx);
        let tempContactList = this.contacts;
        tempContactList.splice(indx,1);
        console.log( 'Temp Contacts are ' + JSON.stringify( tempContactList ) );
        this.contacts = JSON.parse( JSON.stringify( tempContactList ) );
    }

    handleChange(event) {
        let recs =  this.contacts;
        let value = event.target.value;
        let label = event.target.label;
        let name;

        switch( label ) {

            case 'First Name':
                name = 'FirstName';
                break;

            case 'Last Name':
                name = 'LastName';
                break;

            case 'Email':
                name = 'Email';
                break;

            case 'Description':
                name = 'Description';                
                break;

            case 'CleanStatus':
                name = 'CleanStatus';
                value = event.target.checked;
                break;
        }

        console.log( label + ' – ' + value );
        let strIndex = event.target.dataset.recordId;
        console.log( 'Index is ' + strIndex );
        let rec = recs[ strIndex ];
        rec[ name ] = value;
        recs[ strIndex ] = rec;
        console.log( 'Temp Contacts are ' + JSON.stringify( recs ) );

        console.log('LIST OF CONTACTS==>>> '+JSON.stringify( this.contacts ) )
        this.contacts = JSON.parse( JSON.stringify( this.contacts ) );
    }
    
    saveContacts(){
        this.isLoading = true;
        updateContacts({conList : this.contacts})
        .then(result => {
            console.log( 'Result ' + result );
            let message;
            let variant;
           
            if ( result == "Successful" ) {
                message = 'Successfully Processed!';
                variant = 'success';
                this.isLoading = false;


            } else {

                message = 'Some error occured. Please reach out to your Salesforce Admin for help!';
                variant = 'error';
                
            }   
            
            const toastEvent = new ShowToastEvent({
                title: 'Contact Created',
                message: message,
                variant: variant
            });
            this.dispatchEvent(toastEvent);
            
            this.dispatchEvent(new CloseActionScreenEvent());


        }).catch( error => {

            console.log( 'Error ' +  error );
            
        } );

    }

}

addDeleteRow.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Add Delete Contact</masterLabel>
    <targets>
      <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
            <actionType>ScreenAction</actionType>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

uniquesymbol

Leave a Reply