Ir al contenido
Odoo Menú
  • Identificarse
  • 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
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    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
    • Empresa 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 de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • 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 paneles publicitarios
    • 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 empresa contable
    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

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

What should onchange methods do and return?

Suscribirse

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

Se marcó esta pregunta
1 Responder
9783 Vistas
Avatar
Leonardo Donelli

I see a lot of onchange methods in the modules, but I'm not clear on their purpose and what they should return.

0
Avatar
Descartar
Leonardo Donelli
Autor

Doc question, feel free to edit and add in any more information guys.

Avatar
Leonardo Donelli
Autor Mejor respuesta

Version 7 and lower, the API for onchange methods are different for version 8+

The onchange method are server side functions called by the client when a field in a form view is changed.
They should be used to help the user during data input, allowing him to work faster.

The onchange methods can change the data of all the record fields, not only the field that was changed. If an onchange method changes the value of another field (with the 'value' dict key we'll see in a bit) it will trigger the onchange method of that field, if any. So pay attention to not create onchange loops.

Onchange methods can show errors and/or change fields domain/values by returning a dictionary with one of more of these keys:

  • `warning`
    • Used to show an error popup, useful for example for alerting the user that the value he inserted is invalid.
    • The value should be a dict in the form {'title': <title>, 'message': <message>} where <title> will be the title of the error popup and <message> the error message.
    • This doesn't replace server-side validation: even if the client shows a popup error and doesn't accept the value the user could send a bad value with a direct RPC call, request tampering and other ways..
       
  • `domain`:
    • Used to change the domain of a relational field. Useful you have a relational field B which options should be related to the value of field A: you can write and onchange method on field A that returns a new domain for field B according to the new value. For example, if you have a field "company" and a field "contact" you can make an onchange method that when you change the company will limit the options of "contact" to only people of that company.
    • The value should be in the form {<field>: <domain>, <field>: <domain>, ...}, where field is the name of the field you want to update and domain is the new domain, in the usual domain notation.
       
  • `value`:
    • Used to change the value of a field. Onchange methods can change values even if invisible and readonly fields. (but if the fields are readonly the values won't be saved: it should be seen only as a visual hint).
    • The value should be in the form {<field_name>: <value>, <field_name>:  <value>, ...} and value should be in the correct form according to the field type. You can even change the fields of a relational field by using the correct write syntax. For example, you can update the quantity field of all the lines of a sale order.
    • This doesn't replace functional fields and bussiness logic: as with `warning`, the user could bypass the automaatic value set by onchange if he wanted to.

An example of a complete onchange return dict structure (assume the model is sale_order):

{
    'warning': {'title': 'Error!', 'message': 'Something went wrong! Please check your data'},
    'domain': {'partner_shipping_id': [('parent_id', '=', 42)]},
    'value': {
        'partner_id': 42,
        'note': 'I was changed automatically!',
        'order_lines': [
            (1, 13, {'discount': 30, 'quantity': 10}),
            (1, 14, {'discount': 15, 'quantity': 34}),
            ...
        ]
    }
}

 

 

1
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

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

Inscribirse
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 ภาษาไทย 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