user132
user132

Reputation: 33

Is it possible to change the value of a selection field dynamically in Odoo 10?

I would like to have my selections depend on the value of a Char field, for instance, a Char field defined as such:

my_char = fields.Char("Enter Something", readonly = False)

so I suppose the selection field should call a function, something like "_get_value"

my_selection = fields.Selection(selection = ' _get_value')
@api.model
def _get_value(self):
    my_list = [('key1','value1')]
    #no idea how to assign the value of my_char to value1
    return my_list

Eventually, I would like to have the selections in the drop down list vary as the user input different strings in my_char.
Is this achievable in Odoo? Because if it's not, I should better start reorganizing my structure. Thanks a lot.

Upvotes: 1

Views: 3897

Answers (2)

Nitin Kantak
Nitin Kantak

Reputation: 168

No need to write method here. Just declare the dictionary to a variable and call it in selection field.

VAR_LIST = [('a','ABC'),
            ('p','PQR'),
            ('x','XYZ')]

my_selection = fields.Selection(string="Field Name",VAR_LIST)

Upvotes: 0

CZoellner
CZoellner

Reputation: 14768

As far is i know, it isn't possible with field type Selection. But you can use a Many2one field for such a behaviour.

class MySelectionModel(model.Models):
    _name = "my.selection.model"

    name = fields.Char()

class MyModel(models.Model):
    _name = "my.model"

    my_char = fields.Char()
    my_selection_id = fields.Many2one(
        comodel_name="my.selection.model", string="My Selection")

    @api.onchange("my_char")
    def onchange_my_char(self):
        return {'domain': {'my_selection_id': [('name', 'ilike', self.my_char)]}}

Or without a onchange method:

    my_selection_id = fields.Many2one(
        comodel_name="my.selection.model", string="My Selection",
        domain="[('name', 'ilike', my_char)]")

To let the Many2one field look like a selection, add the widget="selection" on that field in the form view.

How the domain should look like, should be decided by you. Here it is just an example.

Upvotes: 1

Related Questions