Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Inteligencia artificial
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Sectores
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Asesoría contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos corporativos
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Oficios
    • Servicios de mantenimiento
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de vallas publicitarias
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu asesoría contable
    • Referral Program
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Sobre este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Sobre este foro
Ayuda

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

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Esta pregunta ha sido marcada
webclientjavascriptdevelopment
4 Respuestas
1640 Vistas
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
Mejor respuesta
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 Mejor respuesta

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
Mejor respuesta

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
Mejor respuesta
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
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
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
sept 25
4202
How to Load Related Many2Many Data (pos.ticket.type) into the Frontend?
javascript development
Avatar
0
jun 25
3330
Odoo 18 POS - Discount Button Group Permissions Not Working
javascript development
Avatar
Avatar
2
jun 25
3489
¿Cómo puedo crear un Dashboard con KPIs y gráficos con Chart.js?
javascript development
Avatar
0
abr 25
3322
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones empresariales de código abierto que cubre todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

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