Welcome to this tutorial on Odoo search view customization. In this post, we explain how to set a default filter in an Odoo search view using XML code. We use key phrases such as “default filter”, “Odoo search view”, and “preset filter” throughout this article. You will learn to implement a default search filter with active, clear examples and detailed explanations. Additionally, we provide external resources such as the Odoo Developer Documentation for further studies and reference.
Introduction to Default Filters in Odoo
In this tutorial, we discuss how to enhance your Odoo search view with a default filter. We begin by explaining the importance and benefits of using a default filter in an Odoo search view. You will discover that a default filter makes it easier for users to access specific records automatically, thereby improving the user experience. Moreover, we design the code using XML snippets and provide detailed explanations for every section.
First, you must know that utilizing default filters ensures that your application displays records that meet preset criteria by default. Consequently, users save time as they do not have to manually select options to filter data. In this post, we show you how to implement default filtering in your Odoo views consistently, step by step.
Understanding the Basics: Odoo Search View and Default Filters
When you work with Odoo, the search view is crucial because it organizes how data is filtered and presented. Let’s examine some key concepts:
- Odoo Search View: This view defines the available search fields and filters for a given model. Setting a default filter ensures that a specific set of records appears when the user opens the view.
- Default Filter: A preset condition that applies immediately when a user accesses the view. This reduces redundant actions for users and drives focus on the most important information.
Additionally, you benefit from using familiar terms and shorter sentences. For example, using terms such as “preset filter” and “default search” improves readability and makes the code more accessible to newcomers.
Transitioning from theory to practice, we now delve into the steps required to add a default filter to an Odoo search view. We examine a sample XML file that defines the search view configuration and default context settings.
Step-by-Step Tutorial with XML Code
Below is the complete XML code that sets a default filter in an Odoo search view. We will explain every part in detail so that you can replicate the process in your own project.
<record id="wb_student_search_view" model="ir.ui.view">
<field name="name">wb.student.search.view</field>
<field name="model">wb.student</field>
<field name="arch" type="xml">
<search>
<!-- Predefined filters for dynamic date ranges -->
<filter name="30_days" string="30 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=30), None))]"/>
<filter name="7_days" string="7 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=7), None))]"/>
<filter name="14_days" string="14 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=14), None))]"/>
<!-- Search fields for filtering records -->
<field name="name"/>
<field name="school_id"/>
<!-- Additional filters using default criteria -->
<filter name="school_name" domain="[('school_id.name', 'ilike', 'sunny')]" string="School Sunny"/>
<filter name="student_name" domain="[('name', 'ilike', 'sunny')]" string="Sunny Student"/>
<filter name="gender_male_filter" domain="[('gender', '=', 'male')]" string="Male Students"/>
<filter name="gender_female_filter" domain="[('gender', '=', 'female')]" string="Female Students"/>
<!-- Grouping filters for better search organization -->
<group>
<filter name="gender_filter"
context="{'group_by': 'gender'}"
domain=""
string="Gender"/>
<filter name="school_groupby"
context="{'group_by': 'school_id'}"
string="School"/>
</group>
</search>
</field>
</record>
<record id="wb_student_action" model="ir.actions.act_window">
<field name="name">Student</field>
<field name="res_model">wb.student</field>
<field name="view_mode">list,form</field>
<field name="context">
{'search_default_student_name': 1,
'search_default_gender_groupby': 1}
</field>
</record>
Detailed Explanation
- Record Definition for Search View:
We create a record withid="wb_student_search_view"in their.ui.viewmodel. This record defines the search view for thewb.studentmodel. In every case, we keep our XML tags properly closed and structured. - Search Filters:
Inside the<search>tag, we define various<filter>elements. Transition words such as “first” and “next” help in guiding step-by-step:- The filters for “30 Days”, “7 Days”, and “14 Days” allow for dynamic filtering based on the date.
- We specify fields such as
<field name="name"/>and<field name="school_id"/>to include them in the search form. - We add named filters that match criteria, for instance, filtering students whose school name or student name contains the substring “sunny”.
- Gender filters separate male and female students.
- Grouping Filters:
We group similar filters to make the search view cleaner. The<group>element contains filters that enable grouping by gender and school. This grouping allows Odoo to automatically apply a context grouping to the view. - Action Record Settings:
The second record defines an action (wb_student_action) that opens the student records. Notice how we specify the default context filter using:'search_default_student_name': 1, 'search_default_gender_groupby': 1This ensures that when you open the view, Odoo applies these default filters immediately.
Each snippet of code uses active voice and transitions like “first”, “next”, and “then” to create a smooth guide for developers.
Customizing Your Odoo Search View: Best Practices
It is essential to build maintainable and user-friendly views. Therefore, while creating default filters, follow these best practices:
- Keep It Simple:
Use a clear and straightforward approach when defining XML attributes. For example, useilikefor case-insensitive search and avoid overly complex domain filters. - Test Consistently:
Make sure to test your search view after adding new filters. Use Odoo’s debug mode to check if the default filter applies automatically. - Group Filters Logically:
Organize related filters into groups for a cleaner interface. For instance, you can group date filters, text filters, and relational filters separately to enhance the user experience. - Use Standard Naming Conventions:
Name your filters and records in a consistent manner. This minimizes confusion and helps you maintain your module in the long run. - Leverage External Tools:
Use the Odoo Developer Documentation and community forums. Additionally, resources such as the Odoo Help Forum provide valuable insights into advanced customization.
By following these practices, you will create robust and readable XML code for default filters in your Odoo environment.
Advanced Customization Techniques
In addition to implementing default filters, you can extend your Odoo search view by adding more complex domain filters. Let’s consider several customization ideas:
Using Dynamic Date Ranges
Rather than using static values for date filters, you can implement dynamic date ranges. For example, you may want to filter records based on the last 15 days instead of 7 or 30 days. Adjust the relativedelta value accordingly:
<filter name="15_days" string="15 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=15), None))]"/>
Transition words such as “alternatively”, “furthermore”, and “in addition” help make these instructions clear.
Combining Filters for Complex Searches
You can combine multiple filters to create complex search domains. For instance, you might combine a default filter that searches for “sunny” and another that filters by gender. This approach increases modularity and gives users a powerful search tool. Always consider performance when combining multiple filters; test them in your development environment before deploying live.
Enhancing Readability Through Comments
Adding comments to your XML code is a best practice. Comments clarify your logic for other developers and for your future self. In the provided XML code, notice that we add inline comments above each filter definition. Always include comments for sections that manipulate complex data types.
Incorporating Context for More Advanced Functionality
Sometimes, you might need to pass contextual parameters to your filters. For instance, using context keys like search_default_student_name allows the system to apply the default search filter automatically. This feature facilitates a more dynamic search view that can adapt to user behavior.
Below is an example of how context parameters are defined within an action:
<field name="context">
{'search_default_student_name': 1, 'search_default_gender_groupby': 1}
</field>
This snippet automatically applies the student name filter and groups the results by gender. Transition words like “therefore” and “consequently” underscore the impact of using context in your searches.
Tutorial Walkthrough: Implementing Your First Default Filter
Let’s walk through creating a default filter step by step. Follow these instructions to successfully set up your own default search view in an Odoo module.
Step 1: Define the Search View
First, you create a new XML record in your module directory (usually located at views/your_module_views.xml). You start by setting up the basic structure:
<record id="wb_student_search_view" model="ir.ui.view">
<field name="name">wb.student.search.view</field>
<field name="model">wb.student</field>
<field name="arch" type="xml">
<search>
<!-- Base filter definitions go here -->
</search>
</field>
</record>
Here, you define the search view for the student model. Transition words such as “first” and “next” guide you to add the necessary filters.
Step 2: Add Filters and Fields
Next, you add specific filters to target your use case. For example, you incorporate filters for various time ranges, text searches, and gender classification:
<filter name="30_days" string="30 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=30), None))]"/>
<filter name="7_days" string="7 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=7), None))]"/>
<filter name="14_days" string="14 Days"
domain="[('create_date', '>', datetime.datetime.combine(context_today() - relativedelta(days=14), None))]"/>
<field name="name"/>
<field name="school_id"/>
These filters act as presets for dynamic date ranges and text searches. Transition words help your readers understand that adding each filter enhances the functionality of your search view.
Step 3: Group Related Filters
You then organize the filters into logical groups. Grouping filters makes it easier for users to understand how the search is segmented:
<group>
<filter name="gender_filter"
context="{'group_by': 'gender'}"
domain=""
string="Gender"/>
<filter name="school_groupby"
context="{'group_by': 'school_id'}"
string="School"/>
</group>
This grouping divides the filters by gender and school, making the interface cleaner and more intuitive.
Step 4: Define the Action for Your View
Finally, you add an action record that opens the default view with your settings. This record includes the context that enables the default filtering:
<record id="wb_student_action" model="ir.actions.act_window">
<field name="name">Student</field>
<field name="res_model">wb.student</field>
<field name="view_mode">list,form</field>
<field name="context">
{'search_default_student_name': 1, 'search_default_gender_groupby': 1}
</field>
</record>
When users open the student list view, Odoo automatically applies the predefined filters without extra input from the user.
Step 5: Validate and Test Your Configuration
After implementing the code, restart your Odoo server and upgrade your module. Transition words like “finally” mark the end of the process. Test the search view by navigating to the student view in Odoo. Confirm that the default filter displays the expected records. If necessary, adjust the domain filters or context keys based on user feedback or testing outcomes.
Best Practices in Writing Default Filters for Odoo
When you write XML code for Odoo search views, applying best practices is crucial for creating effective, maintainable modules. Here are some best practices:
- Keep XML Clean and Structured:
Always indent your XML code and add sufficient comments. This practice enhances long-term maintainability and ensures that other developers can understand your logic. - Use Descriptive Names:
Choose meaningful names for filters and groups. For instance, use “gender_filter” for grouping by gender. This reduces confusion and makes your code more self-explanatory. - Test Your Domain Expressions:
Validate your domain expressions by testing them in various user scenarios. Use Odoo’s logging features to check the output of your filters. - Leverage External Documentation:
Utilize resources like the Odoo Developer Documentation and the Odoo Community Association (OCA) guidelines to stay updated with best practices. - Include Context for Flexibility:
Pass context values for dynamic filtering. This enables your views to adapt automatically based on user actions or specific triggers.
By following these practices, you ensure that your default filters in Odoo are robust, flexible, and easy to maintain.
Common Pitfalls and How to Avoid Them
Understanding common pitfalls is essential to avoid mistakes when implementing default filters. Here are some challenges and solutions:
- Incorrect Domain Syntax:
Always ensure that your domain expressions are correctly formatted. For example, using>instead of>is necessary in XML to avoid parsing errors. Transition words such as “remember” and “note” remind you to check these details. - Unclosed XML Tags:
Missing closing tags can cause XML parsing errors. Use an XML validator or integrated development environment (IDE) with XML linting to find these mistakes quickly. - Misconfigured Context:
If default filters do not apply, double-check the context keys in your action record. Changing keys fromsearch_default_student_nameto a different value without updating the view can lead to misconfiguration. - Overcomplicating Filter Logic:
Avoid complex domain statements that are hard to read or maintain. Instead, break them into smaller, manageable filters and group them logically.
By anticipating these issues, you can prevent common mistakes and ensure a smooth implementation process.
Extending the Tutorial: Additional Tips and Enhancements
Once you master the basics of implementing default filters in Odoo, you can experiment with advanced features. Here are a few ideas to further improve your search view:
- Add Conditional Filters:
Use context variables to display different filters based on user roles. For example, administrators might see more detailed filters than regular users. - Integrate with JavaScript:
Enhance the search view by coupling it with custom JavaScript. This integration could provide dynamic filter adjustments or even immediate visual feedback when filters are applied. - Implement Multi-Language Support:
Prepare your XML code to support multiple languages. Use Odoo’s translation features by addingt-translationattributes so that labels and strings appear in the user’s preferred language. - Optimize Performance:
Monitor and optimize the performance of your search view by testing filtered queries on large datasets. Use caching where appropriate and ensure that database indices match your domain filters. - Document Your Code:
As your module grows in complexity, document your code extensively. Include inline comments and create separate documentation files that explain each filter’s purpose, configuration, and expected behavior.
These enhancements can significantly improve the functionality and maintainability of your Odoo search view while also providing users with a better experience.
Practical Use Case: Real-World Scenario in Odoo
Let’s consider a practical scenario. Imagine you have a school management system in Odoo. You want to display a default view that shows only active students registered in the last 30 days. You also want to group the students by gender for quick visual reference. Using the XML code explained in this tutorial, you can implement this feature easily.
When the school administrator logs in, the default filter automatically narrows the student list to recent registrations. The grouping by gender further helps the administrator to quickly analyze the distribution of students, and if any further filtering is necessary, they apply additional filters right away. This real-world application demonstrates the importance of a default filter in simplifying user interaction and empowering administrators with relevant data at a glance.
Code Integration and Deployment Steps
After finalizing the XML code, follow these deployment steps to integrate your custom search view into your Odoo installation:
- Place the XML File:
Save your XML file (e.g.,views/student_search_view.xml) in your custom module’s views directory. - Update the Module Manifest:
Ensure that your module’s__manifest__.pyincludes a reference to the new XML file in thedatasection.{ 'name': "Student Management", 'version': "1.0", 'depends': ['base'], 'data': [ 'views/student_search_view.xml', ], 'installable': True, 'application': True, } - Restart the Odoo Service:
Restart your Odoo server so that the changes take effect. Transition words like “subsequently” and “finally” indicate the end of setup steps. - Upgrade Your Module:
In Odoo, upgrade your module from the Apps menu or using the command line to load the new configuration. - Test the Functionality:
Log in to Odoo under the appropriate user role and navigate to the student search view. Confirm that the default filter and grouping apply as expected.
Following these deployment steps ensures that your new search view settings are integrated correctly into your production environment.
Conclusion
In conclusion, setting a default filter in an Odoo search view optimizes user experience and enhances data presentation. Through this tutorial, you have learned how to create a default filter using XML code, configure context parameters, and group filters logically. We shared practical tips, best practices, and common pitfalls, which should empower you to build sophisticated Odoo search views.
Remember that each filter and grouping statement plays an essential role in tailoring the application to your users’ needs. By incorporating clear, active sentences with transition words, this guide has provided a comprehensive approach that even beginners can follow smoothly.
For more insights and advanced techniques, visit the Odoo Developer Documentation and explore community forums. Apply these default filter settings in your projects and observe the improved efficiency and enhanced usability in your Odoo environment.
Happy coding, and may your Odoo modules run smoothly with well-crafted default filters!
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.

