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

如何在Odoo 16中用JavaScript监听字段onChange事件?(代码尝试无效)

Odoo 16 字段 onChange 事件监听实现方案

问题分析

你当前代码里的_onFieldChanged并非Odoo 16 FieldChar组件的标准钩子方法,不会被自动触发,所以监听无效。以下是两种可行的实现方式:

方式一:监听输入框实时变化(编辑模式)

重写_renderEdit方法,为输入框绑定input或change事件,实现实时输入监听:

odoo.define('my_module.on_field_changes', function (require) {
"use strict";

const fieldRegistry = require('web.field_registry');
const { FieldChar } = require('web.basic_fields');

const OnChangeWidget = FieldChar.extend({
    // 重写编辑模式渲染逻辑,绑定输入事件
    _renderEdit: function () {
        this._super.apply(this, arguments);
        // 绑定input事件(实时监听每一次输入)
        this.$el.find('input').on('input', (ev) => {
            console.log('字段实时变化:', ev.target.value);
            // 如需将输入同步到模型字段,可调用:
            // this._setValue(ev.target.value);
        });
    },

    // 组件销毁时解绑事件,避免内存泄漏
    destroy: function () {
        this.$el.find('input').off('input');
        this._super.apply(this, arguments);
    },
});

fieldRegistry.add('onchange_widget', OnChangeWidget);
});

方式二:监听字段值全局变更事件

通过监听Odoo内置的field_change事件,无论字段值是用户输入还是其他方式修改,都会触发回调:

odoo.define('my_module.on_field_changes', function (require) {
"use strict";

const fieldRegistry = require('web.field_registry');
const { FieldChar } = require('web.basic_fields');

const OnChangeWidget = FieldChar.extend({
    start: function () {
        this._super.apply(this, arguments);
        // 监听字段值变更事件
        this.on('field_change', this, (ev) => {
            // 仅响应当前字段的变更
            if (ev.data.field === this.name) {
                console.log('字段值变更:', ev.data.value);
            }
        });
    },
});

fieldRegistry.add('onchange_widget', OnChangeWidget);
});

注意事项

  • 确认father_name字段为Char类型,若为其他类型(如Text、Boolean),需继承对应字段组件(如FieldText、FieldBoolean)
  • 模块安装/更新后,强制刷新浏览器页面(Ctrl+F5) 清除静态资源缓存
  • 表单视图和manifest.py的配置无需修改,保持现有设置即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:27:33