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
    • eLearning
    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 taberna
    • 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
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • 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
    Browse all Industries
  • 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
    • Services for 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

Many2one dependant booleans

Suscribirse

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

Se marcó esta pregunta
onchangeOdoo13.0v13
1 Responder
3553 Vistas
Avatar
José Moreno Hanshing

I am using Odoo v13. I need help with setting the order's urgent field to True if any of the urgent fields in its items are True. And also if you change the order's value, to set all of its items' values to it, so in essence the order's checkbox will be acting as a "Select All/ Deselect All" button, but you can also check the boxes individually. 

class Order(models.Model):
    urgent = fields.Boolean()
    items = fields.One2many('my_module.items', inverse_name='order', ondelete='set null')
class Item(models.Model):
    urgent = fields.Boolean()
    order= fields.Many2one('my_module.order')

I have tested a lot with compute, inverse and onchange but I have not achieved the desired effect. Inverse function runs on save button, so I had to replace it with onchange. But I had a weird interaction where the compute and inverse functions were being called twice with each change, while my code was supposed to only run one of the functions per change, once.

Now the trouble I'm having is that I can't modify the order's value from an onchange in the items. Simply nothing happens. I read that in the past you couldn't do this, but the last comment says it was fixed.

https://github.com/odoo/odoo/issues/2693

 This is what I currently have:


# class Order(models.Model):
@api.onchange('urgent')
def select_all(self):
​    if not self.env.context.get('no_onchange'):
        self.items.write({'urgent': self.urgent}) # This works fine
# class Item(models.Model):
@api.onchange('urgent')
def any_urgent(self):
    urgents = self.order.items.filtered(lambda m: m.urgent)
    self.with_context(no_onchange=True).order.urgent = bool(len(urgents))   # This doesn't do anything.

Is there a feasible way to achieve what I'm trying to do?


0
Avatar
Descartar
Avatar
Ravi Gadhia
Mejor respuesta
It seems the main problem is recursive onchage. we can solve it by adding context on XML fields like

<field name="urgent" context="{'toggle_urgent': True}"/>

class Item(models.Model):
    _name = 'my.item'                                                                          
urgent = fields.Boolean()
order_id = fields.Many2one('my.order')

class Order(models.Model):
    _name = 'my.order'                          
urgent = fields.Boolean()
item_ids= fields.One2Many('my.item', 'order_id')

​    @api.onchange('urgent', 'iteam_ids')
def _onchange_iteam_ids(self):
if self.env.context.get('toggle_urgent'):
self.item_ids.write({'urgent': self.urgent})
else:
self.urgent = any(self.item_ids.mapped('urgent'))
1
Avatar
Descartar
José Moreno Hanshing
Autor

Thank you so much! This worked perfectly

¿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
fill a field up based on domain condition Resuelto
onchange Odoo13.0
Avatar
Avatar
Avatar
5
dic 22
6365
[v13] Update one2many field after a change in its parent Resuelto
one2many onchange parent Odoo13.0 v13
Avatar
Avatar
2
oct 20
9015
AttributeError: module 'odoo.api' has no attribute 'multi' Resuelto
Odoo13.0 v13 13
Avatar
1
nov 23
63452
Tax update from backend (code) in invoice. onchanges doesnt work. calculations doesnt refresh Resuelto
invoice onchange Odoo13.0
Avatar
Avatar
2
feb 23
5294
On change is not triggered Resuelto
one2many onchange Odoo13.0
Avatar
Avatar
1
ene 21
6242
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 de código abierto que cubren 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 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