Enable Dark Mode!
overview-of-context-aware-and-debugging-of-onchange-methods.jpg
By: Anupriya Ashok

Overview of Context-Aware and Debugging of Onchange Methods

Technical Odoo 19 Odoo Enterprises Odoo Community

Odoo 19's context-aware onchange methods dynamically update field values in response to user input and context, and debugging onchange methods use print statements, logs, and developer tools to find problems with real-time field behaviour.

What Are Onchange Methods in Odoo 19?

When a user modifies a field in the form view, Onchange methods are used to automatically update those fields without saving the record to the databases.

Key Features:

  • Triggered instantly on field change
  • Works only in the user interface (form view)
  • Does not store data unless saved

Example:

from odoo import api, fields, models
class Student(models.Model):
   _name = 'school.student'
   age = fields.Integer()
   category = fields.Selection([
       ('minor', 'Minor'),
       ('adult', 'Adult')
   ])
   @api.onchange('age')
   def _onchange_age(self):
       if self.age < 18:
           self.category = 'minor'
       else:
           self.category = 'adult'

What Does Context-Aware Mean in Onchange Methods?

When your onchange method is context-aware, it reads this dictionary and modifies its behavior according to what it discovers.

Without context-awareness:

@api.onchange('partner_id')
def _onchange_partner(self):
   self.note = "Partner selected"

With context-awareness:

@api.onchange('partner_id')
def _onchange_partner(self):
   if self.env.context.get('default_type') == 'sale':
       self.note = "Customer selected in Sales Order"
   elif self.env.context.get('default_type') == 'purchase':
       self.note = "Vendor selected in Purchase Order"

Why Context Matters:

Consider this situation. You have one model — account.move — that is used for both invoices and vendor bills. The form looks similar. But when a user selects a partner on an invoice, you want to set customer-related defaults. When they select a partner on a vendor bill, you want vendor-related defaults.

How is the situation that your single onchange method is in determined? You are not informed by the form itself. The same field name is used. It's the same model.

The answer is context. When Odoo opens an invoice form, it puts {'default_move_type': 'out_invoice'} in the context. When it opens a vendor bill, it puts {'default_move_type': 'in_invoice'}. Your method reads this and behaves differently:

@api.onchange('partner_id')
def _onchange_partner_smart(self):
   move_type = self.env.context.get('default_move_type', '')
   if move_type == 'out_invoice':
       # This is a customer invoice
       self.payment_term_id = self.partner_id.property_payment_term_id
   elif move_type == 'in_invoice':
       # This is a vendor bill
       self.payment_term_id = self.partner_id.property_supplier_payment_term_id

Without context, you would need two separate models or two separate methods. With context, one smart method handles both situations cleanly.

How to Debug Onchange Methods in Odoo 19?

Debugging is essential because onchange methods do not persist data and run only in the UI.

1. Use Logging

import logging
_logger = logging.getLogger(__name__)
@api.onchange('age')
def _onchange_age(self):
   _logger.debug("Age value: %s", self.age)

Check logs in:

  • Terminal
  • Log file

2. Use Print Statements(Quick Testing)

print("Onchange triggered", self.age)

3. Enable Debug Mode in Odoo UI

  • Go to Settings
  • Activate Developer Mode
  • Inspect fields and technical data

Common Issues in Onchange Methods

1. Values Not Updating

Make sure the method is appropriately decorated with @api.onchange and that the field names used inside the method are correct if values are not updating correctly.

2. Data Not Saved

It is crucial to realise that onchange methods do not store values in the database; they only modify values in the user interface. You should use methods like create() or write() to store data.

3. Context Not Working

Verify that the necessary context key is present if the context is not acting as it should. To prevent errors, it is also advised to use.get() when accessing context values.

When Should You Use Onchange?

Use onchange when:

  • You need instant UI updates
  • You want to guide user input
  • You don’t need immediate database storage

Odoo 19's context-aware onchange techniques improve user experience by dynamically modifying form behaviour in response to contextual information and real-time input. They become effective tools for creating responsive and effective applications when paired with appropriate debugging methods like logging and developer mode. Developers can use onchange techniques to produce more intelligent and user-friendly Odoo solutions by adhering to best practices and being aware of their limitations.

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

What distinguishes Odoo's compute and onchange fields?

onchange fields work only in the form view and update values immediately when a user changes another field. These changes are not stored in the database until the record is saved. In contrast, compute fields automatically calculate values based on other fields and can be stored in the database, making them available for backend logic, searches, and reports.

Can onchange methods save data in Odoo?

No, they only make changes to the form view's values. Only when the record is saved is data saved.

How can I troubleshoot a non-triggering onchange?

If an onchange method is not being triggered, first make sure the correct @api.onchange decorator is used. Then verify that the field name inside the decorator matches the actual field in the model. You can also enable debug logs in Odoo to check whether the method is being called.

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