1

I have a requirement to create multiple records of a custom object by Adding or Deleting new rows on UI using Lightning Web Components. I was able to add one record by binding each lightning-input using event.target.value taking name attribute of the lightning-input as the unique identifier but I'm unable to understand how to do this dynamically.

Html code:

<lightning-layout-item padding="around-small">
      <lightning-input type="number" formatter="currency" name="amount" value={Custom_Object__c.Amount__c} onchange={handleChange} required></lightning-input>
</lightning-layout-item>

<lightning-layout-item padding="around-small">
      <lightning-input name="size" value={Custom_Object__c.Size__c} onchange={handleChange} required></lightning-input>
</lightning-layout-item>

JavaScript code:

if (event.target.name === 'amount') {
        this.Custom_Object__c.Amount__c = event.target.value;
    }
    if (event.target.name === 'size') {
        this.Custom_Object__c.Size__c = event.target.value;
    }
0

I would look at the datatable component documentation:

https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/example

Specifically the data table with row actions and the data table with inline edit examples.

Too much code to try to bring over but it should get you set up so that you can create tables with row based actions and shows how to add or remove items from a table.

Ultimately, what you want, is an array of objects to track the rows of your table. These rows will be basic JS objects with all the properties you will want access to when you go to create or delete the records at a later time.

You will want a second array to keep track of records that should be deleted. When selecting the delete action, the records should be moved from the upsert array into the delete array.

You will probably have a button somewhere that allows for adding new instances of these objects to create new records. When clicking the button an empty object should be added to your array which will then rerender your table with a new, blank row.

You will also have a save button somewhere. When clicked this save button will translate the data in the basic JS list into new records or updates to existing records. This will also fire the code to delete any records identified for deletion.

This documentation can teach you how to actually work with SF data, including creating or deleting records

| improve this answer | |
0

we have to capture the input in the same way

 
    <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" title="S.No">S.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="Account Industry">Account Industry</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Phone">Account Phone</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={accountRecList} for:item="account" for:index="index">

                <tr key={keyIndex}>
                    <td>{index}</td>
                    <td>
                        <lightning-input name='accName' access-key={index} id={index} type='text' onchange={changeHandler}  value={account.Name}>
                        </lightning-input>
                    </td>
                    <td>
                        <lightning-input name='accIndustry' access-key={index} id={index} type='text' onchange={changeHandler}   value={account.Industry}>
                        </lightning-input>
                    </td>
                    <td>
                        <lightning-input name='accPhone' access-key={index} type='Phone' id={index}  onchange={changeHandler} value={account.Phone}></lightning-input>
                    </td>
                    <td>
                        <lightning-icon icon-name="action:delete"  access-key={index} id={index} alternative-text="Click to Call" size="small" title="large size" onclick={removeRow}>
                        </lightning-icon>
                        <!--lightning-button
                                variant="base"                                       
                                icon-name="utility:close"
                                class="slds-m-left_x-small"
                                id={index}
                                onclick={removeRow}></lightning-button-->

                    </td>
                </tr>

            </template>
        </tbody>
    </table>      

Javascript Code:

import { LightningElement,track,api} from 'lwc';
import saveAccounts from '@salesforce/apex/AccountCreationController.createAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class MultipleRowInsertion extends LightningElement {
    @track keyIndex = 0;  
    @track error;
    @track message;
    @track accountRecList = [
        {                      
            Name: '',
            Industry: '',
            Phone: ''
        }
    ];
    //Add Row 
    addRow() {
        this.keyIndex+1;   
        this.accountRecList.push ({            
            Name: '',
            Industry: '',
            Phone: ''
        });
        console.log('Enter ',this.accountRecList);
        console.log('Enter ',this.accountRecList);
    }
    changeHandler(event){       
       // alert(event.target.id.split('-'));
        console.log('Access key2:'+event.target.accessKey);
        console.log('id:'+event.target.id);
        console.log('value:'+event.target.value);       
        if(event.target.name==='accName')
            this.accountRecList[event.target.accessKey].Name = event.target.value;
        else if(event.target.name==='accIndustry'){
            this.accountRecList[event.target.accessKey].Industry = event.target.value;
        }
        else if(event.target.name==='accPhone'){
            this.accountRecList[event.target.accessKey].Phone = event.target.value;
        }
    }
    //Save Accounts
     saveMultipleAccounts() {

        console.log("accountlist"+JSON.stringify(this.accountRecList));
        saveAccounts({ accountList : this.accountRecList })
            .then(result => {
                this.message = result;
                this.error = undefined;                
                this.accountRecList.forEach(function(item){                   
                    item.Name='';
                    item.Industry='';
                    item.Phone='';                   
                });

                //this.accountRecList = [];
                if(this.message !== undefined) {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Accounts Created!',
                            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 records',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log("error", JSON.stringify(this.error));
            });
    }
    removeRow(event){       
        console.log('Access key2:'+event.target.accessKey);
        console.log(event.target.id.split('-')[0]);
        if(this.accountRecList.length>=1){             
             this.accountRecList.splice(event.target.accessKey,1);
             this.keyIndex-1;
        }
    }  

}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.