Saturday, January 30, 2021

Add or Delete Multiple Rows in LWC

Salesforce image



we are creating custom component for inserting multiple records in a single hit. It will prevent to consuming a lot of time in adding multiple records. As we know, In standard salesforce when we manually create any record, it create only one record at a time. So if you have any scenario when you need to create multiple records manually, this component will help you.

Let's Create Step by Step...

In Lightning Web Component, we are using visual studio code editor for writing code and deploy the component to salesforce org. When we create new component in LWC it generates three files:

1. HTML

2. Java Script

3. XML

We have created Lightning Web Component with name "Visitors" for the Salesforce Community page. 


STEP 1: Create visitors.html file.


<template> 
    <div class="slds-card border-mod">
        
        <template for:each={visitorList} for:item="v" for:index="index">
            <div class="slds-card__body" key={v.key} id={v.key}>
                    
                <div class="slds-grid">  
                    <div class="slds-col slds-grid slds-small-size_11-of-12 
                        slds-medium-size_11-of-12 slds-large-size_11-of-12" >

                        <div class="slds-col margin-horizontal">
                            <lightning-input type="text" placeholder="Full Name" 
                                name="name" data-index={index}  value={v.name} 
                                label="Name" onchange={handleChange} required >
                            </lightning-input>
                        </div>
                        <div class="slds-col margin-horizontal">         
                            <lightning-input type="text"  placeholder="Company Name" 
                                name="company" data-index={index} value={v.company} 
                                label="Company" onchange={handleChange} required>
                            </lightning-input>
                        </div>
                        <div class="slds-col margin-horizontal">
                            <lightning-input type="email"  placeholder="Email Address"
                                 name="email" data-index={index} value={v.email} 
                                 label="Email" onchange={handleChange} required>
                            </lightning-input>
                        </div>
                        <div class="slds-col margin-horizontal">   
                            <lightning-input type="tel"  placeholder="Phone Number" 
                                name="phone" data-index={index} value={v.phone} 
                                label="Phone" onchange={handleChange} required>
                            </lightning-input>
                        </div>   
                    </div>

                    <div class="slds-col slds-grid slds-small-size_1-of-12 
                        slds-medium-size_1-of-12 slds-large-size_1-of-12 action-btn "> 
                        <lightning-button-icon icon-name="utility:delete" size="medium" 
                            class="btnDelete" variant="border-filled" 
                            data-index={index} alternative-text="Delete"     
                            onclick={deleteRow}>
                        </lightning-button-icon>
                    </div>   
                </div>  

            </div>
        </template>

        <!-- Add Row Button -->
        <lightning-button variant="neutral" label="Add Row"  
            onclick={addRow} class="margin-left"> 
        </lightning-button>

         <!-- Save Button -->
        <footer class="slds-modal__footer margin-top">             
            <lightning-button  variant="brand" name="save" 
                label="Save" onclick={handleSave} >
            </lightning-button>
        </footer>

    </div>             
</template>

In html we are using lightning-input, lightning-button etc and html elements with slds properties like slds-grid, slds-col etc for moble, tablet responsiveness.


STEP 2: Create visitors.js file.


import { LightningElementapitrack } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { createRecord } from 'lightning/uiRecordApi';
import VISITOR_OBJECT from '@salesforce/schema/Visitor__c';
import NAME_FIELD from '@salesforce/schema/Visitor__c.Name';
import COMPANY_FIELD from '@salesforce/schema/Visitor__c.Company__c';
import EMAIL_FIELD from '@salesforce/schema/Visitor__c.Email__c';
import PHONE_FIELD from '@salesforce/schema/Visitor__c.Phone__c';

export default class Visitors extends LightningElement {
    @api recordId;
    @track visitorList = [{
        name:'',
        company:'',
        email:'',
        phone:''  
    }];

  
    addRow() {
        this.visitorList.push(JSON.parse(JSON.stringify(this.visitorList)));
    }

    deleteRow(event) {
        var rowIndex = event.currentTarget.dataset.index;
        if(this.visitorList.length > 1) {
            this.visitorList.splice(rowIndex1);
        } 
    }

