View elements also support a few dynamic attributes that allow views to dynamically change their appearance or behavior depending on field values . We may have on change events, able change values on other fields while editing data on a form, or have fields to be mandatory or visible only when certain conditions are met.
The on change mechanism allows us to change values in other form fields when a particular field is changed. For example, the on change on a Product field can set the Price field with a default value whenever the product is changed.
In older versions the on change events were defined at the view level, but since version 8.0 they are defined directly on the Model layer, without the need for any specific markup on the views. This is done by creating methods to perform the calculations, and using @api.onchange('field1', 'field2')
to bind it to fields. These onchange methods are discussed in more detail in Chapter 7, ORM Application Logic - Supporting Business Processes.
The on change mechanism also takes care of the automatic recomputation of computed fields, to immediately react to the user input. Using the same example as before, if the Price field is changed when we changed the Product, a computed Total Amount field would also be automatically updated using the new price information. Dynamic attributes A couple of attributes provide an easy way to control the visibility of a particular user interface element:
groups
can make an element visible depending on the security Groups the current user belongs to. Only the members of the specified groups will see it. It expects a comma separated list of Group XML IDs.states
can make an element visible depending on the record's State field. It expects a comma separated list of State values.Other than these, we also have a flexible method available to set an element visibility depending on a client-side dynamically evaluated expression. This is the attrs
special attribute, expecting for a value dictionary that maps the value of the invisible
attribute to the result of an expression.
For example, to have the refers_to
field visible in all states except draft, use the following code:
<field name="refers_to" attrs="{'invisible': state=='draft'}" />
The invisible
attribute is available in any element, not only fields. For example, we can use it on notebook pages and in group elements.
The attrs
can also set values for two other attributes: readonly
and required
. These only make sense for data fields, to make them not editable or mandatory. This allows us to implement some basic client-side logic, such as making a field mandatory depending on other record values, such as the State.