i have odoo17 project and i need to show in form view of res.users the groups that i want based on users type and role,
res.users.tree
res.users
res.users.form.custom
res.users
To achieve dynamic display of user groups in the res.users form view based on the user's type and role in Odoo 17, you'll need to implement a combination of XML view modifications and Python model enhancements. Below is a comprehensive guide to help you accomplish this.
Overview
Define a Computed Field for Available Groups: Create a computed Many2many field that determines which groups should be available based on the user's type and role.
Modify the Form View with Dynamic Domain: Update the form view to apply a dynamic domain to the groups_id field, filtering available groups.
Ensure Groups are Assigned Appropriately: Maintain your existing logic to assign groups based on type and role, ensuring consistency.
Let's go through each step in detail.
1. Define a Computed Field for Available Groups
First, extend the res.users model to include a computed field that determines which groups should be available for selection based on the user's type and role.
python
from odoo import fields, models, api
from odoo.exceptions import AccessError
class Users(models.Model):
_inherit = "res.users"
position = fields.Char(string='Position')
type = fields.Selection([
('admin', 'Admin'),
('moderator', 'Moderator'),
('reader', 'Reader'),
], string='User Type', required=True, default='reader')
role = fields.Selection([
('republic', 'Republic'),
('region', 'Region'),
('district', 'District'),
('mahalla', 'Mahalla'),
], string='Role', default='mahalla')
region_id = fields.Many2one('region', string="Region")
district_id = fields.Many2one('district', string="District")
mahalla_id = fields.Many2one('mahalla', string="Mahalla")
# Computed field for available groups based on type and role
available_group_ids = fields.Many2many(
'res.groups',
string='Available Groups',
compute='_compute_available_group_ids'
)
@api.depends('type', 'role')
def _compute_available_group_ids(self):
for user in self:
groups = self.env['res.groups']
if user.type == 'admin':
groups |= self.env.ref('mahallam.group_admin', raise_if_not_found=False)
if user.type == 'moderator':
groups |= self.env.ref('mahallam.group_moderator', raise_if_not_found=False)
if user.type == 'reader':
groups |= self.env.ref('mahallam.group_reader', raise_if_not_found=False)
if user.role == 'republic':
groups |= self.env.ref('mahallam.group_republic', raise_if_not_found=False)
elif user.role == 'region':
groups |= self.env.ref('mahallam.group_region', raise_if_not_found=False)
elif user.role == 'district':
groups |= self.env.ref('mahallam.group_district', raise_if_not_found=False)
elif user.role == 'mahalla':
groups |= self.env.ref('mahallam.group_mahalla', raise_if_not_found=False)
# Add other groups based on type and role as needed
# Example:
# if user.some_other_condition:
# groups |= self.env.ref('module.group_xyz', raise_if_not_found=False)
# Remove any None values in case ref was not found
groups = groups.filtered(lambda g: g)
user.available_group_ids = groups
Explanation:
available_group_ids: A computed Many2many field that aggregates the relevant groups based on the user's type and role.
_compute_available_group_ids: The compute method populates available_group_ids by referencing the appropriate groups. The raise_if_not_found=False parameter ensures that missing group references don't cause errors.
2. Modify the Form View with Dynamic Domain
Next, update the form view to apply a dynamic domain to the groups_id field, ensuring that only the groups specified in available_group_ids are displayed.
xml
Explanation:
groups_id Field: The domain attribute is set to filter groups based on the available_group_ids computed field.
xml
domain="[('id', 'in', available_group_ids)]"
Attributes (attrs): Simplified the syntax to use attrs for better readability and maintainability.
xml
attrs="{'invisible': [('type', '=', 'admin')]}"
Note: Corrected the invisible attribute in the button element to use attrs instead of inline conditions.
3. Ensure Groups are Assigned Appropriately
Your existing Python code already assigns groups based on the user's type and role during creation and update. Ensure that this logic complements the dynamic domain in the form view.
Key Points:
Conflict Avoidance: Since you're dynamically filtering available groups in the form view, ensure that the assign_group_based_on_role method doesn't inadvertently remove necessary groups. It's critical that the group assignment logic aligns with the groups available in the form view.
Readonly Groups (Optional): If you want to prevent users from manually modifying their groups and rely solely on the automated assignment, consider making the groups_id field read-only in the form view.
Note: Making groups_id read-only restricts manual changes, ensuring that group assignments are managed exclusively through your Python logic.
Complete Python Model Code
For clarity, here's the complete Python model with additional comments and improvements:
python
Improvements and Considerations:
Safety with raise_if_not_found=False: This prevents the code from breaking if a group reference is missing. Ensure that all group XML IDs used exist in your modules.
Efficient Group Assignment: Instead of removing all groups and reassigning, you might prefer a more efficient method to only add or remove specific groups. However, this approach ensures that group assignments strictly follow the defined logic.
Extensibility: You can easily extend the group assignment logic by adding more conditions based on additional fields or requirements.
Final Thoughts
By implementing the above steps, your res.users form view will dynamically display and allow selection of user groups based on the specified type and role. This ensures that user permissions are managed consistently and align with your business logic.
Additional Tips:
Testing: After implementing, thoroughly test with different user types and roles to ensure that the correct groups are available and assigned.
Security: Ensure that only authorized personnel can assign or modify user groups, especially administrative groups.
Maintenance: Document the group assignment logic for future maintenance and potential onboarding of new developers or administrators.
If you encounter any issues or have further questions, feel free to ask!