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

Hi, my goal is to change a boolean field based on current selected company under 'sale.order'.

'sale.order' has field Many2one 'company_id' related to 'res.company'.

If the stored value in field 'company_id' is different than the one selected by current user, field value equals to False in UI before saving, if they are the same, the boolean field equals to True.

Below is what I've got, Any input is very welcome, thank you.

match = fields.Boolean('Match', compute='_check_company')

def _check_company(self):
    current_company = lambda self: self.env['res.users']._get_company()
    if self.company_id.name != current_company.name:
        self.match = False
    else:
        self.match = True
Avatar
Discard
Best Answer

Hi Justin,

self.env.user.company_id is getting company of logged user from current Environment/Session.
self.env['res.users']._get_company(), if you see this method returning self.env.user.company_id.

define field with store=True like:
match = fields.Boolean('Match', compute='_compute_company', store=True)

And if you want to adapt company changes to calculate field match add company_id in depends like.
@api.depends('company_id')

Also better to compare company_id.id instead name.


Avatar
Discard
Author

Hey, thank you very much for the explanation.

For attribute 'store', my module is to use 'match' to hide/show fields/button in views and some other chained action through api.onchange for user/groups, the actual value is not critical.

For @api.depends, seems like it makes no difference on '_compute_company' or not. Even without it, upon saving the record, the function is triggered and so as switching user company cuz it reloads the page.

For company_id.id, that was my mistake comparing names, I am now comparing 'id', thx!

Author Best Answer

I cannot edit post or comment below, so posting this update here.

match = fields.Boolean('Match', compute='_compute_company')

@api.multi
def _compute_company(self):
    self.ensure_one()
    if self.company_id.name != self.env.user.company_id.name:
        self.match = False
    else:
        self.match = True

The above code works fine, but I still don't understand the difference between, self.env.user.company_id and lambda self: self.env['res.users']._get_company()

And also, when is 'compute' field being triggered.

Can anyone explain, please?

Avatar
Discard
Related Posts Replies Views Activity
3
Nov 24
347
0
Nov 24
153
4
Sep 24
1491
2
Aug 24
355
2
Jul 24
413