
本文详解如何将自定义用户字段(如 hide_product_information)安全、可靠地传递至 Odoo 18 的 POS 前端,并在 ProductScreen 等组件中通过 JavaScript 直接访问,无需修改 pos.session 的 _load_pos_data 方法。
本文详解如何将自定义用户字段(如 hide_product_information)安全、可靠地传递至 odoo 18 的 pos 前端,并在 productscreen 等组件中通过 javascript 直接访问,无需修改 pos.session 的 _load_pos_data 方法。
在 Odoo 18 中,POS 前端的数据加载机制已重构为基于「数据模型分层加载」(_load_pos_data + load_pos_data_fields),其核心原则是:会话级配置应由 pos.config 和关联的 res.users 实例承载,而非直接挂载到 pos.session 对象上。因此,将用户偏好字段(如布尔型 hide_product_information)注入前端的正确路径是扩展 res.users 模型的数据加载逻辑。
✅ 正确实现步骤
1. 在 Python 端声明字段并注册前端可加载字段
在自定义模块中继承 res.users,添加字段,并重写 _load_pos_data_fields 方法,显式声明该字段需随 POS 启动时一并加载:
from odoo import models, fields, api
class ResUsers(models.Model):
_inherit = 'res.users'
hide_product_information = fields.Boolean(
string="Hide Product Information in POS",
default=False,
help="If enabled, product details (e.g., description, barcode) will be hidden on the POS product screen."
)
@api.model
def _load_pos_data_fields(self, config_id):
# 继承父类字段列表,并追加自定义字段
res = super()._load_pos_data_fields(config_id)
res += ['hide_product_information']
return res
⚠️ 注意:无需修改
pos.session的_load_pos_data—— 因为current_user_id是pos.config的关联记录,而pos.config在前端通过this.pos.config可直接访问;其current_user_id属性即为当前登录用户的完整数据(含你注册的字段)。
2. 在 JavaScript 端安全读取字段值
在 ProductScreen 的补丁中,可直接通过 this.pos.config.current_user_id.hide_product_information 获取值。例如:
/** @odoo-module */
import { patch } from '@web/core/utils/patch';
import { ProductScreen } from '@point_of_sale/app/screens/product_screen/product_screen';
patch(ProductScreen.prototype, {
async onProductInfoClick(product) {
// ✅ 安全访问用户配置
const shouldHide = this.pos.config.current_user_id?.hide_product_information || false;
if (shouldHide) {
this.showPopup('ErrorPopup', {
title: 'Information Hidden',
body: 'Product details are disabled for your user account.',
});
return;
}
// 继续执行原逻辑(如打开产品详情弹窗)
await this._super(...arguments);
},
});
? 提示:使用可选链操作符
?.防止因数据未加载完成导致的 JS 报错;|| false提供默认回退值,增强健壮性。
3. 部署与验证
- 升级模块并重启 Odoo 服务(确保
.py文件被重新加载); - 清除浏览器缓存或使用无痕窗口访问 POS;
- 在后台为测试用户勾选
hide_product_information,进入 POS → 点击任意商品信息图标,验证逻辑是否生效。
? 总结
Odoo 18 的 POS 数据流设计强调“按需加载”与“模型职责分离”。用户个性化配置属于 res.users 的范畴,应通过 _load_pos_data_fields 注册字段,而非侵入 pos.session。这种方式不仅符合官方架构规范,还能确保数据在多会话、多用户场景下准确隔离,避免状态污染。后续如需扩展其他用户级开关(如 show_tax_in_receipt、default_quantity_unit),均遵循同一模式,简洁且可维护。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











