This question has been flagged
3 Replies
7994 Views

In my view I have a Boolean field (chk_valido) and two other fields. I want those fields to get the value of the current user and the current date, when the boolean fields is set to True. With this code the fields are getting the value but when I click the "Save" button those values desapear. What is causing these issue? How can i save those values? "user_valido" and "fecha_validaciongabinete" are set to readoly in the view

chk_valido = fields.Boolean(string='Está validado')
user_valido = fields.Many2one('res.users', string='Usuario valido')
fecha_validaciongabinete = fields.Datetime(string='Fecha Validacion gabinete')

@api.onchange('chk_valido')
def _onchange_chk_valido(self):
    if self.chk_valido:
        self.fecha_validaciongabinete=fields.Datetime.today()
        self.user_valido= self.env.user
    else:
        self.fecha_validaciongabinete=""
        self.user_valido=False
Avatar
Discard
Best Answer

Hi,

if you are using odoo latest version give force_save="1" along with field definition in XML.

 See :-https://www.youtube.com/watch?v=XEnvGQilBk8


Thanks


Avatar
Discard
Best Answer
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

Save Readonly Field in Database



Avatar
Discard
Best Answer

You can try this :   <field name="field_name" readonly="1" force_save="1"/>

Explanation:when using onchange on a readonly field value when changed can't be stored to the database ,You can use this to force saving its value,

gd luck

Avatar
Discard