Technical

OWL in Odoo for Backend Developers: Components, Hooks, Patching

A practical introduction to OWL, Odoo's frontend framework, written for Python developers. It covers components, hooks, services and patching, and builds a small field widget step by step.

Kalvyai Engineering · · Updated · 6 min read

OWL in Odoo for Backend Developers: Components, Hooks, Patching (cover)
On this page

If you write Odoo modules in Python, you can get a long way with models, views and server actions. Sooner or later a request comes in that XML views cannot handle: a custom input, a button that calls the server without a page reload, or a small change to how an existing form behaves. That work happens in OWL, the Odoo Web Library.

This post explains OWL in terms a backend developer already knows, then builds a small field widget you can drop into a form view.

The code targets Odoo 17. Where Odoo 16 differs, we say so. If you are on Odoo 18 or later, check the import paths against your version's source before copying.

The mental model: OWL mapped to things you already know

OWL is a component framework, similar in spirit to React or Vue, but built by Odoo and used for the whole web client since Odoo 16 (OWL 2).

A rough translation table:

Backend concept

OWL equivalent

A Python model class

A component class

A QWeb server template

An OWL template (also QWeb syntax, rendered in the browser)

_inherit on a model

patch() on a component

View inheritance with xpath

Template inheritance with t-inherit and xpath

self.env['model']

The orm service

Registries of models

JavaScript registries (fields, services, actions, and more)

The big difference: templates run in the browser and re-render when data changes. You do not build HTML strings. You describe what the UI should look like for a given state, and OWL updates the DOM.

Where the files go

Frontend code lives in your module's static/src folder and is loaded through asset bundles declared in the manifest.

Plain text
my_module/
├── __manifest__.py
├── views/
│   └── my_model_views.xml
└── static/
    └── src/
        └── int_stepper/
            ├── int_stepper.js
            ├── int_stepper.xml
            └── int_stepper.scss
Python
{
    "name": "My Module",
    "depends": ["web"],
    "data": ["views/my_model_views.xml"],
    "assets": {
        "web.assets_backend": [
            "my_module/static/src/int_stepper/*",
        ],
    },
}

web.assets_backend is the bundle for the backend web client. JavaScript, XML templates and SCSS in that list are all loaded together. After changing the manifest, upgrade the module; after changing only JS or XML, a browser refresh in debug mode with assets (?debug=assets) is usually enough.

Components

A component is a JavaScript class with a template. The smallest useful one looks like this:

JavaScript
/** @odoo-module **/
import { Component } from "@odoo/owl";

export class Hello extends Component {
    static template = "my_module.Hello";
    static props = {
        name: { type: String },
    };
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
    <t t-name="my_module.Hello">
        <div class="o_hello">Hello, <t t-esc="props.name"/></div>
    </t>
</templates>

Three things to notice:

  1. static template points to a template name. Prefix it with your module name to avoid collisions.
  2. static props declares what the parent passes in. In debug mode OWL validates props and throws a clear error if one is missing or has the wrong type. Treat it like field definitions on a model.
  3. `/ @odoo-module /` marks the file as an ES module for Odoo's asset system. Recent versions treat files in static/src as modules by default, but the comment is harmless and keeps older versions happy.

On Odoo 16, backend templates may also need owl="1" on the t-name element to be compiled as OWL templates. From Odoo 17 this is no longer required.

Inside templates, this is the component instance, so getters and methods on the class are available directly. Event handlers use t-on-<event>:

XML
<button t-on-click="() => this.change(1)">+</button>

Hooks

Hooks are functions you call inside a component's setup() method. setup() is OWL's equivalent of a constructor. Do not override constructor; use setup().

The hooks you will use most:

  • useState(obj): returns a reactive object. When you change a property, the component re-renders.
  • onWillStart(fn): runs before the first render. It can be async, so it is the place to load data.
  • onMounted(fn) and onWillUnmount(fn): run after the component is in the DOM and before it is removed. Use them for event listeners or third-party libraries.
  • useRef(name): gives access to a DOM element marked with t-ref="name" in the template.
  • useService(name): an Odoo hook (not part of core OWL) that gives you a service.

Here is a component that loads five companies before rendering:

JavaScript
/** @odoo-module **/
import { Component, useState, onWillStart } from "@odoo/owl";
import { useService } from "@web/core/utils/hooks";

export class CompanyList extends Component {
    static template = "my_module.CompanyList";
    static props = {};

