How to create dynamic selection field base on condition?

I'm learning to develop something with ODOO 11CE. I'd like to filling the "filelds.Selection" with the condition.

So for example: If I change the stage of CRM lead the x_status select field will also change.

Here is my tried, But I does not working.

class MYLead(models.Model): _inherit = ['crm.lead']

def _get_status_list(self):
    vals = []
    for rec in self:
        #New
        if rec.stage_id == 1:
            vals.extend([('0', 'Pending'), ('1', 'Ready')])
        #Qualified 
        elif rec.stage_id == 2:
            vals.extend([('0', 'Pending'), ('1', 'Waiting])
        #Proposition    
        elif rec.stage_id == 3:    
        else:
            vals.extend([('0', 'Processing'), ('1', 'Approve'), ('2', 'Pending'), ('-1', 'Reject')])
    return vals             

x_status = fields.Selection(selection=_get_status_list, string='Status')

Upvotes: 2

Views: 2190

Answers (2)

kerbrose
kerbrose

Reputation: 1185

This can approached by 3 patterns. they are all used in Odoo code. what makes your code to not work. is that your method definition is in class so it doesn't get called. so to fix it your method must be outside the class definition. your code has to be something like

def _get_status_list(self):
    vals = []
    for rec in self:
        #New
        if rec.stage_id == 1:
            vals.extend([('0', 'Pending'), ('1', 'Ready')])
        #Qualified 
        elif rec.stage_id == 2:
            vals.extend([('0', 'Pending'), ('1', 'Waiting])
        #Proposition    
        elif rec.stage_id == 3:    
        else:
            vals.extend([('0', 'Processing'), ('1', 'Approve'), ('2', 'Pending'), ('-1', 'Reject')])
    return vals


class ModelName(models.Model):
    _name = 'model.name'

    x_status = fields.Selection(selection=_get_status_list, string='Status')

another example

def _get_purchase_order_states(self):
    return self.env['purchase.order']._fields['state'].selection

class PurchaseReport(models.Model):
    _name = 'purchase.report'

    state = fields.Selection(_get_purchase_order_states, string='Order States')

to know about the other 2 patterns you could check the following: https://dev.to/kerbrose/dynamic-selection-list-in-odoo-for-selection-fields-16h8

Upvotes: 0

gdaramouskas
gdaramouskas

Reputation: 3747

Thats because self is empty, so it does not loop at all.

The selection attribute is filled when the module is updated and not on record creation. It is executed only once.

You cannot dynamically fill the Selection's elements you have to do it in a static way. eg.

def _get_status_list(self):
    return [(1, 'option1'), ('2', 'option2')]

x_status = fields.Selection(selection=_get_status_list, string='Status')

Upvotes: 1

Related Questions