Magento 2.4 get value of Dynamic Rows for Ajax [closed]
-
15-04-2021 - |
Question
I've got a form that uses ajax to submit data. I recently added a dynamicRows component to the form and using ajax doesn't appear to be as straight forward.
What I was using (on Non DynamicRows input)
let weight = $('input[name="registration_fieldset[weight]"]').val();//single input from Ui form
let url = registrationUrl;
jQuery.ajax({
url: url,
type: "POST",
data: {weight:weight},
showLoader: true,
cache: false,
success: function(response){
console.log(response.output);
},
error: function (response) {
console.log(response.output);
}
});
Getting the value of the DynamicRows element is not the same as a standard input such as:
$('input[name="registration_fieldset[attributes]"]').val();
How can I get the data from the DynamicRows element, in array/json format, with Javascript?
-- Update -- I've managed to get the data in the required format. The problem now is loading data retrieved from ajax into dynamic rows.
Solution
I've managed to solve this using a custom jquery widget.
getDynamicRowsData: function () {
let self = this;
//rows is the table used to store the dynamic rows.
//data-index = the name of the dynamicRows element in the ui_components xml (<dynamicRows name="attributes" >)
let rows = $("table[data-index='attributes']").find("tr");
let data = [];
rows.each(function(k, v){
//input names
let attrName = $("select[name='registration_fieldset[attributes][attributes][" + k + "][attribute_name]']").val();
let attrVal = $("input[name='registration_fieldset[attributes][attributes][" + k + "][attribute_value]']").val();
if (attrName && attrVal) {
data.push(self.rowToObject(attrName, attrVal, k));
data.push(self.rowToObject(attrName, attrVal, k));
}
});
return data;
},
rowToObject: function (key, value, recordId) {
//format so data displays correctly when loaded in the future
const row = {};
row.record_id = recordId;
row.attribute_name = key;
row.attribute_value = value;
row['initialize'] = 'true';
return row;
},
OTHER TIPS
You should try like this:
$('input[name="registration_fieldset[attributes]"]').on('click', function() {
//or try on("change", func...)
// you may have to target the element that's being changed on "click/input" so that you can get the value
// and then call other (ajax) functions
console.log($(this).val());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange