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

Odoo 15如何限制Order lines行数至2行并隐藏添加按钮

解决Odoo订单行数量限制及按钮自动隐藏问题

要实现订单行最多2个产品,且实时隐藏添加按钮,得从前端视图控制和后端验证兜底两方面入手——光用@api.constrains肯定不够,因为它只在保存时触发。

一、前端实时控制按钮显隐

在订单的表单视图里,通过JavaScript监听订单行的变化,实时判断行数,当行数≥2时自动隐藏对应的添加按钮。

找到订单视图的XML代码,添加如下脚本:

<field name="order_line" widget="one2many_list">
    <tree editable="bottom">
        <!-- 这里保留你原有的订单行字段配置 -->
    </tree>
</field>

<script type="text/javascript">
    $(document).ready(function() {
        // 核心检查函数:判断行数并控制按钮显隐
        function toggleAddButtons() {
            const lineCount = $('.o_field_one2many_list tbody tr.o_data_row').length;
            const targetButtons = $('.o_form_button_add').filter(function() {
                const btnText = $(this).text();
                return btnText.includes('Add a Product') || 
                       btnText.includes('Add a section') || 
                       btnText.includes('Add a note');
            });
            lineCount >= 2 ? targetButtons.hide() : targetButtons.show();
        }

        // 页面加载时先执行一次检查
        toggleAddButtons();

        // 监听添加按钮点击(延迟执行确保行已渲染)
        $(document).on('click', '.o_form_button_add', () => setTimeout(toggleAddButtons, 500));

        // 监听删除按钮点击
        $(document).on('click', '.o_list_button_remove', toggleAddButtons);
    });
</script>

注:如果你的系统是中文界面,记得把includes里的文本改成对应中文,比如“添加产品”“添加章节”“添加备注”。

二、后端验证兜底

防止用户通过导入、API等绕过前端的方式添加超过2行订单,在订单模型里添加验证逻辑:

from odoo import models, api, exceptions

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    @api.constrains('order_line')
    def _check_max_order_lines(self):
        for order in self:
            if len(order.order_line) > 2:
                raise exceptions.ValidationError("订单行最多只能添加2个产品!")

    # 可选:在创建和写入时提前拦截,避免无效操作
    @api.model
    def create(self, vals):
        order = super().create(vals)
        if len(order.order_line) > 2:
            raise exceptions.ValidationError("订单行最多只能添加2个产品!")
        return order

    def write(self, vals):
        res = super().write(vals)
        for order in self:
            if len(order.order_line) > 2:
                raise exceptions.ValidationError("订单行最多只能添加2个产品!")
        return res

这样前端实时控制按钮显隐,后端确保数据合法性,就能完全满足你的需求了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:50:39