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

Odoo 15:覆盖FieldBinaryImage的_render函数移除错误通知

Odoo 15 移除FieldBinaryImage错误通知的正确扩展方法

问题原因分析

  • 使用extend时调试跳过var FieldBinaryImage:大概率是模块依赖或加载顺序错误,导致自定义代码在原组件加载前执行,无法获取到FieldBinaryImage对象。
  • 使用include时变量未定义:原_render函数中的$img、value是局部变量,扩展函数中无法直接引用,需在扩展的_render内部重新定义或通过this访问组件属性。

解决方案步骤

1. 配置自定义模块的资源加载

在自定义模块的manifest.py中,将扩展JS文件添加到后端资源列表,确保在原组件之后加载:

{
    # ... 其他manifest配置项
    'assets': {
        'web.assets_backend': [
            'your_module_name/static/src/js/field_binary_image_extend.js',
        ],
    },
}

2. 编写正确的扩展代码

创建your_module_name/static/src/js/field_binary_image_extend.js,使用include方法重写_render函数,移除错误通知逻辑:

odoo.define('your_module_name.FieldBinaryImageExtend', function (require) {
    "use strict";

    const basic_fields = require('web.basic_fields');
    const FieldBinaryImage = basic_fields.FieldBinaryImage;

    FieldBinaryImage.include({
        _render: function () {
            if (!this.value && !this.hasPlaceholder()) {
                this.$el.empty();
                return;
            }

            // 重新获取或创建img元素
            let $img = this.$('img');
            if (!$img.length) {
                $img = $('<img>', {class: 'o_field_binary_image'});
                this.$el.append($img);
            }

            const value = this.value;
            if (value) {
                const url = '/web/image?' + $.param({
                    model: this.model,
                    id: this.res_id,
                    field: this.name,
                    unique: value,
                });
                $img.attr('src', url);
                // 保留图片加载失败时显示占位图的逻辑,移除错误通知
                $img.on('error', () => {
                    $img.attr('src', '/web/static/src/img/placeholder.png');
                });
            } else {
                $img.attr('src', this._getPlaceholder());
            }
        },
    });

    return FieldBinaryImage;
});

3. 关键注意事项

  • 变量作用域:扩展函数中需在内部重新定义$img、value等变量,不能直接引用原函数的局部变量。
  • 加载顺序:确保自定义JS文件在web.basic_fields之后加载,通过manifest的assets_backend配置实现。
  • 错误逻辑处理:仅移除do_notify错误通知代码,保留占位图显示逻辑,避免影响用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:13:31