odooodoo-10odoo-9odoo-11

Save value from readonly field in odoo


I have 3 fields on form field sum is readonly. After click on Save data from readonly field is not store in database.

Example:

class myClass(models.Model):

number_1 = fields.Integer(store=True,default=0)
number_2 = fields.Integer(store=True,default=0)
sum = fields.Integer(store=True)

@api.onchange('number_1','number_2')
def compute_sum(self):
    total = self.number_1 + self.number_2
    self.sum = total

Solution

  • I would prefer a computed field in this situation. Readonly fields won't be saved by formular changes (for example on change events). In Odoo 11 there was introduced a new option force_save for this behaviour in views, but previous versions don't have this option (except with community modules e. g. web_readonly_bypass by OCA).

    The solution for computed fields:

    class myClass(models.Model):
    
        number_1 = fields.Integer()
        number_2 = fields.Integer()
        sum = fields.Integer(compute="compute_sum", store=True)
    
        @api.depends('number_1','number_2')
        @api.multi
        def compute_sum(self):
            for record in self:
                total = record.number_1 + record.number_2
                record.sum = total
    

    There is no need for view definition changes. And there also is no need for store parameter in normal Integer fields. Default value 0 is already the default on Integer so ne need to define it.

    You don't have to explictly define readonly in the view for sum because a computed field without inverse method is readonly by default.