    setup() {
        this.orm = useService("orm");
        this.state = useState({ partners: [] });

        onWillStart(async () => {
            this.state.partners = await this.orm.searchRead(
                "res.partner",
                [["is_company", "=", true]],
                ["name"],
                { limit: 5 }
            );
        });
    }
}

The rule backend developers trip over: hooks must be called synchronously inside setup(), not inside a click handler or an await. Call useService once in setup(), store the result on this, and use it later.

Services

Services are long-lived singletons shared by the whole web client. They are registered in registry.category("services") and reached with useService. You will mostly use the ones Odoo already provides:

  • orm: talks to models. searchRead, read, create, write, unlink, and call for any public model method.
  • notification: shows toast messages. this.notification.add("Saved", { type: "success" }).
  • action: runs actions, like doAction in Python returning an action dict.
  • dialog: opens dialogs.

Calling a Python method from JavaScript:

JavaScript
const result = await this.orm.call(
    "sale.order",
    "action_my_custom_check",
    [[orderId]]
);

On the Python side, action_my_custom_check is a normal model method. Access rights and record rules apply exactly as they would for any RPC call, so do not rely on the frontend to enforce security.

You can write your own service when several components need shared state or a shared connection. For a single widget, it is usually unnecessary.

Example: an integer stepper field widget

Let us build a widget for integer fields: minus and plus buttons around the value, with an optional maximum set from the view. It uses a component, a getter, a service and Odoo's field registry.

Step 1: the component

JavaScript
/** @odoo-module **/
import { Component } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { standardFieldProps } from "@web/views/fields/standard_field_props";

export class IntStepper extends Component {
    static template = "my_module.IntStepper";
    static props = {
        ...standardFieldProps,
        max: { type: Number, optional: true },
    };

    setup() {
        this.notification = useService("notification");
    }

    get value() {
        return this.props.record.data[this.props.name] || 0;
    }

    async change(delta) {
        const next = this.value + delta;
        if (next < 0) {
            return;
        }
        if (this.props.max !== undefined && next > this.props.max) {
            this.notification.add(`The maximum is ${this.props.max}.`, {
                type: "warning",
            });
            return;
        }
        await this.props.record.update({ [this.props.name]: next });
    }
}

export const intStepper = {
    component: IntStepper,
    supportedTypes: ["integer"],
    extractProps: ({ options }) => ({ max: options.max }),
};

registry.category("fields").add("int_stepper", intStepper);

What is going on:

  1. standardFieldProps gives the props every field widget receives, including record, name and readonly.
  2. The value is read from this.props.record.data, not stored in local state. The record is the single source of truth, and the form's save and discard buttons keep working.
  3. record.update() marks the record dirty, exactly like typing into a normal input.
  4. extractProps turns the options attribute from the XML view into a prop.
  5. Registering under "int_stepper" makes widget="int_stepper" available in views.

On Odoo 16 the field registry takes the component class directly, with supportedTypes and extractProps as static members. The object form shown above is the Odoo 17 style.

Step 2: the template

XML
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
    <t t-name="my_module.IntStepper">
        <div class="o_int_stepper d-flex align-items-center gap-2">
            <button t-if="!props.readonly" type="button"
                    class="btn btn-sm btn-secondary"
                    t-on-click="() => this.change(-1)">-</button>
            <span class="o_int_stepper_value" t-esc="value"/>
            <button t-if="!props.readonly" type="button"
                    class="btn btn-sm btn-secondary"
                    t-on-click="() => this.change(1)">+</button>
        </div>
    </t>
</templates>

type="button" keeps the browser from treating the click as a form submit.

Step 3: a little style

CSS
.o_int_stepper .o_int_stepper_value {
    min-width: 2rem;
    text-align: center;
}

Save this as int_stepper.scss; plain CSS is valid SCSS.

Step 4: use it in a view

XML
<record id="my_model_view_form" model="ir.ui.view">
    <field name="name">my.model.form</field>
    <field name="model">my.model</field>
    <field name="arch" type="xml">
        <form>
            <sheet>
                <group>
                    <field name="box_count" widget="int_stepper"
                           options="{'max': 10}"/>
                </group>
            </sheet>
        </form>
    </field>
</record>

Upgrade the module, open a record, and the field shows the stepper. Readonly fields show only the value.

Patching an existing component

Custom widgets cover new UI. Changing Odoo's own UI is done by patching, which is the frontend equivalent of _inherit.

Patching behaviour

JavaScript
/** @odoo-module **/
import { patch } from "@web/core/utils/patch";
import { FormController } from "@web/views/form/form_controller";
import { useService } from "@web/core/utils/hooks";

patch(FormController.prototype, {
    setup() {
        super.setup(...arguments);
        this.notification = useService("notification");
    },

    // Check this hook name in form_controller.js for your version.
    async onRecordSaved(record) {
        const result = await super.onRecordSaved(...arguments);
        if (this.props.resModel === "my.model") {
            this.notification.add("Record saved.", { type: "success" });
        }
        return result;
    },
});

The Odoo 17 syntax uses super, as shown. Odoo 16 used a different signature: patch(Target.prototype, "my_module.unique_name", { ... }) with this._super(...arguments). This is one of the most common breakages when moving custom modules from 16 to 17.

Two habits that save time:

