qooboy
1
代码如下:
const formValues = await ctx.getVar(‘ctx.formValues’);
const details = formValues?.order_details || ;
const totalAmount = details.reduce((sum, item) => {
const quantity = Number(item?.quantity) || 0;
const price = Number(item?.code?.price) || 0;
return sum + (quantity * price);
}, 0);
return totalAmount;
只能返回金额和,而不能返回每行的金额,请帮忙看看如何解决?
qooboy
3
// 终极解决方案:强制重新计算所有行
// 注意:这会在每次触发时计算所有行,但只返回当前相关的值
const recalculateAmount = () => {
const formValues = ctx.form?.getFieldsValue(true);
if (!formValues?.order_details || !Array.isArray(formValues.order_details)) {
return 0;
}
// 在实际运行时,我们需要确定当前行
// 由于技术限制,我们假设当前正在编辑的行是最后一个有数据的行
let targetRow = null;
// 从后往前找,找到第一个有quantity或price的行
for (let i = formValues.order_details.length - 1; i >= 0; i–) {
const row = formValues.order_details[i];
if (row.quantity !== undefined || row.price !== undefined) {
targetRow = row;
break;
}
}
// 如果没找到,使用第一行
targetRow = targetRow || formValues.order_details[0];
if (targetRow) {
const quantity = parseFloat(targetRow.quantity) || 0;
const price = parseFloat(targetRow.price) || 0;
return Math.round((quantity * price) * 100) / 100;
}
return 0;
};
return recalculateAmount();
用NocoBase的AI编写的,试了很多方法,要么为0,要么是把结果写到所有的行内金额字段值,并不能进行单行的计算!
// 为子表格每一行的合计字段 (f_wivp0iqzmxj) 设置值 = 数量 × 单价
const subTableRows = ctx.form.getFieldValue(‘f_tomore_id’) || ;
if (!Array.isArray(subTableRows)) {
return;
}
// 使用 setFieldValue 确保每个字段都被正确设置
subTableRows.forEach((row, index) => {
const quantity = (typeof row?.f_vwcbbcstrun === ‘number’ && !isNaN(row.f_vwcbbcstrun)) ? row.f_vwcbbcstrun : 0;
const unitPrice = (typeof row?.f_avwweicsgbk === ‘number’ && !isNaN(row.f_avwweicsgbk)) ? row.f_avwweicsgbk : 0;
const total = quantity * unitPrice;
// console.log(‘【调试】获取到的数量:’, quantity, ‘类型:’, typeof quantity);
// console.log(‘【调试】获取到的单价:’, unitPrice, ‘类型:’, typeof unitPrice);
// 直接设置合计字段
if (ctx.form.setFieldValue) {
ctx.form.setFieldValue([‘f_tomore_id’, index, ‘f_wivp0iqzmxj’], total);
}
});
提供参考