Search code examples
pythonodooodoo-8odoo-14

Clear TextField with a checkbox


I want to clear the value entered in the text field whenever the user unchecks the checkbox, I am wondering if this is possible through XMl or Javascript in a XML Odoo view.

enter image description here

XMl code

<field name="expend_percetage" attrs="{'readonly':[('state', 'in', ('done','cancel','sale'))],
                                                       'invisible':[('fixed_expend', '=', True)]}" />
                
                <field name="fixed_expend" attrs="{'readonly':[('state', 'in', ('done','cancel','sale'))],
                                                       'invisible':[('expend_percetage', '=', True)]}" />
                
                <field name="percent_amount" nolabel="1"
                attrs="{'invisible':['&amp;',('expend_percetage', '=', False),('fixed_expend', '=', False)],
                        'readonly': [('state', 'in', ('done','cancel','sale'))] }"/>

Python validations

@api.constrains('percent_amount')
    def check_percent_amount(self):
        for record in self:
            if record.expend_percetage == True:
                if record.percent_amount > 100:
                    raise exceptions.ValidationError("Percentage of costs cannot be greater than 100%")
                elif record.percent_amount < 0:
                    raise exceptions.ValidationError("The percentage cannot be a negative value")
            elif record.fixed_expend == True:
                if record.percent_amount > record.total_revenue:
                    raise exceptions.ValidationError("The Fixed amount cannot be greater than the total revenue")
                elif record.percent_amount < 0:
                    raise exceptions.ValidationError("The Fixed amount cannot be a negative value")

Solution

  • @api.constrains would be better for validating data, but for clearing user input at frontend you should use @api.onchange.

    @api.onchange('expend_percetage','fixed_expend')
    def onchange_percent_amount(self):
        if not self.expend_percetage or not self.fixed_expend:
            self.percent_amount = 0