forvas
forvas

Reputation: 10189

Best way to apply dynamic domain to many2many field in Odoo8?

I have a model in which the user can select the breed of a dog (dog_breed, a Selection field). Then, in the same model, I have a Many2many field (dogs) in which the user can add dogs. But I want that when the user adds a dog, he is only able to select among the dogs whose breed is the one selected in the Selection field.

<field name="dog_breed"/>
<field name="dogs" domain="[('breed', '=', dog_breed)]"/>

When you add an element to a Many2many, first you see a list of the available records, to select one of them if the one you are looking for already exists. What I need is to apply a domain to that list.

Example:

An user selects foxterrier in the Selection field dog_breed. Now he adds an element in the Many2many dogs. A list with all the available dogs will be opened, but I want to show a list with all the available foxterriers. To do that, I wrote the above code, but it is not working at all.

However, if I modify the code this way:

<field name="dog_breed"/>
<field name="dogs" domain="[('breed', '=', 'foxterrier')]"/>

It works perfect. Is it possible to manage this from XML code?

Upvotes: 3

Views: 715

Answers (1)

forvas
forvas

Reputation: 10189

Dynamic domain must be applied in Python code, in this case isn't even necessary to use onchanges to return the required domain, I've only had to cut my domain to the definition of the Many2many field in Python:

dogs = fields.Many2many(
    comodel_name='dog',
    relation='mss_dog_rel',
    column1='mss_id',
    column2='dog_id',
    string='Dogs',
    domain="[('breed', '=', dog_breed)]",
)

Upvotes: 1

Related Questions