Enable Dark Mode!
how-to-use-onchange-with-multiple-fields-in-odoo-19.jpg
By: Anupriya Ashok

How to Use Onchange with Multiple Fields in Odoo 19

Technical Odoo 19 Odoo Enterprises Odoo Community

By passing the names of all dependent fields into the decorator, you can use @api.onchange with multiple fields in Odoo 19. The onchange method is called whenever one of those fields in the form view changes. This enables you to validate user input, display warnings, and dynamically update other fields in real time, all without storing the record in the database.

When creating interactive and user-friendly forms, where values respond instantly to user input, this feature is extremely helpful.

What Is @api.onchange in Odoo 19?

Logic is executed by Odoo's @api.onchange client-side mechanism when a user modifies a field in a form view. It helps users fill out forms, updates dependent fields, and applies UI-level validations.

Key Characteristics of @api.onchange

  • Triggered only in form views
  • Only when users interact with fields in a form view do the onchange methods function. They don't carry out backend, kanban, or in-tree operations.

  • Executes before saving the record
  • Even before the user clicks Save, the method begins to execute as soon as a field value changes.

  • Does not write data to the database automatically
  • Any changes made inside an onchange method exist only in memory until the record is explicitly saved.

  • Best suited for UI logic and user guidance
  • Onchange should be used for calculations, default values, warnings, and field updates—not for enforcing critical business rules.

How to Use @api.onchange with Multiple Fields

A value in the real world usually depends on several different fields. Odoo allows you to listen to changes from multiple fields by listing them inside the @api.onchange decorator. Every time one of the specified fields changes, the onchange method will be called.

Syntax:

@api.onchange('field_one', 'field_two', 'field_three')
def _onchange_multiple_fields(self):
   Pass
  • All listed fields are listeners
  • Changing any single field triggers the method
  • Helps avoid writing multiple onchange methods for related logic
  • Example: Onchange with Multiple Fields in Odoo 19

You want to automatically calculate the total amount when either quantity or unit_price changes.

Example: Onchange with Multiple Fields in Odoo 19

Use Case

When either quantity or unit_price changes, the total amount is automatically calculated.

Modules for sales, inventory, and invoicing frequently need this.

from odoo import api, fields,  models
class SaleOrderLine(models.Model):
   _name = 'custom.sale.line'
   quantity = fields.Float(string="Quantity" help="Number of units for the sale order line."
)
   unit_price = fields.Float(string="Unit Price")
   total_price = fields.Float(string="Total Price")
   @api.onchange('quantity', 'unit_price')
   def _onchange_quantity_unit_price(self):
       """Compute total price when quantity or unit price changes.
       Resets total price to 0.0 if values are missing.
      (UI-only onchange, not stored until saved.)"""
       for record in self:
           if record.quantity and record.unit_price:
               record.total_price = record.quantity * record.unit_price
           else:
               record.total_price = 0.0
  • The onchange method executes when the user modifies the quantity.
  • The same procedure is used when the user modifies the unit_price.
  • The method instantly recalculates total_price.
  • The outcome can be seen right away in the form
  • Until the user clicks Save, no database write occurs.

Using Conditions with Multiple Onchange Fields

You can also apply conditional logic and validations inside an onchange method to prevent incorrect input early.

@api.onchange('start_date', 'end_date')
def _onchange_dates(self):
"""Validate date range and prevent end date
from being earlier than start date."""
   if self.start_date and self.end_date and self.start_date > self.end_date:
       self.end_date = False
       return {
           'warning': {
               'title': "Invalid Date Range",
               'message': "End Date cannot be earlier than Start Date."
           }
       }
  • The method listens to both start_date and end_date
  • If the end date is earlier than the start date:
  • The invalid value is reset
  • A warning message is shown to the user
  • The user is guided immediately instead of facing an error after saving

Best Practices for Using Onchange with Multiple Fields

  • Keep your reasoning straightforward and UI-focused.
  • Verify only the user's edits.
  • Create a single onchange by combining related fields.
  • Instead of blocking actions, use warnings to help users.
  • Always support important rules with limitations.

Why Onchange Should Not Replace Constraints

Onchange improves the user interface, but it:

  • Can be bypassed
  • Does not run during imports or backend writes
  • Should never be trusted for data integrity

In Odoo 19, you can use @api.onchange with multiple fields to create responsive, user-friendly forms. Simultaneously listening to multiple fields allows you to manage UI behavior, validations, and dynamic computations while keeping your business logic clear and manageable.

To read more about Overview of Onchange Methods in Odoo 19, refer to our blog Overview of Onchange Methods in Odoo 19.


Frequently Asked Questions

Can I use the same field with more than one onchange method?

Yes, but in order to increase readability and prevent conflicts, it is advised to combine related logic into a single method.

Does onchange work in tree or kanban views?

No. @api.onchange works only in form views.

Will onchange trigger when values are set programmatically?

No. It triggers only when fields are changed manually in the UI.

Can I return warnings from an onchange method?

Yes. You can return a dictionary with a warning key to display alert messages.

Is onchange executed on record creation?

It executes during form interaction, not during backend record creation.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, KINFRA Techno Park
Kakkanchery, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message