Search code examples
pythonodooodoo-14

Default values for a dropdown when forms loads in odoo 14


I'd like to have a dropdown filtered based on another value of the form when the forms load, I've been trying to do it in the default_get method, the fields receive the correct data but the dropdown seems not to update

@api.model
def default_get(self, fields_list):
    result = super(ProjectTask, self).default_get(fields_list)
    #some logic to get user list, pre filtered
    result['user_id'] = users_list

user_list contains the pre-filtered list of user ids

Edit

this list is populated like this:

 for e in result_list:
        users_list.append((0,0,{
            'user_id':e['user_id'].id
        }))

The relationship is many to one as follows:

user_id = fields.Many2one('res.users',
    string='Assigned to',
    default=False,
    index=True, track_visibility='always')

I'm looking to load a domain based on the values in the form I have exactly this issue presented in this question, I tried the answer proposed without any luck


Solution

  • In the end, I followed this approach, the highlights of the solution:

    • Defining a function to create a dynamic domain didn't work for me
    • I create a computed field with the filtered information
    • Set the domain in the view, not in the code
    • Use a common function that set the values for a list
    • Add the computed field to the view
    • The same function set the values for the on change on the dropdown and the computed field

    Check the following code:

    fetched_users = fields.Many2many('res.users', compute='fetch_available_employees_default')
    
    def fetch_available_employees_default(self):
        # custom logic, set the computed field and also return the list
        self.fetched_users = users_list      
        return users_list
    

    the on change event of the dropdown, to re-populate the field

    @api.onchange('role_id')
    def fetch_available_employees(self):
        users_list = self.fetch_available_employees_default()
        if len(users_list)>0:
            return {'domain': {'user_id': [('id', 'in', users_list)] }}
        else:
            # return empy list by default
            return {'domain': {'user_id': [('id', '=', -1)]}}
    

    In the View:

    <field name="fetched_users" invisible="True"/>
    
    <xpath expr="//field[@name='user_id']" position="attributes">
         <attribute name="domain">
             [('id','in',fetched_users)]
         </attribute>
     </xpath>