In Odoo 18, Init Hooks remain a key feature for developers, enabling the execution of specific functions before and after module initialization. These hooks are essential for customizing the behavior of modules during installation, update, or uninstallation. Like in previous versions, Odoo 18 provides several types of Init Hooks, each with a distinct role:
Types of Init Hooks in Odoo 18:
1. pre_init_hook
2. post_init_hook
3. uninstall_hook
4. post_load hook
1) pre_init_hook
The pre_init_hook is a function executed just before the module initialization begins. This hook is useful for preparing data or configurations that the module needs before its installation. For example, you might use it to create or modify tables or adjust configurations that must exist prior to the main installation.
To define a pre_init_hook, you need to:
* Create the hook function in your module's Python files.
* Reference it in the module's __manifest__.py.
# In __init__.py
from . import models
from odoo.exceptions import AccessError, UserError, ValidationError
def _pre_init_sale(env):
sale_management_installed = env['ir.module.module'].search([
('name', '=', 'sale_management'),
('state', '=', 'installed')
])
if not sale_management_installed:
raise ValidationError("The 'sale_management' module is required for installation.")
The code defines a function called _pre_init_sale, which is used as a pre_init_hook in Odoo. This function ensures that the 'sale_management' module is installed before proceeding with the initialization of another module. If the 'sale_management' module is not present, a ValidationError is triggered, displaying a message to indicate that the 'sale_management' module is required. This check ensures that critical dependencies are in place before the module can be initialized.
In the __manifest__.py file, metadata about the module is provided, including the module's name, version, author, summary, description, dependencies, and related data files. Additionally, the pre_init_hook is specified in the manifest to make sure that the defined function is executed during the installation process, before the module is fully initialized.
{
'name': "Company Employee",
'version': "18.0.1.0.0",
'data': [
'views/company_empolyee.xml',
],
'pre_init_hook': '_pre_init_sale',
'installable': True,
'auto_install': False,
'application': False,
}
The result of the given code is that the 'Company Employee' module will only be installed if the 'sale_management' module is present. If the 'sale_management' module is missing, the code will raise a ValidationError, blocking the installation of the 'Company Employee' module until the necessary dependency is fulfilled.
2) post_init_hooks
The post_init_hook in Odoo is a special type of initialization hook that runs after a module is installed, allowing you to set up certain actions or configurations upon installation. This guide demonstrates how to use post_init_hook in Odoo 18 with a sample module named 'custom_module' that includes a model called company.employee. The post_init_hook will create an initial employee record as part of the module setup.
Step 1: Define the Model in models.py
To start, define the data model. In this example, we create a model named CompanyEmployee to manage employee information, including fields for name, phone number, and email.
from odoo import fields, models
class Company(models.Model):
"""
This model represents company employees and their contact information.
The model stores basic employee information including their name,
phone number, and email address. It is designed to maintain a
centralized database of employee contact details.
"""
_name = "company.employee"
_description = "Company"
name = fields.Char(
string="Name",
required=True,
help="Enter the full name of the employee"
)
phone = fields.Char(
string="Phone Number",
help="Contact number of the employee (optional)"
)
email = fields.Char(
string="Email",
required=True,
help="Professional email address of the employee"
)
This code establishes a model with three fields: name, phone, and email. It represents the structure of employee records within the module.
Step 2: Set Up the post_init_hook in __init__.py
Next, create the post_init_hook function, which will execute after the module is initialized. Here, it will add a sample employee record to the database using predefined values.
# In __init__.py
from . import models
def create_sample_employee(env):
env['company.employee'].create({
'name': 'ABC',
'phone': '+7865 6675 2341',
'email': 'abc123@gmail.com'
})
This function, create_sample_employee, takes advantage of the Odoo environment (env) to create a new record in the company.employee model with sample data.
Step 3: Configure post_init_hook in __manifest__.py
Finally, configure your module's manifest file to include metadata and set the post_init_hook. This lets Odoo know to execute the function after module installation.
{
'name': "Custom Module - Company Employee",
'version': "18.0.1.0.0",
'summary': "Module to manage employee records",
'data': [
'security/ir.model.access.csv',
'views/company_employee.xml',
],
'post_init_hook': 'create_sample_employee',
'installable': True,
'auto_install': False,
'application': False,
}
Here, the post_init_hook key instructs Odoo to run the create_sample_employee function immediately after module installation.
Once the module is installed, you should see a pre-populated employee record in the company.employee model, demonstrating how the post_init_hook can be used to initialize data as part of the installation process in Odoo 18.
3) uninstall_hook
In Odoo, the uninstall_hook is a valuable feature that enables developers to execute specific actions just before a module is uninstalled. It’s helpful for performing cleanup operations or managing particular conditions before the module is fully removed from the system.
Below is an example of how to define and use an uninstall_hook in an Odoo 18 module.
Step 1: Define the Uninstall Hook in __init__.py
To implement the uninstall_hook, start by creating a function that will handle any necessary cleanup tasks, such as deleting records related to the module. Here, the example function removes specific records in the ir.model.data model associated with the module.
from . import models
def _uninstall_hook_cleanup(env):
# Remove records associated with this module
env['ir.model.data'].sudo().search([
('module', '=', 'company_employee'),
]).unlink()
This function, _uninstall_hook_cleanup, finds all records in the ir.model.data table that belong to the company_employee module and deletes them. This approach ensures that any data created by the module is cleaned up upon uninstallation.
Step 2: Set Up the Uninstall Hook in __manifest__.py
In the module's manifest file, specify the uninstall_hook to ensure Odoo runs the function before uninstallation.
{
'name': "Company Employee",
'version': "18.0.1.0.0",
'summary': "Module to manage company employee records",
'data': [
'security/ir.model.access.csv',
'views/company_employee.xml',
],
'uninstall_hook': '_uninstall_hook_cleanup',
'installable': True,
'auto_install': False,
'application': False,
}
Here, the uninstall_hook key instructs Odoo to execute the _uninstall_hook_cleanup function before the module is uninstalled.
When the module is uninstalled, the uninstall_hook is triggered, executing any cleanup tasks defined in _uninstall_hook_cleanup. This feature helps maintain data integrity by ensuring no residual data remains, leading to a smoother uninstallation process in Odoo 18.
4) Post_load hook
In Odoo, the post_load hook is an initialization hook that is triggered before any model or data is fully initialized. This hook is particularly useful for implementing server-wide changes that apply across all registries. It’s often used for scenarios like monkey patching, where you want to modify or extend core functionality globally within Odoo.
For example, the post_load hook can be leveraged to implement monkey patches that affect multiple models or add functionality that operates at a server-wide level. This capability makes post_load ideal for modifications that don’t depend on a specific module’s registry.
Implementing Monkey Patching with post_load Hook
Using the post_load hook for monkey patching allows you to alter Odoo's default behaviors globally. For example, you might want to extend a method in a core model across the entire Odoo server, affecting any instance where the model is used. You can find a guide on how to implement monkey patching in Odoo by reading this blog What is Monkey Patching & How It Can Be Applied in Odoo 17.
Conclusion
In summary, Odoo 18's initialization hooks—pre_init_hook, post_init_hook, uninstall_hook, and post_load—offer developers flexible options for customizing module behavior during various stages of initialization. These hooks enable developers to tailor modules closely to specific requirements, enhancing both customization and functionality. Mastering these hooks contributes to a more efficient and adaptable Odoo development workflow.
To read more about How to Use Init Hooks in Odoo 17, refer to our blog How to Use Init Hooks in Odoo 17.