如何在 Odoo 中创建动态选择字段?

How to create a dynamic selection field in Odoo?

我试图创建一个基于条件的动态选择字段

x_material_orientation = fields.Selection(selection='_product_customer_uom_change',string='Material Orientation')

def _product_customer_uom_change(self):
        for rec in self:
            if rec.x_order_customer_uom.name == 'sht':
                return [('sheetfaceup','Sheets Face Up'),('sheetfacedown','Sheets Face Down')]
               
            elif rec.x_order_customer_uom.name == 'yds':
                return [('windfaceout','Wind Face Out'),('windfacein','Wind Face In')]

这样可以吗?它现在不工作。 任何建议都会有很大帮助!!

_product_customer_uom_change在加载当前记录之前调用,所以不能使用当前记录计算选择字段。

您可以使用上下文(但 active_id 仍然不可用)并传递先前视图中的一些信息,例如:

def _product_customer_uom_change(self):
    if self.env.context.get('order_type') == 'sht':
        return [('sheetfaceup','Sheets Face Up'),('sheetfacedown','Sheets Face Down')]
           
    elif self.env.context.get('order_type') == 'yds':
        return [('windfaceout','Wind Face Out'),('windfacein','Wind Face In')]

如果您无法做到这一点,您应该在视图中将 many2one 字段(widget="selection" 或 create=False)与域一起使用。

(根据使用 Odoo 10 的经验编写的答案)