首页 > 解决方案 > 如何在创建函数中使用 odoo 的服务器端 onchange 方法?

问题描述

例如,如果我想触发这个功能:

@api.onchange("fieldA")
def _onchange(self):
   for rec in self:
        random = rec.fieldB

onchange 函数通常采用以下形式:onchange(values, field_name, field_onchange)

子问题 1:我要求 fieldB 已经可用。我是否将其传递给“值”参数?
子问题2:回答者能否提供适当的代码示例?


参考文献中给出的常见示例通常采用以下形式:

wizard = self.env['library.return.wizard']
values = {'borrower_id': self.env.user.partner_id.id}
specs = wizard._onchange_spec()
updates = wizard.onchange(values, ['borrower_id'], specs)
....
....
wiz = wizard.create(values)

但这在我的情况下不起作用..

谢谢您的帮助!

标签: odooodoo-8

解决方案


终于想通了。有一些隐藏的陷阱:

  1. self.onchange 实际上调用了@api.depends 和@api.onchange 修饰函数
  2. values dict(self.onchange 的第一个参数)实际上有 2 种用途:检查下面的代码
  3. (观察)self.onchange返回值dict,不包括未被通过self.onchange调用的函数修改的字段

您可以参考下面我的代码注释以获取更多详细信息。希望这可以帮助某人。

 @api.model
    def create(self, vals):
        # SECTION: Trigger server-side onchange to initialize all child dependent values of qty_to_ship. More generally, to trigger all @api.onchange functions in this shipment.item model.
        
        stock_move = self.env['stock.move'].browse([vals['move_id']])
        # 'values' dict: (1) provide values of fields when used in calling onchange functions (2) indicate fields that we want a return value for after calling onchange
        # Note: some key-values are commented because related fields of move_id will be computed when we call self.onchange
        values = {
            # 'product_id': stock_move.product_id.id,
            # 'product_tmpl_id': stock_move.product_id.product_tmpl_id.id,
            'move_id': stock_move.id,
            'qty_to_ship': stock_move.product_uom_qty,
            'carton_qty': 0,
            'item_sub_total': 0,
        }
        specs = self._onchange_spec()
        # Note: self.onchange, triggers both @api.depends, @api.onchange decorated functions (this is not mentioned in any documentation)
        # Note: the order of the list (2nd arg) matters
        # move_id needed to: trigger def _assign_relational_fields
        # product_tmpl_id needed to: trigger def _compute_carton_single
        # qty_to_ship needed to: trigger other functions with @api.onchange('qty_to_ship') decorator
        updates = self.onchange(values, ['move_id', 'product_tmpl_id', 'qty_to_ship'], specs)
        value = updates.get('value', {}) 
        for name, val in value.items(): 
            if isinstance(val, tuple): 
                value[name] = val[0]
        vals.update(value)
        # insert qty_to_ship as it is not modified by any of the onchange functions triggered earlier. Hence it will not be attached to 'value' dict
        vals.update({'qty_to_ship': stock_move.product_uom_qty})

        # Continue with super create
        res = super(ACDShipmentItems, self).create(vals)

        return res

推荐阅读