Skip to Content
Menu
This question has been flagged
2 Replies
1148 Views

Hi guys,

how can i get department(many2one field in model A) and it s Child based on user session odoo 13

Avatar
Discard
Author Best Answer

thanks @brahim i did it in that way

department_id = fields.Many2one('hr.department', string='Unité administrative',default= lambda self: self.env.user.employee_ids.department_id, domain="['|',('id','=',department_id),('parent_id','=',department_id)]")

@api.onchange('department_id')
def _onchange_department_id(self):
    my_dep = self.env.user.employee_ids.department_id.id
    return {'domain': {'department_id': ['|',('id','=',my_dep),('parent_id','=',my_dep)]}}

Avatar
Discard
Best Answer

Hi,
can you explain more what's your need ? for example: how would the session's user change the value of departments and its childs ?


FYI, you get session's user with: self.env.user

After that,i cannot tell you the rest because i ignore your requirement.

Regards.

Avatar
Discard
Author

thank for repply ,for exemple when i logged as user X i want to get in my field department_id in model A (many2one field) : user X department and department childs

To sum up what you said in steps:
1- log in as user X
2- go to model A
3- Click on M2O field

=> Dropdown must only contain X's department and its child.

Solution:
This is done by inheriting ORM's search function.
Steps of the solutions:
1- Add context in your M2O field.
Let's say for instance : 'is_m2o_field': True
2- inherit search of your M2O's model : if m2o is a partner, then inherit res.partner and call search method.

3- in search method: check if you have the context 'is_m2o_field'
4- if it doesn't, simple, youjust call then the super. no further operations are needed in this case.
5- it context existsn then: browse your user and get his department and child.
then append to your args.

method should look like this:

@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
context = self._context or {}
if context.get('is_m2o_field'):
department_id = self.env.user.your_user_department_field
args += [('id', 'in', (department_id + department_id.your_department_child_field).ids)]
return super()._search(args, offset, limit, order, count=count, access_rights_uid=access_rights_uid)