Wednesday, 5 October 2016

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)

4 comments:

  1. Please describe more in depth for better understanding.

    ReplyDelete
  2. Is it possible to create a record of another model (a mail.activity) associated to the record that has changed?

    This is my code:

    @api.onchange('stage_id')
    def _onchange_stage_id(self):
    values = self._onchange_stage_id_values(self.stage_id.id)
    event_user_id = self.user_id
    self.update(values)
    if self.stage_id.id == 3:
    self = self.env['event_mgmt.event_mgmt'].browse(self._origin.id)
    activity = self.env['mail.activity']
    activity_ins = activity.create(
    {'res_id': self.id,
    'res_model_id': 170,
    'res_model':'event_mgmt.event_mgmt',
    'activity_type_id':2,
    'summary': 'Follow Up',
    'note':'Han pasado 5 días desde el paso a propuesta. Realizar seguimiento a la propuesta enviada.',
    'date_deadline': date.today() + timedelta(days=5),
    'activity_category':'default',
    'previous_activity_type_id': False,
    'recommended_activity_type_id': False,
    'user_id': self.user_id.id
    })


    The onchange applies to a crm.lead record and I would like to create an activity (as a reminder) when the stage changes.

    Any help would be very appreciated

    ReplyDelete
    Replies
    1. under your onchange methode use below code snippet to create records for another model:

      values = {
      'key1':value1,
      'key2':value2,
      'key3':value3
      }

      create_another_model_records = self.env['another.model'].create(values)

      Delete