Method decorators gives the elements to manage two different API styles, namely the “traditional” and “record” styles.
In the “traditional” style, parameters like the db cursor, uid, context dictionary and record ids (usually written as cr, uid, context, ids) are passed explicitly to all methods. In the “record” style, those parameters are hidden into model instances, it gives a more object-oriented feel.
|env = Env(cr, uid, context)||# cr, uid, context are in env|
|recs = env[MODEL]||# retrieves an instance of MODEL|
|recs = recs.search(DOMAIN)||# search returns a recordset|
|for rec in recs:|
|# iterates over the records|
|recs.write(VALUES)||# update all records in recs|
Methods written in the “traditional” style are automatically decorated, following some heuristics based on parameter names.
Here I am explaining one of the most important Method Decorator “OnChange”
@api.onchange: updating UI on the fly
When a user changes field’s value on a form (but has not saved the form yet), it can be useful to automatically update other fields based on that value like updating a final total when the tax is changed or a new order line is added.
- computed fields are automatically checked and recomputed, an onchange is not needed
- for non-computed fields, the onchange() decorator is used to provide new field values:
@api.onchange(‘field1’, ‘field2’) #if these fields are changed, it will call method
if self.field1 < self.field2:
self.field3 = True
the changes performed while executing the method are then sent to the client program and become visible to the user
- Computed fields and new API onchanges are automatically called by the client without having to add them in views
- Now just restart the server and your onchange is ready, No need to update the module.
- It is possible to initiate the trigger from a specific field by adding on_change=”0″ in a view:It won’t trigger any interface update when the field is edited by the user, even if there are function fields or explicit onchange depending on that field.
Other Decorators in Odoo: