Search code examples
odooodoo-8

Odoo Filter many2one field on load


In my module I have a many2one field to select workers for a particular task. According to the requirement that field should only display the workers in the current user's department. Simply this is the code,

 _columns = {
    'employee_id': fields.many2one('hr.employee', 'Employee'),
}

My problem is how to perform such filteration for a field on load? I tried using functional field in a domain in view xml. but It seems functional field gets its value when saving the particular record.

Also I tried adding domain to the field itself, here get_current_user_department is a function returns the department id

_columns = {
    'employee_id': fields.many2one('hr.employee', 'Employee',domain=[('department_id.id','=',get_current_user_department)]),
}

This generates following error,

TypeError: is not JSON serializable

Any suggestion to make this work? Thanks


Solution

  • Also you can take one field for storing current user department you can set default value of current user department.

    default_department_id = fields.Many2one('employee.department', 
                                            string='My User',
                                            default='get_department') 
    

    Now you need to create function for set default department.

    After that you need to write in XML:

    <field name="default_department_id" invisible="1"/>
    <field name="employee_id" 
           domain="
               [('department_id','=',default_department_id)]
           "/>