Search Here

On Onchange Method Readonly Field Not Stored in Database

 In this article you will learn how to store vlaues of a readonly field into the Database on onchange method. 

On Onchange Method Readonly Field Not Stored in Database

The problem is when we set the value of some field on onchange of some another field, than this field convert into readonly mode and does not save into the database.

Read More: How to Show Two Different Values in Many2one Field in Odoo

How to Save Readonly Field in Database in Odoo

You can store readonly field values into the database on onchange method by following ways.

Read More: How to make a field readonly or visible, invisible using attrs in Odoo

  • If you are using newer version of Odoo than follow below steps

Use attribute force_save="1" in view to save value of readonly field

<field name="some_field" readonly="1" force_save="1"/>

If you want to do above step using inheritance than use below code

<xpath expr="//field[@name='your_field_name_goes_here']" position="attributes">
    <attribute name="force_save">True</attribute>
</xpath>


  • If you are using older version of odoo than follow below steps
Read More: How to Override Create, Write and Unlink Method in Odoo

As we know that when we get the value on onchange method, the desired field convert into readonly mode and its value does not save into the database to save the value into the database we are going to override create and write method and in that method we explicitly save the value.

store_readonly_field_value_in_database.py

 

from openerp import models, fields, api,exceptions
class your_model(models.Model):
_inherit = 'your.model'
field_1 =fields.Many2one('model.a', required="True", string="Field 1")
field_2 = fields.Integer(string = 'Field 2')
# onchange of field_1 we are populating value in field_2
@api.onchange('field_1')
def _onchange_field_1(self):
if field_1:
# your logic goes here to get value for field_2
self.field_2 = some_value
# As we know that when we get the value on onchange method,
# the desired field convert into readonly mode and its value does not save into the database
# to save the value into the database we are going to override create and write method and in that method we explicitly save the value
@api.model
def create(self,vals):
if self.field_2:
vals['field_2']=self.field_1
res = super(your_model, self).create(vals)
return res
@api.multi
def write(self,vals):
if not self.field_2:
vals['field_2'] = self.field_1
res = super(your_model, self).write(vals)
return res

Post a Comment

0 Comments