    handleChange(event) {
        var rowIndex = event.currentTarget.dataset.index;
        if(event.target.name === 'name') {
            this.visitorList[rowIndex].name = event.target.value;
        } else if(event.target.name === 'company') {
            this.visitorList[rowIndex].company = event.target.value;
        } else if(event.target.name === 'email') {
            this.visitorList[rowIndex].email = event.target.value;
        } else if(event.target.name === 'phone') {
            this.visitorList[rowIndex].phone = event.target.value;
        }
    }


    handleSave() { 
        var emptyCheck = false
        for(let rowIndex in this.visitorList) { 
            if(this.visitorList[rowIndex].name == null ||
                this.visitorList[rowIndex].company == null ||    
                this.visitorList[rowIndex].email == null || 
                this.visitorList[rowIndex].phone == null ||
                this.visitorList[rowIndex].name == '' ||
                this.visitorList[rowIndex].company == '' ||
                this.visitorList[rowIndex].email == '' || 
                this.visitorList[rowIndex].phone == '') {
                emptyCheck = true;
                this.dispatchEvent(new ShowToastEvent({
                    title: 'Error',
                    message: 'Please fill all empty fields',
                    variant: 'error',
                }));
                return false;
            } else {
                console.log('pass');
            }
        }
       
        if(emptyCheck === false) {
        const fields = {}; 
        for(let rowIndex in this.visitorList) {
            fields[NAME_FIELD.fieldApiName] = this.visitorList[rowIndex].name;
            fields[COMPANY_FIELD.fieldApiName] = this.visitorList[rowIndex].company;
            fields[EMAIL_FIELD.fieldApiName] = this.visitorList[rowIndex].email;
            fields[PHONE_FIELD.fieldApiName] = this.visitorList[rowIndex].phone;
           
            const recordInput = { apiName: VISITOR_OBJECT.objectApiNamefields};
            createRecord(recordInput)
            .then(result => {
                if(result !== undefined) { 
                    this.visitorList[rowIndex].name = '';
                    this.visitorList[rowIndex].company = '';
                    this.visitorList[rowIndex].email = '';
                    this.visitorList[rowIndex].phone = '';
                    this.dispatchEvent(new ShowToastEvent({
                        title: 'Success',
                        message: 'Visitor created Successfully',
                        variant: 'success',
                    }));
                }
            })
            .catch(error => {
                this.dispatchEvent(new ShowToastEvent({
                    title: 'Error creating record',
                    message: error.body.message,
                    variant: 'error',
                }));
            });
         }
       }
    }

}

In Java Script file, we have created four methods:

1. addRow : This method is adding the row to the array using push method on every click.

2. deleteRow : This method is deleting the row from the array using splice method.

3. handleChange : This method is getting the values from the input fields on any changes.

4. handleSave : This method first checking all the fields is empty or not, if not empty any fields then insert the records using createRecord lightning method.


STEP 3: Create visitors.css file.


.border-mod{
    border1px solid #000
    padding-left1%;
}

.margin-horizontal{
    margin0 1%;
}

.action-btn{
    padding-top:24px;
    justify-Content:space-evenly;
}

.margin-top{
    margin-top1%;
}

.margin-left{
    margin-left1%;
}

@media (max-width768px){   
    lightning-input {
        widthmax-content;
    } 
}


This css file is creating for styling and alignment the contents and layout.


STEP 4:  Create visitors.js-meta.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
      
    </targets>
    <targetConfigs>
        <targetConfig targets="lightningCommunity__Default">
            <property name="recordId" type="String" label="Record ID"
                description="Should be set to {!recordId}"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

In this file, we are targeting the lightningCommunity page for deploy and display the UI of the component on the Community page. You can also target this component into the salesforce home and record page by adding "lightning_HomePage" and "lightning_RecordPage" inside the target tag.

For more information: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_configuration_tags


For any queries or suggestions, comment below.

Happy Coding...😊




No comments:

Post a Comment