Skip ke Konten
Odoo Menu
  • Login
  • Uji coba gratis
  • Aplikasi
    Keuangan
    • Akuntansi
    • Faktur
    • Pengeluaran
    • Spreadsheet (BI)
    • Dokumen
    • Tanda Tangan
    Sales
    • CRM
    • Sales
    • POS Toko
    • POS Restoran
    • Langganan
    • Rental
    Website
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventaris
    • Manufaktur
    • PLM
    • Purchase
    • Maintenance
    • Kualitas
    Sumber Daya Manusia
    • Karyawan
    • Rekrutmen
    • Cuti
    • Appraisal
    • Referensi
    • Armada
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Acara
    • Otomatisasi Marketing
    • Survei
    Layanan
    • Project
    • Timesheet
    • Layanan Lapangan
    • Meja Bantuan
    • Planning
    • Appointment
    Produktivitas
    • Discuss
    • Kecerdasan Buatan
    • IoT
    • VoIP
    • Pengetahuan
    • WhatsApp
    Aplikasi pihak ketiga Odoo Studio Platform Odoo Cloud
  • Industri
    Retail
    • Toko Buku
    • Toko Baju
    • Toko Furnitur
    • Toko Kelontong
    • Toko Hardware
    • Toko Mainan
    Makanan & Hospitality
    • Bar dan Pub
    • Restoran
    • Fast Food
    • Rumah Tamu
    • Distributor Minuman
    • Hotel
    Real Estate
    • Agensi Real Estate
    • Firma Arsitektur
    • Konstruksi
    • Manajemen Properti
    • Perkebunan
    • Asosiasi Pemilik Properti
    Konsultansi
    • Firma Akuntansi
    • Mitra Odoo
    • Agensi Marketing
    • Firma huku
    • Talent Acquisition
    • Audit & Sertifikasi
    Manufaktur
    • Tekstil
    • Logam
    • Perabotan
    • Makanan
    • Brewery
    • Corporate Gift
    Kesehatan & Fitness
    • Sports Club
    • Toko Kacamata
    • Fitness Center
    • Wellness Practitioners
    • Farmasi
    • Salon Rambut
    Perdagangan
    • Handyman
    • IT Hardware & Support
    • Sistem-Sistem Energi Surya
    • Pembuat Sepatu
    • Cleaning Service
    • Layanan HVAC
    Lainnya
    • Organisasi Nirlaba
    • Agen Lingkungan
    • Rental Billboard
    • Fotografi
    • Penyewaan Sepeda
    • Reseller Software
    Browse semua Industri
  • Komunitas
    Belajar
    • Tutorial-tutorial
    • Dokumentasi
    • Sertifikasi
    • Pelatihan
    • Blog
    • Podcast
    Empower Education
    • Program Edukasi
    • Game Bisnis 'Scale Up!'
    • Kunjungi Odoo
    Dapatkan Softwarenya
    • Download
    • Bandingkan Edisi
    • Daftar Rilis
    Kolaborasi
    • Github
    • Forum
    • Acara
    • Terjemahan
    • Menjadi Partner
    • Layanan untuk Partner
    • Daftarkan perusahaan Akuntansi Anda.
    Dapatkan Layanan
    • Temukan Mitra
    • Temukan Akuntan
    • Konsultasi
    • Layanan Implementasi
    • Referensi Pelanggan
    • Bantuan
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Dapatkan demo
  • Harga
  • Bantuan
Anda harus terdaftar untuk dapat berinteraksi di komunitas.
Semua Post Orang Lencana-Lencana
Label (Lihat semua)
odoo accounting v14 pos v15
Mengenai forum ini
Anda harus terdaftar untuk dapat berinteraksi di komunitas.
Semua Post Orang Lencana-Lencana
Label (Lihat semua)
odoo accounting v14 pos v15
Mengenai forum ini
Help

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

Langganan

Dapatkan notifikasi saat terdapat aktivitas pada post ini

Pertanyaan ini telah diberikan tanda
webclientjavascriptdevelopment
4 Replies
1554 Tampilan
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
Buang
Avatar
Kunjan Patel
Jawaban Terbai
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
Buang
Avatar
Brissa Cx, Eliana Bermudez
Penulis Jawaban Terbai

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
Buang
Avatar
Sangar
Jawaban Terbai

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
Buang
Avatar
Jyotin DRKDS INFOTECH
Jawaban Terbai
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
Buang
Menikmati diskusi? Jangan hanya membaca, ikuti!

Buat akun sekarang untuk menikmati fitur eksklufi dan agar terlibat dengan komunitas kami!

Daftar
Post Terkait Replies Tampilan Aktivitas
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
4080
How to Load Related Many2Many Data (pos.ticket.type) into the Frontend?
javascript development
Avatar
0
Jun 25
3151
Odoo 18 POS - Discount Button Group Permissions Not Working
javascript development
Avatar
Avatar
2
Jun 25
3434
¿Cómo puedo crear un Dashboard con KPIs y gráficos con Chart.js?
javascript development
Avatar
0
Apr 25
3225
Komunitas
  • Tutorial-tutorial
  • Dokumentasi
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Terjemahan
Layanan
  • Odoo.sh Hosting
  • Bantuan
  • Peningkatan
  • Custom Development
  • Pendidikan
  • Temukan Akuntan
  • Temukan Mitra
  • Menjadi Partner
Tentang Kami
  • Perusahaan kami
  • Aset Merek
  • Hubungi kami
  • Karir
  • Acara
  • Podcast
  • Blog
  • Pelanggan
  • Hukum • Privasi
  • Keamanan
الْعَرَبيّة 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 adalah software terintegrasi dengan 70+ aplikasi seperti CRM, Akuntansi, Inventaris, Sales, eCommerce, Marketing, POS; plus fitur lokal Indonesia!

Mudah digunakan dan terintegrasi penuh pada saat yang sama adalah value proposition unik Odoo.

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