Skip to Content
Odoo Menu
  • Sign in
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Artificial Intelligence
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Property Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

How to reliably auto-fill a Website Form field using URL parameters in Odoo 19

Subscribe

Get notified when there's activity on this post

This question has been flagged
webclientjavascriptdevelopment
4 Replies
1622 Views
Avatar
Brissa Cx, Eliana Bermudez

Hi to all,

I am trying to implement a simple "Lead Source/Interest" capture. When a user clicks a button on my landing page, they are redirected to a registration page with a URL parameter, for example: mywebsite.com/registro?servicio=AgentesIA

The Goal: I want the "Subject" (Asunto) field of the Odoo Website Form to automatically fill with the value "AgentesIA" upon page load.

The Problem: I have tried several JavaScript approaches (using DOMContentLoaded, setInterval to wait for the element, and searching by name, id, and class), but none seem to work reliably.

  1. The field ID often appears as #Field or a generic string that seems to change.

  2. Even when the script finds the input and changes the value, the data is sometimes not captured when the form is submitted unless there is a manual "input" or "blur" event.

  3. The Odoo form seems to be protected or rendered in a way that standard document.querySelector sometimes misses it during the initial load.

Current Script Snippet:

(function() {
    const params = new URLSearchParams(window.location.search);
    let service = params.get('servicio');
    if (service) {
        let attempts = 0;
        const monitor = setInterval(function() {
            let field = document.querySelector("input[name='name']") || 
                        document.querySelector("input[id*='Field']");
            if (field) {
                field.value = service;
                field.dispatchEvent(new Event('input', { bubbles: true }));
                field.dispatchEvent(new Event('change', { bubbles: true }));
                clearInterval(monitor);
            }
            if (attempts > 100) clearInterval(monitor);
            attempts++;
        }, 100);
    }
})();

Question: Is there a "standard" or more "Odoo-friendly" way to achieve this? Should I be using a specific Odoo JS Class or a different selector to ensure the form controller recognizes the injected value?

Any help or pointing to the right documentation would be greatly appreciated!

Thanks in advance!


0
Avatar
Discard
Avatar
Kunjan Patel
Best Answer
Hello Eliana Bermudez,
I hope you are doing well

- The standard way is server-side via data-for use Odoo's native data-for prefill mechanism.
- This is the mechanism Odoo uses internally. The form's prefillValues() method in js reads data-for spans and applies the values during its own initialization.

Code:
Controller:                                                                                                                                                                                 
@http.route('/registro', type='http', auth='public', website=True)
def registro(self, servicio=None, **kwargs):
return request.render('your_module.registro_page', {'servicio': servicio})

Template:
<span t-if="servicio" t-att-data-for="form_id"
t-att-data-values="{'Asunto': servicio}" class="d-none"/>
The key in data-values must match the field's name attribute exactly.
URL: mywebsite.com/registro?servicio=AgentesIA → fills the "Asunto" field.

The form's prefillValues() runs after DOMContentLoaded/load, overwriting any values you set earlier. data-for is read by prefillValues() itself, so it's timing-proof.

I hope this information helps you

Thanks & Regards,
Kunjan Patel
0
Avatar
Discard
Avatar
Brissa Cx, Eliana Bermudez
Author Best Answer

Hi everyone, thanks for the insights!

Following the suggestion regarding the dynamic rendering of the website form controller, I've moved away from simple ID selectors to the more stable data-attribute-name="name" approach. I also understand that the OWL framework might be overwriting the value if the timing isn't perfect.

I’ve implemented a MutationObserver combined with a Native Value Setter to ensure the framework registers the change as a user-initiated event. However, I’m still seeing a 'flicker' where the value is injected but then cleared by Odoo's internal state management.

Below is the current iteration of the script I'm using. I've added a retry burst (polling) to fight against the framework's cleanup. Does anyone have experience with a specific OWL event or a website_form method that should be called to 'commit' this value to the component state properly?

