Odoo Discard Change When an Exception Occurred

Viewed 55

I need to discard the change user made when an exception occurred, to go back to the value when input is valid.

For example I have 2 field check_in & check_out as Date type. I need to check the check_in must be smaller than check_out. When the check_in is bigger than check_out, an exception dialog shows. When the user closes the exception dialog, I need to discard the change for check_in.

@api.onchange('check_in', 'check_out')
def validate_check_in(self):
    for rec in self:
        if rec.check_in > rec.check_out:
            raise ValidationError("Not valid check in and check out")
1 Answers

I don't know the method of discarding the changes. However, I do have a workaround in case you haven't got one.

By using _origin, you can get the original values before the onchange is triggered. So, when the exception is going to occur, you can just set the value(s) back to its original state, which is almost similar to discard.

The code should be something like this.

@api.onchange('check_in', 'check_out')
def validate_check_in(self):
    for rec in self:
        if rec.check_in > rec.check_out:
            rec.check_in = rec._origin.check_in # Added for the workaround
            raise ValidationError("Not valid check in and check out")

If you don't like this solution, please wait a bit longer in case there's someone who knows how to discard because I also want to know that.

Related