edward
edward

Reputation: 29

@api. depends or @api.onchange not working with compute field. why?

In CRM module , in pipeline record, I have added one Float called price_difference with the help of inheritance. That field is difference between planned_revenue and sale_amount_total fields from the CRM module.

when I tired to use method name get_price_diff(), it is not worked for me. I want to use sale_amount_total and planned_revenue with @api. depends or @api.onchange, but it is not working now.

Working of my method is simple, it depending upon sale_amount_total and price_difference field. If any of the values changed, the method should run.

sale_amount_total is compute field in base module.

My code is below. How to do it?

class rate_record(models.Model):
    _inherit = 'crm.lead'

    price_difference = fields.Float(string='Price Difference', readonly=True)

    @api.onchange('sale_amount_total', 'planned_revenue')
    def get_price_diff(self):
        self.price_different = self.planned_revenue - self.sale_amount_total

Upvotes: 0

Views: 4524

Answers (3)

Nhon Ha
Nhon Ha

Reputation: 488

Your code:

price_difference = fields.Float(string='Price Difference', readonly=True)

readonly=True - you won't be able to save this data price_difference.

Remove it, and test your code. Should work.

I had the same problem, it updates, but when I save it, it just disappears. Not sure if this is your problem, because your question is vague (what do you mean its not working now? Not saving the data? If this is the case, then my solution will work for you as it worked for me)

Upvotes: 0

Yunan
Yunan

Reputation: 43

What you want to do can't be achieved using api.depends or api.onchange only because it's not the way they work (see: HERE).

You can do it by using a compute method:

class rate_record(models.Model):
    _inherit = 'crm.lead'

    price_difference = fields.Float(
                           string='Price Difference', 
                           compute='get_price_diff')

    @api.depends('sale_amount_total', 'planned_revenue')
    def get_price_diff(self):
        self.price_different = self.planned_revenue - self.sale_amount_total

Upvotes: 1

CZoellner
CZoellner

Reputation: 14801

I can only guess, because to this moment i don't have all information about your code. The onchange method get_price_diff looks right. But you set the field as readonly=True, and that means, the "computed" value won't be saved.

Since Odoo 11 you can force Odoo to save value changes on readonly marked fields with force_save="1" on it's field view definition:

<field name="price_difference" force_save="1" />

For older versions there are modules in the OCA repositories on Github. For example for Odoo 10 web_readonly_bypass.

Upvotes: 0

Related Questions