Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Artificial Intelligence
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Property Management
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    • Referral Program
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

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

Subscriure's

Get notified when there's activity on this post

This question has been flagged
webclientjavascriptdevelopment
4 Respostes
1635 Vistes
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
Descartar
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
Descartar
Avatar
Brissa Cx, Eliana Bermudez
Autor 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
Descartar
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
Descartar
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
Descartar
Enjoying the discussion? Don't just read, join in!

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

Registrar-se
Related Posts Respostes Vistes Activitat
Latam telefono Perú¿Cómo puedo llamar a Latam Perú?
javascript development
Avatar
0
de març 26
67
How can I use my only web url domain using odoo?
javascript development
Avatar
Avatar
1
de set. 25
4189
How to Load Related Many2Many Data (pos.ticket.type) into the Frontend?
javascript development
Avatar
0
de juny 25
3314
Odoo 18 POS - Discount Button Group Permissions Not Working
javascript development
Avatar
Avatar
2
de juny 25
3474
¿Cómo puedo crear un Dashboard con KPIs y gráficos con Chart.js?
javascript development
Avatar
0
d’abr. 25
3316
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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