Search code examples
javascriptodoo-8odoo

How to check if an user belongs to several groups in Odoo?


I am trying to perform an action if an user belongs to several groups, in JavaScript.

So I have the following code, which works:

Users.call('has_group', ['group1']).done(function(belongs_to_group1) {
    if (belongs_to_group1 == true)
        Users.call('has_group', ['group2']).done(function(belongs_to_group2) {
            if (belongs_to_group2 == true)
                Users.call('has_group', ['group3']).done(function(belongs_to_group3) {
                    if (belongs_to_group3 == true)
                        perform_the_action();
                    else
                        return;
                });
            else
                return;
        });
    else
        return;
});

The problem is that it looks awful, and I was wondering if there is a simpler way to achieve this, something like:

Users.call('has_group', ['group1', 'group2', 'group3']).done(function(belongs_to_all_groups) { ... }

But last line is not working at all. Any ideas?


Solution

  • In that you need to create another method in python file belongs to res.users model in which you should check that user belongs to multiple groups or not and then you need to use this customize method in javascript.

    I just give you idea how to do this (however given code may not be executable directly)

    @api.model
    def customize_has_groups(self, groups_ext_ids):
        """here groups_ext_ids is a list of groups(external_id may be)"
        if not groups_ext_ids:
            return False
        user = self.env.user
        for group in groups_ext_ids:
            group_id = self.env.ref(group).id
            if group_id in user.groups_id:
                return False
        return True
    

    Here this method returns false if any of the groups are not belongs to users. You may need to update methods behaviour according to your requirement.

    And then you can achieve result by single json_rpc call.

    Users.call('customize_has_groups', ['group1', 'group2', 'group3']).done(function(belongs_to_all_groups) { ... }