How do I create a dynamic amount of new rows with certain fields that differ within a for loop?
How do I create a dynamic amount of new rows with certain fields that differ within a for loop?
Hi all,
I'm working on an Editor form that allows the user to enter information on a single form that creates a dynamic amount of new rows dependent on a specific pair of fields in the form - I've attached an image for reference. The form has an add more button, which allows the user to enter multiple amounts and subdepartment values
Depending on how many amount and subdepartment pairs have been filled out, I would like to create that many new rows where each row has the same information in it except the amount and subdepartment fields.
The code below is executed when the create button on the form is clicked.
I think I've gotten relatively close to achieving this a few times. I know the correct data is there, it's just the process for actually creating the new rows I'm struggling with. I've referenced these questions, which helped point me in the right direction, but wasn't enough for me to get my desired output:
https://datatables.net/forums/discussion/comment/147795/#Comment_147795
https://datatables.net/forums/discussion/36504/editor-bulk-row-creation-based-on-single-editor-form
Thank you!
{
text: 'Create', action: function ( e, dt, node, config ) {
// Gather data from filled out Editor form and store in array.
var data = [];
data = Object.values(editor.val());
// Loop through specific fields in data array to create purchaseAmounts array
// with data that will be different between each new row created.
var temp = {};
var purchaseAmounts = [];
for (i = 3; i < 23; i += 2) {
if (data[i]) {
temp.purchaseamount = data[i];
temp.subdepartmentID = data[i + 1];
purchaseAmounts.push(temp);
temp = {};
}
}
// Create dynamic amount of rows based on how many purchase amounts and
// subdepartment fields were filled out.
editor.create(purchaseAmounts.length, false);
// Loop to create new rows with 2 fields that will differ between each record.
for (i = 0; i < purchaseAmounts.length; i++) {
editor.field('Purchases.purchaseamount')
.multiSet(i, purchaseAmounts[i].purchaseamount);
editor.field('Purchases.subdepartmentID')
.multiSet(i, purchaseAmounts[i].subdepartmentID);
}
// Submit the form.
editor.submit();
}
}
This question has an accepted answers - jump to answer
Answers
This thread should help, it's asking the same thing - see the example in my post.
Cheers,
Colin
Thanks, Colin! I was able to repurpose that code according to my needs.