Search code examples
pythonodoopython-3.8

How to create a dynamic selection field in Odoo?


I was trying to create a dynamic selection field based on conditions

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')]

This would work this way? It is not working as of now. Any suggestion would be of great help!!


Solution

  • _product_customer_uom_change is called before current record is loaded, so you cannot use current record to calculate selection field.

    You could use context (but active_id still won't be available) and pass some information from the previous view, e.g.:

    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')]
    

    If you're not able to this, you should use many2one field (with widget="selection" or create=False) with domain in a view.

    (answer written based on experience with Odoo 10)