Odoo 17 Development Book - Onchange Method

Onchange Method

When a field value changes from the front end and a function triggers ,which performs certain operations.Let’s depict 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)
    phone = fields.Integer(string="Phone", help="Patients Phone number")
    email = fields.Char(string="Email Address", help="Patient's email")

Now ,Let's write a function while changing the partner_id field.While changing the partner_id we want to write the phone and email of the op with partner_id’s phone and email.

@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
   })

Here we are using a method decorator onchange( ) in which we are passing partner_id fields as its argument.As result it triggers this function whenever the fields partner_id changes though front end and performs the operations.Moreover we can pass multiple fields as the argument for the onchange( ) decorator and which triggers the function while change in any of the fields.

whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message