4
votes

I'm trying to make a field readonly depending on a condition. This condition is that the user who opens the form belongs to a specific group (that's why I can't use attrs or groups to manage this).

What I did, and I'm pretty close to my purpose, is to overwrite fields_view_get method, check the condition, and alter the field if necessary.

@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
                    submenu=False):
    res = super(res_partner, self).fields_view_get(
        view_id=view_id, view_type=view_type, toolbar=toolbar,
        submenu=submenu)
    my_group_gid = self.env.ref(
        'my_module.my_group').id
    current_user_gids = self.env.user.groups_id.mapped('id')
    if view_type == 'form':
        if my_group_gid in current_user_gids:
            doc = etree.XML(res['arch'])
            the_fields = doc.xpath("//field[@name='my_field']")
            the_field = the_fields[0] if the_fields \
                else False
            the_field.set('readonly', '1')
            res['arch'] = etree.tostring(doc)
    return res

It seems to work well, because if I click on Fields View Get under the Developer Mode, the XML view code has been changed and I can see <field name="the field" attrs= ... readonly="1"/>. However, I always can edit the field.

I can't understand this very well, because there are other modules in which fields are modified exactly like this and they work.

Despite that, I keep trying and if instead of readonly attribute, I set modifiers in the following way, it works:

the_field.set('modifiers', '{"readonly": true}')

The problem: I'm totally overwriting all the modifiers of the field (like attrs, required, etc). So I want to update the modifiers attribute, not overwrite it. What I do is:

modifiers = the_field.get('modifiers')

When I try to convert the string modifiers to a dictionary, I get an error. This is the value of modifiers:

{"invisible": [["is_company", "=", true]]}

Can any one explain me why the_field.set('readonly', '1') is not working properly or why I cannot convert to a dictionary the variable modifiers?

EDIT

Ok, that variable is JSON data, so I should have converted it to a dictionary in a good way like this:

import json
modifiers_dict = json.loads(modifiers)

Now my question is only the first one:

Why can't I simply use the_field.set('readonly', '1') to manage my purpose?

1

1 Answers

2
votes

This is what modifiers are

Point is, openerp uses the attrs attribute into the view to setup accordingly the modifiers attribute, after that the fields_view_get is called, thus if you just change attrs it wouldn't work, then you need to change modifiers as well when you are within fields_view_get.