Note: I am not exactly sure what needs to happen if the user has 2 rows with 2 different sets of values when they click on the add new row button. But I will assume that you want to copy the last row and if you need to you can modify the code below to tailor it to your needs.
Also, I couldn't set up a LWC playground because lightning-record-edit-form
doesn't seem to be supported there. Take the code below with a grain of salt and let me know if something is not working so I can test in my sandbox later.
What you need to do is set the value
for the lightning inputFields
.
Let's take the first field as an example:
<template for:each={itemList} for:item="item" for:index="index">
<lightning-record-edit-form key={item.id} object-api-name="Contact">
<lightning-messages> </lightning-messages>
<lightning-layout multiple-rows>
<lightning-layout-item size="12" small-device-size="6" medium-device-size="4" large-device-size="2"
padding="around-small">
<lightning-input-field field-name="FirstName" variant="label-stacked" required>
</lightning-input-field>
What you should do is add a value
property to the inputField like so:
<lightning-input-field field-name="FirstName" variant="label-stacked" required value={item.firstName}>
Next you need to make some changes on the JS side as well:
@track itemList = [
{
id: 0,
firstName: ''
}
];
addRow() {
let firstNameInputs = this.template.querySelectorAll('lightning-input-field');
const firstNameValue = firstNameInputs[firstNameInputs.length-1].value;
++this.keyIndex;
var newItem = [{ id: this.keyIndex, firstName: firstNameValue}];
this.itemList = this.itemList.concat(newItem);
}
Similarly you can work your code to set the other values that you need it to.
Now when the new is added JS will check if there's a firstName
value for each item from the itemList
and if there is one it will prepopulate the firstName
field for that row.