
本文详解如何将自定义字段 resource_name 从销售订单行同步至 POS 订单行,并确保其在打印小票时正确渲染,重点解决 JS 层字段未初始化导致显示为 undefined 的常见问题。
本文详解如何将自定义字段 resource_name 从销售订单行同步至 pos 订单行,并确保其在打印小票时正确渲染,重点解决 js 层字段未初始化导致显示为 undefined 的常见问题。
在 Odoo 中为 sale.order.line 和 pos.order.line 添加同名字段 resource_name 后,即使数据库已正确写入、Python 层 _export_for_ui() 已返回该字段,前端小票仍显示为空或 undefined,根本原因在于 POS 的 JavaScript 模型(Orderline)在实例化时未从服务端传入的原始 JSON 数据中提取该字段。
✅ 正确的 JS 初始化方式
原代码中仅执行了 this.resource_name = this.resource_name || "";,但此时 this.resource_name 尚未被赋值(因构造函数未主动读取 options.json.resource_name),故始终取默认空字符串,无法反映真实数据。
应改为:
odoo.define('pos_invoice_ksa.model', function (require) {
'use strict';
var pos_model = require("point_of_sale.models");
var SuperOrderLine = pos_model.Orderline.prototype;
// 确保后端字段被加载
pos_model.load_fields("pos.order.line", ["resource_name"]);
pos_model.Orderline = pos_model.Orderline.extend({
initialize: function (attr, options) {
SuperOrderLine.initialize.call(this, attr, options);
// ✅ 关键修复:从 options.json 中读取原始数据
this.resource_name = options.json.resource_name || "";
},
export_for_printing: function () {
var json = SuperOrderLine.export_for_printing.call(this);
json.resource_name = this.resource_name;
return json;
},
});
});⚠️ 注意:
options.json是 POS 加载订单行时由_export_for_ui()返回的原始对象,是唯一可靠的数据源;直接访问this.resource_name在初始化阶段无效,因其尚未被赋值。
? 后端同步逻辑验证(推荐增强版)
你当前的 _order_line_fields() 实现存在潜在风险:vals['resource_name'] 被写入的位置可能被后续逻辑覆盖。建议显式确保字段传递:
def _order_line_fields(self, line, session_id=None):
result = super()._order_line_fields(line, session_id)
vals = result[2]
# 安全获取 sale.order.line 并同步 resource_name
sale_line_id = vals.get('sale_order_line_id')
if sale_line_id:
sale_line = self.env['sale.order.line'].browse(sale_line_id)
if sale_line.resource_name:
vals['resource_name'] = sale_line.resource_name
else:
vals['resource_name'] = False # 显式设为 False 避免 None 导致 JS 异常
return result
def _export_for_ui(self, orderline):
result = super()._export_for_ui(orderline)
# 始终携带字段,即使为空字符串
result['resource_name'] = orderline.resource_name or ""
return result? XML 小票模板(确认已正确继承)
确保你的 QWeb 模板中已启用字段加载并正确引用:
<!-- 在 receipt 渲染循环内 -->
<t t-foreach="orderlines" t-as="orderline" t-key="orderline.id">
<!-- 其他列 -->
<td style="text-align:right;">
<t t-esc="orderline.resource_name or ''"/>
</td>
</t>? 调试建议
- 在浏览器控制台检查
orderline对象:console.log(orderline);→ 确认resource_name是否存在于orderline实例属性中; - 查看 Network →
/pos/web响应中的orderlines数组,确认resource_name是否已包含在_export_for_ui返回的 JSON 中; - 若仍为空,请检查
sale_order_line_id是否有效、sale.order.line记录是否存在且resource_name非空。
通过以上三步(JS 初始化修正 + Python 同步加固 + XML 安全渲染),即可稳定、可靠地在 POS 小票中展示 resource_name 字段。

















