this is the client script i am working i am fetching my mrp from item doctype when i am adding a new row the custom_mrp is getting fetched but after that whne again i am adding new row below that the first select option is getting autopopulated and 1 more issue is there that the in editing row custom_mrp is also not getting fetched
frappe.ui.form.on(‘Purchase Order’, {
refresh: function (frm) {
if (frm.doc.items && frm.doc.items.length) {
console.log(Found ${frm.doc.items.length} items to process
);
frm.doc.items.forEach((item, index) => {
console.log(Processing item ${index + 1}: ${item.item_code}
);
if (item.item_code) {
updateMRPOptionsForItem(frm, item.doctype, item.name, item.item_code);
}
});
}
}
});
frappe.ui.form.on(‘Purchase Order Item’, {
item_code: function (frm, cdt, cdn) {
console.log(“Item code changed:”, cdn);
let item = locals[cdt][cdn];
if (item && item.item_code) {
console.log(Updating MRP for item: ${item.item_code}
);
updateMRPOptionsForItem(frm, cdt, cdn, item.item_code);
}
},
// Add this new method to reset MRP when a new row is added
before_items_add: function(frm, cdt, cdn) {
let field = frappe.meta.get_docfield("Purchase Order Item", "custom_mrp");
if (field) {
field.options = '';
}
}
});
function updateMRPOptionsForItem(frm, doctype, rowName, itemCode) {
console.log(Fetching MRP options for: ${itemCode}
);
if (!itemCode) {
console.log(“No item code provided, returning”);
return;
}
frappe.db.get_doc('Item', itemCode)
.then(doc => {
let mrpOptions = ['']; // Start with an empty option
if (doc && doc.custom_mrp_ && Array.isArray(doc.custom_mrp_)) {
mrpOptions = mrpOptions.concat(doc.custom_mrp_.map(mrpRow => `${mrpRow.mrp}`));
console.log("MRP options found:", mrpOptions);
} else {
console.log("No MRP options found.");
}
let field = frappe.meta.get_docfield("Purchase Order Item", "custom_mrp");
if (field) {
field.options = mrpOptions.join("\n");
}
let row = frm.fields_dict.items.grid.grid_rows_by_docname[rowName];
if (row) {
row.refresh();
}
frm.refresh_field("items");
})
.catch(err => {
console.error("Error fetching MRP options:", err);
frappe.show_alert({
message: `Failed to fetch MRP options for ${itemCode}`,
indicator: 'red'
});
});
}