Server Action in Odoo

Abid Patel
25-Oct-2024 Updated : 25-Oct-2024

Discover how to use Server Actions in Odoo to automate tasks and execute server-side logic with Python code efficiently.

Server Action in Odoo

In Odoo, Server Actions are essential for automating tasks and executing server-side logic without extensive coding. Using Server Actions, you can trigger Python code to perform operations in response to certain events in your Odoo applications.

Understanding Server Actions

A Server Action is a model defined by ir.actions.server, which allows you to execute specific actions on records. This feature is particularly useful for automating repetitive tasks, such as sending emails, updating records, or running complex business logic based on certain conditions.

Creating a Server Action

To create a Server Action in Odoo, follow these steps:

  1. ▹ Navigate to Settings > Technical > Actions > Server Actions.
  2. ▹ Click on Create to start a new Server Action.
  3. ▹ Fill in the required fields:
    • Name: Enter a descriptive name for your action.
    • Model: Choose the model on which the action will be applied.
    • Action Type: Select Python Code for executing custom scripts.
    • Python Code: Write the code you want to execute.

Example: Updating a Field

Here is a simple example of a Server Action that updates a field:

xml
<record id="update_field_action" model="ir.actions.server">
    <field name="name">Update Field Action</field>
    <field name="model_id" ref="model_your_model_name"/>
    <field name="state">code</field>
    <field name="code">for record in records:
        record.field_name = 'New Value'
    </field>
</record>

Example: Sending Email Notifications

You can also create a Server Action to send email notifications. Here’s how you can set it up:

xml
<record id="send_email_action" model="ir.actions.server">
    <field name="name">Send Email Notification</field>
    <field name="model_id" ref="model_your_model_name"/>
    <field name="state">code</field>
    <field name="code">template_id = env.ref('your_module.email_template_id').id
    if template_id:
        mail_template = env['mail.template'].browse(template_id)
        mail_template.send_mail(record.id, force_send=True)
    </field>
</record>

Conclusion

Server Actions in Odoo are a powerful tool for automating tasks and executing server-side logic efficiently. By using the ir.actions.server model, you can streamline processes, enhance application functionality, and improve overall productivity in your Odoo instance.

Make a Comment

Your email address will not be published. Required fields are marked *