function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ravinder singh 95ravinder singh 95 

Dynamically add/remove rows for a table in LWC and on pageload load only 2 records

@ Danish Hoda,
I have used code fron this link (https://developer.salesforce.com/forums/?id=9062I000000XvbXQAS) and it is working fine. But I want to display 2 records on datatable when pageload and then the Add row functionaity(which is working fine).
Can you please help me on this.

Thanks
Best Answer chosen by ravinder singh 95
ravinder singh 95ravinder singh 95
<template>
    <div if:true={isLoaded} class="cstm-spinner">
		<lightning-spinner alternative-text="Loading..."></lightning-spinner>
	</div>
               
    <div class="slds-m-around--xx-large container-fluid">
        <div class="slds-float_right slds-p-bottom_small">
            <button class="slds-button slds-button_brand" disabled={disabledbtn} onclick={addRow}>Add Another collection</button>
        </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>      
                    
                    <template for:each={accountList} for:item="acc" for:index="indx">
                        <tr key={acc.key} id={acc.key}> 
                            <td>{indx}</td>                                                  
                            <td>
                                <lightning-input data-id={indx} label="Name" value={acc.Name} onchange={handleNameChange}></lightning-input>                               
                            </td>
                            <td>
                                <lightning-input data-id={indx} label="Account Number" value={acc.AccountNumber} onchange={handleAccountNumberChange}></lightning-input>                        
                            </td>
                            <td>
                                <lightning-input data-id={indx} label="Phone" value={acc.Phone} onchange={handlePhoneChange}></lightning-input>
                            </td>
                            <td style="vertical-align: bottom">
                                <lightning-button-icon icon-name="utility:delete"
																		  data-id={indx}       
																		  alternative-text="Delete"     
																		  class="slds-m-left_xx-small"
																		  onclick={removeRow} 
																		  title="Delete"></lightning-button-icon>
                            </td>
                        </tr>
                    </template>
                     
                </tbody>
            </table>
            <div class="slds-align_absolute-center slds-p-top_small slds-float_left">                
                <button class="slds-button slds-button_brand" onclick={saveRecord}>SAVE</button>
            </div>
        </div>
    </div>

</template>

If you run this code, you will notice that value of i is not decreasing when removing the row.If anyhow we decrease the value of i on remove buton click than we are done.

All Answers

Santosh Kumar 348Santosh Kumar 348
What is your requirement you have mentioned both are working fine. So what are you expecting?
ravinder singh 95ravinder singh 95
@Santosh Kumar 348
I have a scanerio, we can add upto 3 rows, and after e have added 3 rows button add "Add row" should be disabled.I have achieved this functionality.
Now when we remove a row, button again got enabled so that we can add one more row, I am not able to achieve this functionality.
Please find the code below.
import {LightningElement,track,api} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ACCOUNTNUMBER_FIELD from '@salesforce/schema/Account.AccountNumber';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import saveAccounts from '@salesforce/apex/AccountHelper.saveAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreateDynamicRecord extends LightningElement {
    @track accountList = []; 
    @track index = 0;
    @api recordId;
    @track name = NAME_FIELD;
    @track accNumber = ACCOUNTNUMBER_FIELD;
    @track phone = PHONE_FIELD;
    @track disabledbtn =false;
    isLoaded = false;
    
    @api record = {
        firstName : '',
        lastName : '',
        Email : '',
        Phone : '',
        Title : ''
    }

    acc = {
        Name : this.name,
        AccountNumber : this.accNumber,
        Phone : this.phone ? this.phone : "",
        key : ''
    }

    connectedCallback() {  
        this.accountList.push(JSON.parse(JSON.stringify(this.acc)));
    }  

    addRow(){

        this.index++;
        var i = this.index;
        console.log('i +++++++++++++'+ i);
        if(i < 3){
            this.disabledbtn = false;
            console.log('i ======== '+i);
            this.acc.key = i;
            this.accountList.push(JSON.parse(JSON.stringify(this.acc)));
            
        }else{
            console.log('In else');
            this.disabledbtn = true;
            this.showInfoToast();
        }
    }
    
    removeRow(event){
        this.isLoaded = true;
        var selectedRow = event.currentTarget;
        var key = selectedRow.dataset.id;
        if(this.accountList.length>1){
            this.accountList.splice(key, 1);
            this.index--;
            this.isLoaded = false;
            this.disabledbtn = false;
            console.log('Here 1');
        }else if(this.accountList.length == 1){
            this.accountList = [];
            this.index = 0;
            this.isLoaded = false;
            console.log('Here 2');
            
        }
    } 

    handleNameChange(event) {
        var selectedRow = event.currentTarget;
        var key = selectedRow.dataset.id;
        var accountVar = this.accountList[key];
        this.accountList[key].Name = event.target.value;
    }
    
    handleAccountNumberChange(event) {
        var selectedRow = event.currentTarget;
        var key = selectedRow.dataset.id;
        var accountVar = this.accountList[key];
        this.accountList[key].AccountNumber = event.target.value;
    }
    
    handlePhoneChange(event) {
        var selectedRow = event.currentTarget;
        var key = selectedRow.dataset.id;
        var accountVar = this.accountList[key];
        this.accountList[key].Phone = event.target.value;
    }
    
    saveRecord(){        
        saveAccounts({accList : this.accountList})
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.acc.Name = '';
                    this.acc.AccountNumber = '';
                    this.acc.Phone = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Account created successfully',
                            variant: 'success',
                        }),
                    );
                }
                
                console.log(JSON.stringify(result));
                console.log("result", this.message);
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log("error", JSON.stringify(this.error));
            });
    }

    showInfoToast() {
        const evt = new ShowToastEvent({
            message: 'Limit exceed to add collections',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
      
}
User-added image

Now when I remove the row, button gets enabled but can not able to add new row then.
Can you please help.

 
Santosh Kumar 348Santosh Kumar 348
Could you please post the template code here it seems ok to me.
ravinder singh 95ravinder singh 95
<template>
    <div if:true={isLoaded} class="cstm-spinner">
		<lightning-spinner alternative-text="Loading..."></lightning-spinner>
	</div>
               
    <div class="slds-m-around--xx-large container-fluid">
        <div class="slds-float_right slds-p-bottom_small">
            <button class="slds-button slds-button_brand" disabled={disabledbtn} onclick={addRow}>Add Another collection</button>
        </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>      
                    
                    <template for:each={accountList} for:item="acc" for:index="indx">
                        <tr key={acc.key} id={acc.key}> 
                            <td>{indx}</td>                                                  
                            <td>
                                <lightning-input data-id={indx} label="Name" value={acc.Name} onchange={handleNameChange}></lightning-input>                               
                            </td>
                            <td>
                                <lightning-input data-id={indx} label="Account Number" value={acc.AccountNumber} onchange={handleAccountNumberChange}></lightning-input>                        
                            </td>
                            <td>
                                <lightning-input data-id={indx} label="Phone" value={acc.Phone} onchange={handlePhoneChange}></lightning-input>
                            </td>
                            <td style="vertical-align: bottom">
                                <lightning-button-icon icon-name="utility:delete"
																		  data-id={indx}       
																		  alternative-text="Delete"     
																		  class="slds-m-left_xx-small"
																		  onclick={removeRow} 
																		  title="Delete"></lightning-button-icon>
                            </td>
                        </tr>
                    </template>
                     
                </tbody>
            </table>
            <div class="slds-align_absolute-center slds-p-top_small slds-float_left">                
                <button class="slds-button slds-button_brand" onclick={saveRecord}>SAVE</button>
            </div>
        </div>
    </div>

</template>

If you run this code, you will notice that value of i is not decreasing when removing the row.If anyhow we decrease the value of i on remove buton click than we are done.
This was selected as the best answer
Santosh Kumar 348Santosh Kumar 348
Hi Ravinder,

Remove your js code methods of addRow and remove row with below:
addRow(){
        this.index++;
        var i = this.index;
        console.log('i +++++++++++++'+ i);
        if(this.accountList.length<3){
            this.disabledbtn = false;
            console.log('i ======== '+i);
            this.acc.key = i;
            this.accountList.push(JSON.parse(JSON.stringify(this.acc)));
            
        }else{
            console.log('In else');
            this.disabledbtn = true;
            this.showInfoToast();
        }
    }
    
    removeRow(event){
        this.isLoaded = true;
        var selectedRow = event.currentTarget;
        var key = selectedRow.dataset.id;
        if(this.accountList.length>1){
            this.accountList.splice(key, 1);
            this.index--;
            this.isLoaded = false;
            this.disabledbtn = false;
        }else if(this.accountList.length == 1){
            this.accountList = [];
            this.index = 0;
            this.isLoaded = false;
            console.log('Here 2');
            
        }
    }

This will work.

Do let me know if it helps you and close your query by marking it as solved.

Regards,
Santosh
ravinder singh 95ravinder singh 95
Thanks Santosh, It is working fine now.
ravinder singh 95ravinder singh 95
Hi Santosh,
I have posted one more question, can you please help me on that.
https://developer.salesforce.com/forums/ForumsMain?id=9062I000000QxZiQAK