Add values on One2many field onchange

Viewed 711

I'm trying to add values in my one2many field onchange. I tried using the [(0,0, {values})] but nothing happened. Any idea on how to implement it?

custom_line_ids = fields.One2many('mrp.production', 'product_id', 'Custom Line')   
@api.onchange('product_id')
    def add_custom_line_ids(self):
        mrp = self.env['mrp.productions'].search([])
        result = []
        
        vals = {
                'sequence': self.sequence,
                'name': self.name,
                'product_id': self.product_id,
                'date_planned_start': self.date_planned_start,
                'state': self.state,
            }
        self.update({'custom_line_ids':[(0, 0, vals)]})
2 Answers

Actually you are using update method, which only update the model's value but not yet stored on database. You should use write method instead.

You need to return the value in onchange. This would work:

custom_line_ids = fields.One2many('mrp.production', 'product_id', 'Custom Line')   

@api.onchange('product_id')
def add_custom_line_ids(self):
    vals = {}
    mrp_ids = self.env['mrp.productions'].search([])
    if mrp_ids:
        for mrp in mrp_ids:
            vals['custom_line_ids']=[(0,0,{
                'date': mrp.date,  
               
            })]
    return {'value': vals}
Related