Onchange Methods
When the value of a field id is changed in the user interface, usually in a form view, a onchange method is invoked. Let us illustrate this with an example. Consider a model that stores all student records.
class Student(models.Model):
_name = "student.student"
_description = "Student"
partner_id = fields.Many2one('res.partner', string="Partner")
phone = fields.Char(string="Phone Number")
email = fields.Char(string="Email", required=True)
Now, for the field partner_id, let us define an onchange method that will update the email and phone field values. We can write the student's email and phone number based on the partner selected in the partner_id field.
@api.onchange('partner_id')
def _onchange_partner_id(self):
self.write({
'email': self.partner_id.email,
'phone': self.partner_id.phone
})
The field passed as a parameter and the api decorator onchange() are used in an onchange method. As a result, the method specified will be used whenever the user interface changes the value of that field. For the onchange() decorator, more than one field may be supplied as an argument.