Enable Dark Mode!
how-to-use-init-hooks-in-odoo-17.jpg
By: Anfas Faisal K

How to Use Init Hooks in Odoo 17

Technical Odoo 17

In Odoo, Init Hooks are essential functions specified as strings in the __init__ file of a module. These functions execute before and after the existing code, allowing developers to customize module behavior during initialization. Init Hooks are defined within the __manifest__ file and are commonly utilized for creating records. In Odoo 17, several types of Init Hooks exist, each serving a specific purpose:

1. pre_init_hook

2. post_init_hook

3. uninstall_hook

4. Post_load hook

1)pre_init_hook

In Odoo, pre_init_hook is one of the init hooks, a mechanism that allows developers to execute specific functions before and after the initialization of a module. The pre_init_hook is particularly useful for performing actions or configurations just before a module is initialized.

In the __init__.py file, you define a function named pre_init_hook. In Odoo, pre_init_hook is one of the initialization hooks, allowing developers to execute specific functions just before the initialization of a module.

Here is an example of defining and using pre_init_hook in an Odoo Module.

In the init.py

from . import models
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 provided code defines a function _pre_init_sale that acts as a pre_init_hook in Odoo. This function checks if the 'sale_management' module is installed before the initialization of another module. If the 'sale_management' module is not installed, it raises a ValidationError with a message indicating that the 'sale_management' module is required for installation. In essence, it ensures a necessary dependency is met before proceeding with the initialization of the current module.

In the __manifest__.py file, you provide metadata about your module. This includes the module's name, version, author, summary, description, dependencies, and any data files associated with the module. Additionally, you specify the pre_init_hook to instruct Odoo to execute a defined function before the module is fully initialized, during the installation process.

{
    'name': "Company Employee",
    'version': "17.0.1.0.0",
    'data': [
        'security/ir.model.access.csv',
        'views/company_empolyee.xml',
    ],
    'pre_init_hook': '_pre_init_sale',
    'installable': True,
    'auto_install': False,
    'application': False,
}

The output of the provided code is that the 'Company Employee' module will only be installed if the 'sale_management' module is already installed. If 'sale_management' is not installed, a ValidationError will be raised, preventing the installation of the 'Company Employee' module until the required dependency is met.

2) post_init_hook

The post_init_hook is a type of init hook in Odoo that is executed after a module is initialized. It allows you to perform specific actions or configurations once the module is installed.

Let's create a simple example to demonstrate the use of post_init_hook in Odoo version 17. We'll use a hypothetical module named 'custom_module' with a model 'custom.employee'. The post_init_hook will be used to create an employee record after the module is initialized.

In the models.py file, you define the structure of your data model. In this case, we're creating a model named CompanyEmployee for managing employee records. The model has fields such as name, phone number, and email. Here's the code:

from odoo import fields, models
class Company(models.Model):
    _name = "company.employee"
    _description = "Company"
    name = fields.Char(string="Name", required=True)
    phone = fields.Char(string="Phone Number")
    email = fields.Char(string="Email", required=True)

This code defines a model named CompanyEmployee with three fields - 'name', 'phone', and 'email'. The model represents the structure of employee records in your Odoo module.

In the __init__.py file, you define a function named post_init_hook. This function will be executed after the module is initialized. Inside this function, you use the Odoo environment (env) to create a sample employee record with predefined values.

from . import models
def create_employees(env):
    env['company.employee'].create({
        'name': 'ABC',
        'phone': '+7865 6675 2341',
        'email': 'abc123@gmail.com'
    })

This function, post_init_hook, is a hook that executes specific actions after the module is initialized. In this case, it creates a sample employee record using the Odoo environment.

In the __manifest__.py file, you provide metadata about your module. This includes the module's name, version, author, summary, description, dependencies, and any data files associated with the module. Additionally, you specify the post_init_hook to instruct Odoo to execute the defined function after the module is installed.

{
    'name': "Company Employee",
    'version': "17.0.1.0.0",
    'data': [
        'security/ir.model.access.csv',
        'views/company_empolyee.xml',
    ],
    'post_init_hook': 'create_employees',
    'installable': True,
    'auto_install': False,
    'application': False,
}

The post_init_hook key indicates that the function named post_init_hook defined in the __init__.py file should be executed after the module is installed.

As a result, upon successful installation of the 'Custom Module', you can expect to find a pre-existing employee record in the 'company.employee' model. This record serves as an illustration of the post_init_hook in action, showcasing how you can automatically populate data during the initialization phase.

3) uninstall_hook

In Odoo, the uninstall_hook is another type of hook that allows developers to execute specific functions just before a module is uninstalled. This hook is useful for performing cleanup actions or handling special scenarios before a module is removed from the system.

Here's an example of defining and using the uninstall_hook in an Odoo module:

from . import models
def _uninstall_hook_sale(env):
    env['ir.model.data'].sudo().search([
        ('module', '=', 'company_employee'),
    ]).unlink()

In this example, the _uninstall_hook_sale function is defined as the uninstall_hook for the 'Company Employee' module. This function performs cleanup actions, such as deleting specific records associated with the module, before the uninstallation process is completed.

Including the uninstall_hook in the module's __manifest__.py file ensures that Odoo executes the specified function just before uninstalling the module, providing an opportunity to handle any necessary cleanup tasks.

{
    'name': "Company Employee",
    'version': "17.0.1.0.0",
    'data': [
        'security/ir.model.access.csv',
        'views/company_empolyee.xml',
    ],
    'uninstall_hook': '_uninstall_hook_sale',
    'installable': True,
    'auto_install': False,
    'application': False,
}

In summary, the uninstall_hook in Odoo allows developers to execute custom logic or cleanup actions just before a module is uninstalled, contributing to a smoother uninstallation process.

4) Post_load hook

This action can be performed before the initialization of any model or data, which is acceptable since the post-load hook is designed for server-wide functionality rather than being specific to a particular registry. Monkey patches often leverage these functions, allowing for broader and server-wide modifications rather than registry-specific changes.

If you're interested in implementing monkey patching in Odoo, you can refer to the example provided in the following link:  Monkey Patching. This example demonstrates how to utilize the post-load hook for server-wide functionality, making it a valuable resource for understanding and implementing monkey patching in your Odoo projects."

Conclusion:

In summary, Odoo 17's Init Hooks, including pre_init_hook, post_init_hook, uninstall_hook, and Post_load hook, offer developers a versatile means to tailor module behavior during initialization. These hooks empower developers to enhance customization, ensuring modules align seamlessly with specific business needs. Understanding and proficiently utilizing these Init Hooks contribute to an efficient and flexible Odoo development process. If you want to know more about How to use init hooks in odoo , refer to our previous blog.


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



0
Comments



Leave a comment



whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, 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