  1. Read the source first. Open the original file under addons/web/static/src and find the exact method you want to extend. Method names and signatures change between versions.
  2. Scope your patch. A patch on FormController affects every form in the system. Guard it with a check like resModel so it only runs where you intend.

Patching the template

To change markup, inherit the template with an xpath, the same way you inherit an XML view:

XML
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
    <t t-inherit="your_module.TemplateToExtend"
       t-inherit-mode="extension">
        <xpath expr="//div[hasclass('o_target')]" position="after">
            <span class="o_my_note">Extra content here</span>
        </xpath>
    </t>
</templates>

Find the template name in the component's static template line, then read the template XML to write the xpath. Keep xpaths short and anchored on stable class names; long positional paths break on upgrades.

Debugging tips

  • Use ?debug=assets so the browser loads unminified files with real line numbers.
  • Prop validation errors only appear in debug mode. Turn it on while developing.
  • If your widget does not appear, check the browser console first. A typo in an import path stops the whole file from loading, and often the whole bundle.
  • If widget="int_stepper" silently falls back to the default widget, check that the field type is in supportedTypes and that your file is listed in the right asset bundle.

Keeping OWL code upgrade-friendly

Frontend customisations are usually the first thing to break on a version upgrade, because the web client internals move faster than the ORM. A few rules help:

  • Prefer new field widgets over patches when you can. A widget only depends on the field API.
  • Keep patches small and call super every time.
  • Put the module and version in comments next to any xpath or overridden method you copied from core.

When a version upgrade does arrive, our Upgrade Autopilot app moves custom Odoo apps to the next version, automatically upgraded and tested.

How Kalvyai can help

We build Odoo modules end to end, including OWL widgets, patched views and the Python behind them. If you need a custom frontend feature, or need existing customisations moved to a newer Odoo version, see our Odoo services or browse our ready-made apps at store.kalvyai.com. To talk through a specific project, contact us.

Share this article

Last updated 28 Nov 2026

  • Odoo
  • OWL
  • JavaScript
  • Odoo Development
  • Frontend
  • Field Widgets

Kalvyai Engineering · Engineering team

The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.

Comments

No comments yet. Questions and corrections are welcome.

Rate this post or leave a comment

Your rating (optional)
Not rated

Comments appear after an editor approves them. See our privacy notice.

Read next

WhatsApp Coexistence for Odoo 19: Setup and User Guide (cover)User guide
Kalvyai EngineeringOdoo

WhatsApp Coexistence for Odoo 19: Setup and User Guide

How to install, connect and use WhatsApp Coexistence for Odoo 19 so your team keeps replying from the WhatsApp Business app while Odoo logs every message on the same number.

7 min read

Newsletter

Get new guides in your inbox.

Practical notes on Odoo, ERPNext, Shopify and AI agents, written by the engineers who build them. No spam, and you can ask to stop at any time.

Prefer a feed? Subscribe by RSS. We use your email only to send new articles. See our privacy policy.