为何在Odoo14正常运行的JS监听器无法在Odoo12中生效?
Odoo12中商品宽高校验JS代码无法运行的原因
以下代码在Odoo14商城商品详情页可实现宽高输入校验功能:用户输入宽高数值后,系统会将其与后台商品设置的宽高范围对比,若输入值超出范围则弹出错误提示,要求输入正确数值,但该代码在Odoo12中无法正常运行,核心原因在于Odoo12与Odoo14的前端组件机制存在显著差异,具体如下:
odoo.define('product_dimensions.website_sale', function (require) { "use strict"; var core = require('web.core'); var _t = core._t; var ajax = require('web.ajax'); var publicWidget = require('web.public.widget'); publicWidget.registry.ProductDimensions = publicWidget.Widget.extend({ selector: '.oe_website_sale', events: { 'change input[name="wide"]': '_onWidthChange', 'change input[name="high"]': '_onHeightChange', }, start: function () { this.product_id = this.$el.find('#product_id').val(); // Assuming '#product_id' is an input field that holds the product id return this._super.apply(this, arguments); }, _onWidthChange: function () { var wide = parseFloat($('input[name="wide"]').val()); console.log(this.product_id) ajax.jsonRpc("/shop/product/min_dimensions", 'call', {'product_id': this.product_id}).then(function (data) { if (wide < data.wide_mini) { alert(_t('The number you entered is less than the minimum width:')+ data.wide_mini); } else if (wide > data.wide_max) { alert(_t('The number you entered is greater than the maximum width:')+ data.wide_max); } }); }, _onHeightChange: function () { var high = parseFloat($('input[name="high"]').val()); ajax.jsonRpc("/shop/product/min_dimensions", 'call', {'product_id': this.product_id}).then(function (data) { if (high < data.high_mini) { alert(_t('The number you entered is less than the minimum height:')+ data.high_mini); } else if (high > data.high_max) { alert(_t('The number you entered is greater than the maximum height:')+ data.high_max); } }); }, }); return publicWidget.registry.ProductDimensions; });
前端公共组件模块缺失:Odoo13及后续版本引入了
web.public.widget模块用于统一管理前端公共组件,但Odoo12中不存在该模块,代码中require('web.public.widget')会直接抛出加载错误,导致整个组件无法初始化。组件注册机制不兼容:Odoo14通过
publicWidget.registry注册前端组件,而Odoo12没有这一注册体系,通常需通过core.action_registry.add或挂载到website模块的现有组件中,直接使用publicWidget.registry会导致组件无法被系统识别和触发。Widget继承体系差异:Odoo12中的前端Widget继承基础为
web.Widget或website.content.frontend,而非Odoo14的publicWidget.Widget,继承错误会导致start等生命周期方法无法正常执行,进而无法获取product_id等关键数据,校验逻辑也就无法运行。
内容的提问来源于stack exchange,提问作者Simon Liu
相关产品推荐
相关产品推荐

