japs
japs

Reputation: 11

How to Filter res.partner Records by Logged-in User's Country in View Domain on Odoo?

I'm trying to restrict the record list view in my Odoo custom module so that users can only see res.partner records where the country_id matches their own.

I attempted to set this up in my XML using context and domain, but it doesn't seem to work. Here's the current code:

<record id="action_aefc_member_pending_approvals" model="ir.actions.act_window">
    <field name="name">Pending User Approvals</field>
    <field name="res_model">res.partner</field>
    <field name="view_mode">list,form</field>
    <field name="context">{'user_country_id': user.partner_id.country_id.id}</field>
    <field name="domain">[('country_id', '=', context.get('user_country_id'))]</field>
    <field name="view_id" ref="view_partner_list_approval"/>
</record>

I want to filter the list to only display records where the country_id of res.partner matches the logged-in user's country. How can I correctly pass and use the logged-in user's country ID in the domain for this view?

EvalError: Can not evaluate python expression: ({'user_country_id': user.partner_id.country_id.id})
    Error: Name 'user' is not defined
    EvalError: Can not evaluate python expression: ({'user_country_id': user.partner_id.country_id.id})
    Error: Name 'user' is not defined
        at evaluateExpr (http://localhost:8069/web/assets/debug/web.assets_web.js:32125:15)
        at makeContext (http://localhost:8069/web/assets/debug/web.assets_web.js:18878:45)
        at _preprocessAction (http://localhost:8069/web/assets/debug/web.assets_web.js:97579:26)
        at doAction (http://localhost:8069/web/assets/debug/web.assets_web.js:98580:18)
        at async Object.loadState (http://localhost:8069/web/assets/debug/web.assets_web.js:98886:13)
        at async WebClient.loadRouterState (http://localhost:8069/web/assets/debug/web.assets_web.js:102973:27)

Upvotes: 1

Views: 16

Answers (1)

japs
japs

Reputation: 11

I found a solution to my issue, and I want to share it in case someone else encounters the same problem in the future.

The key was to define a field with a search method in the model. Since store=False fields cannot be used directly in domain filters, I implemented a custom search function to map user_country_id to country_id.

Add this field to the model

user_country_id = fields.Many2one(
    'res.country', string="User Country",
    store=False, search="_search_user_country"
)

def _search_user_country(self, operator, value):
    """Defines how `user_country_id` is used in domain searches"""
    return [('country_id', operator, self.env.user.country_id.id)]

Then, modify the view’s domain condition like this:

<field name="domain">[('user_country_id', '=', 1)]</field>

Upvotes: 0

Related Questions