Python – How do I make all fields in a form read-only when the status is ‘confirmed’?

How do I make all fields in a form read-only when the status is ‘confirmed’?… here is a solution to the problem.

How do I make all fields in a form read-only when the status is ‘confirmed’?

When the status of the object changes to “confirmed“, I want all fields in the form to be read-only. So far I’ve put attrs = "{'readonly': [('state', '=', 'confirmed')]}" in each field, but I wonder if there is a way to make it more optimized.

Solution

If you want to apply the condition to each View of the model (a model that shows multiple Form Views in different parts of Odoo), it is best to specify it in Python. In the definition of each field, you should add the states parameter:

your_field = fields. Whatever(
    ...
    readonly=False,
    states={
        'confirmed': [('readonly', True)],
    }
)

That way, if a

user opens the model from a different View than the one you modified, if the status is confirmed, the field will be read-only, and it doesn’t matter if you didn’t modify the open View

On the other hand, if you only want to apply your purpose in a specific form View, you can do something faster than adding attrs to each field, it will add it to the label that contains multiple fields, such as group. This also applies to you and is faster:

<group attrs="{'readonly': [('state', '=', 'confirmed')]}">
    <field name="your field_1"/>
    <field name="your field_2"/>
    ...
</group>

Related Problems and Solutions