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

Odoo技术问询:扩展res.user与pos.category表单及添加智能按钮

1. 扩展res.user模型,关联用户创建的POS分类

要实现用户与自己创建的POS分类关联,我们需要同时扩展pos.category和res.user两个模型:

首先给POS分类添加创建者字段,再在用户模型中建立反向关联:

from odoo import models, fields

class PosCategory(models.Model):
    _inherit = 'pos.category'

    # 记录创建该分类的用户,默认值设为当前登录用户,且只读
    created_by_id = fields.Many2one('res.user', string='Created By', 
                                  default=lambda self: self.env.user, readonly=True)

class ResUser(models.Model):
    _inherit = 'res.user'

    # 反向关联用户创建的所有POS分类
    created_pos_category_ids = fields.One2many('pos.category', 'created_by_id', 
                                             string='Created POS Categories')

这样配置后,每个POS分类会自动记录创建者,用户也能在自己的表单页面查看所有自己创建的分类。


2. 用XPath在POS分类表单顶部添加智能按钮

你已经有了视图继承的基础框架,接下来只需要定位到表单的顶部区域,插入智能按钮即可。通常Odoo表单的顶部按钮会放在button_box容器里,完整代码如下:

<record id="view_pos_category_inherited_form" model="ir.ui.view"> 
  <field name="name">view.pos.category.inherited.form</field> 
  <field name="model">pos.category</field> 
  <field name="inherit_id" ref="point_of_sale.product_pos_category_form_view" /> 
  <field name="arch" type="xml"> 
    <!-- 定位到表单的sheet区域,在内部添加按钮容器 -->
    <xpath expr="//sheet" position="inside">
      <!-- 新增button_box容器,用于放置顶部智能按钮 -->
      <button_box position="inside">
        <!-- 跳转到该分类创建者的用户表单 -->
        <button
          name="%(base.res_users_form_view)d"
          type="action"
          context="{'active_id': created_by_id}"
          string="Created By"
          icon="fa-user"
          attrs="{'invisible': [('created_by_id', '=', False)]}"
        />
        <!-- 打开当前用户创建的所有POS分类列表 -->
        <button
          name="%(point_of_sale.product_pos_category_tree_view)d"
          type="action"
          context="{'search_default_created_by_id': active_id}"
          string="My Created Categories"
          icon="fa-list"
        />
      </button_box>
    </xpath>
  </field> 
</record>

关键说明:

  • 如果原视图已经存在button_box,可以直接用<xpath expr="//sheet/button_box" position="inside">定位,按钮会追加到现有按钮之后。
  • attrs属性用于控制按钮显示逻辑:当分类没有记录创建者时,按钮自动隐藏。
  • 视图ID使用%(模块名.视图ID)d的格式,确保跨模块引用的正确性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:34:20