Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

Defining onchange methods in odoo if on_change is defined on the model

I'm trying to define an onchange event on the field amount and line_cr_ids.amount on account.voucher but any definition like this:

@api.one
@api.depends('line_cr_ids', 'line_cr_ids.amount')
def _line_amount_onchange(self):
    ...

Or

@api.one
@api.onchange('amount')                                 
def _onchange_amount(self):
    ...

Are never called, I noticed that a on_change parameter is defined on those fields in the view. Does it means the only way to get the onchange is to redefine the one already defined?

Upvotes: 2

Views: 1800

Answers (2)

Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

Ok, so I solved my problem as I didn't want to remove the on_change attributes... There is a better and more stable way of working than using the api.onchange decorator for now. I guess the decorators could get more stable over time but in my case it didn't fit at all. It would get called and sometimes it wouldn't... Children of object do not have access to parent object because the ORM doesn't allow it... ask me why I don't know...

That said the holy grail is to override the onchange method on the object.

I noticed that whenever something happens, it would call the onchange method on my account.voucher object.

So the solution is to create a method:

class AccountVoucher(models.Model):
    ...
    @api.model
    def onchange(self, ids, values, field, fields):
        result = super(AccountVoucher, self).onchange(
            values, field, fields
        )
        #...
        # do whatever you want here change result and return it
        #...
        result

This way, all changes are visible and it never miss. It also call other onchange when calling super so you don't miss anything. If you need to use decorators anyway, it shouldn't stop anything from working. In other words... while overriding onchange, you're getting at the root of the problem and nothing stops you from getting things done.

Upvotes: 1

Alessandro Ruffolo
Alessandro Ruffolo

Reputation: 1575

Yes, you need to redefine the on_change method called by the view. Or change the view itself removing it as attribute.

Upvotes: 1

Related Questions