Using @api.onchange to React to Field Changes
When a field value is modified from the frontend (such as through the
user interface), it can trigger a function that performs specific
operations in response to that change. This reactive behavior is
often handled using Odoo’s @api.onchange decorator. Let’s illustrate
this with an example.
Consider a model which contains patients' OP details:
class OpDetails(models.Model):
_name = "op.details"
_description = "Op Details"
partner_id = fields.Many2one('res.partner', string="Patient Name", help="Select the patient")
phone = fields.Integer(string="Phone", help="Patient's Phone number")
email = fields.Char(string="Email Address", help="Patient's email")
Now, let’s define a function that is triggered when the partner_id
field is modified. Upon selecting or changing the partner_id, we
want the system to automatically populate the phone and email fields
of the current record with the corresponding values from the
selected partner’s contact information.
@api.onchange('partner_id')
def _onchange_partner_id(self):
""" Update phone and email while changing the partner_id """
self.write({
'phone': self.partner_id.phone,
'email': self.partner_id.email
})
In this example, we use the @api.onchange() method decorator, passing
partner_id as its argument. This means the function will be
automatically triggered whenever the partner_id field is modified
from the frontend.
Inside the function, you can define the logic that should execute in
response to the change. Additionally, you can pass multiple fields
to the @api.onchange() decorator. In that case, the method will be
triggered whenever any of the specified fields are changed by the
user.