<script>
(function () {
    const DEBUG_TAG = "Brissa AutoFill: ";
    
    const getServiceParam = () => {
        const params = new URLSearchParams(window.location.search);
        return params.get('servicio');
    };

    const fillField = (input, value) => {
        if (!input || !value) return;
        try {
            const decodedVal = decodeURIComponent(value);
            // Native setter bypasses OWL's virtual DOM sync issues
            const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
            valueSetter.call(input, decodedVal);

            // Triggering multiple events to ensure Odoo's controller detects the change
            ['input', 'change', 'blur', 'focusout'].forEach(evt => {
                input.dispatchEvent(new Event(evt, { bubbles: true }));
            });
            console.log(DEBUG_TAG + "Syncing value: " + decodedVal);
        } catch (e) {
            console.error(DEBUG_TAG + "Injection Error", e);
        }
    };

    const findInput = () => {
        // Community recommended stable selector
        return document.querySelector('.s_website_form_field[data-attribute-name="name"] .s_website_form_input') 
               || document.querySelector('input[name="name"]');
    };

    const observer = new MutationObserver((mutations, obs) => {
        const input = findInput();
        const servicio = getServiceParam();

        if (input && servicio) {
            // Burst strategy: fill multiple times during the first 3 seconds
            // to prevent the 'Form Controller' from clearing the input.
            [0, 500, 1000, 2500].forEach(ms => setTimeout(() => fillField(input, servicio), ms));
            
            obs.disconnect(); 
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });
})();
</script>
0
Avatar
Discard
Avatar
Sangar
Best Answer

You’re facing this issue because Odoo website forms are rendered dynamically by the website form controller. Sometimes the form fields are not fully available when your script runs, so the selector either fails or the value is not registered when the form is submitted.

A simpler and more reliable approach is to run the script after the page is fully loaded and select the field using its name attribute.

Example:

window.addEventListener('load', function () {
const params = new URLSearchParams(window.location.search);
const service = params.get('servicio');

if (service) {
const field = document.querySelector("input[name='name']");

if (field) {
field.value = service;
field.dispatchEvent(new Event('input', { bubbles: true }));
field.dispatchEvent(new Event('change', { bubbles: true }));
}
}
});

This works better because the script waits until the form is fully rendered, and using input[name='name'] is more stable than relying on dynamic IDs like Field. Triggering the input and change events also ensures that Odoo properly detects the value before the form is submitted.

Another common approach in Odoo websites is to use a hidden field in the form and populate it from the URL parameter, which is often cleaner for tracking things like lead source or campaign parameters.

0
Avatar
Discard
Avatar
Jyotin DRKDS INFOTECH
Best Answer
This is a common need — pre-filling website form fields from URL query parameters in Odoo. Here's how to do it reliably in Odoo 17/18/19.

## Approach 1: JavaScript (Client-Side)

Create a custom JS file in your module's `static/src/js/`:

```javascript
/** @odoo/owl */
import publicWidget from "@web/legacy/js/public/public_widget";

publicWidget.registry.FormAutoFill = publicWidget.Widget.extend({
    selector: '.s_website_form',
    start() {
        this._super(...arguments);
        const params = new URLSearchParams(window.location.search);
        params.forEach((value, key) => {
            const field = this.el.querySelector(
                `input[name="${key}"], select[name="${key}"], textarea[name="${key}"]`
            );
            if (field) {
                field.value = decodeURIComponent(value);
                field.dispatchEvent(new Event('input', { bubbles: true }));
                field.dispatchEvent(new Event('change', { bubbles: true }));
            }
        });
    },
});
```

Add it to your asset bundle in `__manifest__.py`:
```python
'assets': {
    'web.assets_frontend': [
        'your_module/static/src/js/form_autofill.js',
    ],
},
```

Then use URLs like:
```
https://yoursite.com/contactus?name=John&email=john@example.com
```

**Key points:**
- The `dispatchEvent` calls are critical — without them, Odoo's form validation won't recognize the pre-filled values and may treat them as empty on submit.
- The `name` attribute on the input must match your URL parameter key. Inspect the rendered form HTML to find exact field names — they usually follow the pattern of the field label lowercased.

## Approach 2: Server-Side (QWeb Override)

If you need it SEO-friendly or want server-rendered defaults, override the controller and pass values to the template via `qcontext`. But this is heavier and rarely needed for simple form fills.

## Gotchas in Odoo 19

- The website form builder uses `s_website_form` snippet class — make sure your selector targets this.
- For selection/dropdown fields, set `.value` to the option's actual value, not the display label.
- Hidden fields work too — useful for passing tracking/campaign parameters silently.


-2
Avatar
Discard
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Sign up
Related Posts Replies Views Activity
Latam telefono Perú¿Cómo puedo llamar a Latam Perú?
javascript development
Avatar
0
Mar 26
67
How can I use my only web url domain using odoo?
javascript development
Avatar
Avatar
1
Sep 25
4159
How to Load Related Many2Many Data (pos.ticket.type) into the Frontend?
javascript development
Avatar
0
Jun 25
3262
Odoo 18 POS - Discount Button Group Permissions Not Working
javascript development
Avatar
Avatar
2
Jun 25
3464
¿Cómo puedo crear un Dashboard con KPIs y gráficos con Chart.js?
javascript development
Avatar
0
Apr 25
3301
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk Slovenščina Español (América Latina) Español Svenska ภาษาไทย Türkçe українська Tiếng Việt

Odoo is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now