how-to-dynamically-execute-python-code-when-a-form-loads-in-odoo-18

How to Dynamically Execute Python Code When a Form Loads in Odoo 18

Python has become one of the most popular programming languages due to its simplicity, versatility, and ease of integration into various platforms. In Odoo, Python is central to customizing the platform and automating tasks, making it more efficient for businesses to personalize their systems to meet specific needs.

But what happens when you need a form in Odoo to load dynamically based on the user, their role, or any specific condition? This is where the get_views() method in Odoo 18 comes into play.

In this post, we’ll explore how to execute Python code when a form is loaded, making the Odoo experience more dynamic and personalized.

Executing Python Code When a Form Loads in Odoo 18

In earlier versions of Odoo, developers commonly used the fields_view_get() method to execute Python logic whenever a form was loaded. This method dynamically customised views by altering their structure or injecting specific logic. However, starting from Odoo 16, this method was deprecated, and the get_views() method was introduced to achieve the same functionality with enhanced flexibility.

With get_views(), developers can now handle multiple view types, form, tree, and kanban, at once and apply more conditional logic efficiently.

Why Switch to get_views() Method?

Odoo’s evolution from fields_view_get() to get_views() was driven by the need to provide a more robust and modular approach to view management. The get_views() method allows developers to:

  1. Multiple Views at Once: With a single override, you can modify a form, tree, kanban, or any view simultaneously.
  2. Conditional Logic: This allows for more robust customization, customizing views depending on user roles, departments, or custom fields.
  3. Better Performance: get_views() improves Performance, especially when working with large datasets, by reducing unnecessary calls and enhancing flexibility.

Using get_views() is essential for ensuring that your customizations are not only forward-compatible with Odoo’s updates but also cleaner and more efficient.

Overview of get_views()

The get_views() method is a powerful feature introduced in Odoo 16 and further refined in Odoo 18. It is designed to help developers dynamically customize views based on specific conditions, whether it’s a form, tree, kanban, or any other view type. 

The get_views() method is invoked when a model’s views are loaded. You can override this method in your model to inject custom Python logic and dynamically modify the view based on certain conditions.

By overriding get_views(), you can tap into Odoo’s best architecture and create a more intuitive and context-sensitive user experience.

				
					Method Signature:
def get_views(self, views, options=None):

    # Custom logic

    return super().get_views(views, options)
				
			

Implementing Get_views() in Odoo 18

Now that we understand the basics of the get_views() method. Let’s walk through an example where we customize a form view dynamically based on the user’s branch.

Use Case: Show/Hide Fields Based on User’s Branch

In many businesses, different branches or departments may require distinct sets of information. For instance, a field may need to be visible to users from one branch but hidden from others. In this example, we’ll show or hide a specific field on the form depending on the branch the logged-in user is associated with.

This is a perfect use case for get_views(), as it allows us to conditionally adjust the form’s layout as it’s being loaded without requiring users to refresh the page or interact with complex UI elements.

				
					from odoo import models, fields, api
class CustomModel(models.Model):
    _name = 'custom.model'
    _description = 'Custom Model Example'

    name = fields.Char(string="Name")
    branch_specific_field = fields.Char(string="Branch Specific Field")

    @api.model
    def get_views(self, views, options=None):
        res = super(CustomModel, self).get_views(views, options)
        
        # Get the current user's branch
        user_branch = self.env.user.branch_id
        
        # Check if the current view is a form view
        if views.get('form'):
            arch = res['views']['form']['arch']
            
            # Modify the form view dynamically based on the branch
            if user_branch.code == 'BRANCH_01':
                # Add or modify the XML to include a specific field
                arch = arch.replace('<field name="name"/>',
                                    '<field name="name"/><field name="branch_specific_field"/>')
            
            res['views']['form']['arch'] = arch
        return res

				
			

How the code works : 

    1. Override get_views(): We override the method in our model to inject custom logic when the views are loaded.
    2. Access the User’s Branch: Using self.env.user.branch_id, we fetch the current user’s branch.
    3. Modify the Form View: We dynamically update the form view to include or exclude specific fields based on the branch.

    The arch variable represents the XML structure of the form view. It defines the layout and fields displayed to the user, which we modify dynamically based on the user’s branch.

    Advantages of get_views()

      1. Dynamic View Customization: Custom views dynamically based on user roles, conditions, or preferences.
      2. Improved Performance: Fetch and modify multiple views in a single call.
      3. Future-Proof: Aligns with Odoo’s modern architecture, ensuring compatibility with newer versions.
      4. Modularity and maintainability enable easier management and updating of customizations in large-scale Odoo projects.

      Best Practices for Using get_views()

        1. Avoid Overloading the Method: Only apply the logic necessary for view customization. Complex logic can slow down the view rendering.
        2. Test Thoroughly: Since get_views() is invoked every time a view is loaded, ensure your modifications don’t introduce errors or conflicts.
        3. Use Modular Logic: Keep your modifications modular and reusable.

        We can conclude like:

        The get_views() method in Odoo 18 offers a powerful way to execute Python code when forms (or other views) are loaded. While it replaces the deprecated fields_view_get() method, it provides enhanced functionality, enabling developers to handle multiple views simultaneously.

        By Utilizing get_views(), you can create dynamic and user-specific experiences in your Odoo applications. Whether you need to conditionally display fields, add new elements, or transform views, this method equips you with the tools to achieve it effectively.

        With Odoo’s continuous evolution, adopting modern practices like get_views() ensures that your customizations remain compatible with future versions.
        Happy coding!

        Picture of Lakshmi R Nair

        Lakshmi R Nair

        I’m Lakshmi R Nair, a Junior Odoo Developer passionate about Odoo ERP development, customization, and integration. I love problem-solving and exploring new advancements in Odoo and open-source technologies. Here, I share my insights and experiences to help others in the ERP ecosystem.

        Get a free quote