You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ODOO V14中如何通过JS重写_onSave函数控制sale.order保存逻辑

Sale.order 表单保存自定义校验方案

以下是Odoo环境下针对该需求的实现步骤:

1. 编写自定义JS校验逻辑

在你的自定义模块的static/src/js/目录下新建sale_order_quantity_check.js文件,写入如下代码:

odoo.define('your_module_name.sale_order_quantity_check', function (require) {
    "use strict";
    const FormController = require('web.FormController');
    const Dialog = require('web.Dialog');

    FormController.include({
        async saveRecord(options) {
            // 仅对sale.order模型的表单生效
            if (this.modelName === 'sale.order') {
                const currentRecord = this.model.get(this.handle, {raw: true});
                // 替换为你模型中两个字段的实际技术名称
                const totalQuantity = currentRecord.data.x_total_quantity || 0;
                const consumeQuantity = currentRecord.data.x_consume_quantity || 0;

                if (totalQuantity !== consumeQuantity) {
                    // 抛出错误提示
                    Dialog.alert(this, '保存失败:总数量与消耗数量必须相等,请调整后重试', {
                        title: '数据校验不通过'
                    });
                    // 阻止后续保存流程
                    return Promise.reject();
                }
            }
            // 校验通过执行原生保存逻辑
            return this._super(...arguments);
        }
    });
});

2. 注册JS资源到后端资产

在模块的views/目录下新建assets.xml文件,添加如下配置引入自定义JS:

<odoo>
    <template id="assets_backend_inherit" inherit_id="web.assets_backend">
        <xpath expr="." position="inside">
            <script type="text/javascript" src="/your_module_name/static/src/js/sale_order_quantity_check.js"/>
        </xpath>
    </template>
</odoo>

随后在模块的__manifest__.py的data列表中添加views/assets.xml,确保资源文件被系统加载。

3. 生效&适配注意事项

  • 将所有代码中的your_module_name替换为你自己的自定义模块的技术名称
  • 代码中的x_total_quantity、x_consume_quantity需要替换为你在sale.order模型中定义的两个字段的实际技术名称
  • 该方案适配Odoo 14及以上版本,低版本可调整FormController的引入路径适配
  • 代码修改完成后升级对应自定义模块,刷新浏览器后台即可生效
  • 若要防止接口调用、后端脚本操作绕过校验,建议同时在Python层的sale.order模型中添加@api.constrains约束做双层校验

内容的提问来源于stack exchange,提问作者Dheeraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 02:45:06