Skip to Content
Menu
This question has been flagged
1 Reply
2734 Views

I want to apply the readonly attribute to all fields of the form if a certain condition is met (i.e. when a field has a certain value). 

I would be able to achieve this if I hardcoded all the fields in the form with this:-

attrs="{'readonly': [('stage', '=', 'Freeze')]}"

But I don't wish to do this. This is not an elegant solution and kind of a brittle implementation.

I would like to have an automatic solution. Is there a built-in method that I can overwrite and apply this readonly attribute for all fields irrespective of the fields in the form?

Avatar
Discard
Best Answer

Hi

You should inherit the fields_view_get method

Try this:

    @api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        result = super(SaleOder, self).fields_view_get(view_id, view_type, toolbar=toolbar, submenu=submenu)
        doc = etree.XML(result['arch'])
        if view_type == 'form':
            for node in doc.xpath("//field"):
                domain = [['stage', '=', 'Freeze']]
                if node.attrib.get('modifiers'):
                    attr = json.loads(node.attrib.get('modifiers'))
                    if attr.get('readonly'):
                        value_readonly = attr.get('readonly')
                        if str(attr.get('readonly')) != "True":
                            value_readonly.insert(0, "|")
                            domain = value_readonly + domain
                    attr['readonly'] = domain
                    node.set('modifiers', json.dumps(attr))
        result['arch'] = etree.tostring(doc)
        return result
Hope it helps!!

Avatar
Discard
Author

This worked wonderfully and was easy to understand. Thank you!

You're welcome

Related Posts Replies Views Activity
1
Oct 24
244
1
May 24
1308
1
Nov 22
3299
2
Jul 22
2098
9
Jul 21
60620