Onchange many2one filed in odoo

Today you will learn how to create a dependent drop down (many2one) fields in Odoo. For example I have two many2one fields (campus_id and department_id), and we want to change the department on the basis of campus field.

campus_id = fields.Many2one('model.campus', string="Campus Name")
department_id = fields.Many2one('model.department', string="Department Name")

1     @api.onchange('campus_id')
2    def _campus_onchange(self):
3        res = {}
4        res['domain']={'department_id':[('campus_id', '=', self.campus_id.id)]}
5        return res

Code Description:
In line no 1 we use @api.onchange decorator for campus_id. It means whenever campus changes or select a campus from many2one filed do the following line of code (3,4,5).  In line no 3 we declare a dict named res. In line no 4 we use domain to change the department field.

res['domain']      =     {'department_id':[('campus_id', '=', self.campus_id.id)]}
                                       |                                |
                                       |                                |
   (field name which is to changed)       (field name which is intended to change)

No comments :

Post a Comment

Leave A Comment...