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
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita 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
  • Proyectos
  • 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

Prevent navigation if records are not save

Suscribirse

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

Se marcó esta pregunta
v15
2 Respuestas
3146 Vistas
Avatar
Antonio Krsnik

I am trying to implement warning to user when there is a change in the records, but Save button is not hit and they are navigation to some other screen or closing the window. 

I tried multiple things


Adding flag like below

has_unsaved_changes = fields.Boolean(string="Has Unsaved Changes", default=False)


which should be modified onchange of certain fields to give validation error:


    @api.constrains('has_unsaved_changes')

    def _check_unsaved_changes(self):

        for record in self:

            if record.has_unsaved_changes:

                _logger.warning(f"ValidationError: Unsaved changes detected for record {record.id}.")

                raise ValidationError("You have unsaved changes. Please save your changes before proceeding.")

Which then should be modified to true when button is pressed. But no write or create function work on it, as it immediately triggers the warning 

Annoying thing is also that Odoo is automatically trying to save when you navigate. 

Another thing I tried is using custom button and context

But even when I introduce a button it still get an error when user clicks it:


def write(self, vals):

        """Override write to prevent automatic saving unless explicitly triggered."""

        if not self.env.context.get('is_user_action', False):

            raise UserError("Automatic save is not allowed. Please save explicitly using the appropriate action.")

        if 'has_unsaved_changes' in vals or any(field in vals for field in self._fields):

            vals['has_unsaved_changes'] = False

        return super(CreateTargetMetrics, self).write(vals)


    def save_changes(self):

        """Button action to save changes."""

        for record in self:

            # Save new record

            _logger.info("********Creating new record ********")

            _logger.info("record._convert_to_write(record._cache)==", record._convert_to_write(record._cache))

            record.with_context(is_user_action=True).create(record._convert_to_write(record._cache))


I added the logs also, and when pressing custom button I don't get any, meaning the button is not even triggered

0
Avatar
Descartar
Christoph Farnleitner

You could check out how this is done for the Settings page - any change there will lead to a warning, when navigating elsewhere - and adapt this feature to your needs.

Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

Please refer to the module:

1. https://apps.odoo.com/apps/modules/18.0/auto_save_restrict

Displays a popup asking if you want to save changes when attempting to navigate away from a record with unsaved changes.


Hope it helps




0
Avatar
Descartar
Avatar
D Enterprise
Mejor respuesta
  1. Use Odoo's JS window.onbeforeunload event to detect unsaved changes on the client and warn the user.
  2. Hook into Odoo's FormView JS to detect changes to form fields and set a flag in the browser.
  3. Allow save normally (don’t block server-side writes) — just warn client-side.
How to implement this in Odoo 15/16/17+ (example concept):

1. Create a small JS module extending FormView
odoo.define('your_module.form_warning', function (require) {

    "use strict";


    var FormController = require('web.FormController');


    FormController.include({

        init: function () {

            this._super.apply(this, arguments);

            this.hasUnsavedChanges = false;

        },


        _onFieldChanged: function (event) {

            this.hasUnsavedChanges = true;

            this._super.apply(this, arguments);

        },


        _onSave: function () {

            this.hasUnsavedChanges = false;

            return this._super.apply(this, arguments);

        },

    });


    window.addEventListener('beforeunload', function (e) {

        // If user has unsaved changes, show warning dialog

        if (odoo.__DEBUG__.services.form_controller && odoo.__DEBUG__.services.form_controller.hasUnsavedChanges) {

            var confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';

            e.returnValue = confirmationMessage; // Gecko + IE

            return confirmationMessage; // Webkit, Chrome

        }

    });

});

This example overrides the form controller to track changes, reset on save, and warn on page unload.
Include this JS file in your module manifest:
'assets': {

    'web.assets_backend': [

        'your_module/static/src/js/form_warning.js',

    ],

},

On the server side:

  • Remove the constrains and write overrides related to unsaved changes flag.
  • Keep the database model simple; no need for has_unsaved_changes boolean.
  • Let Odoo handle saves normally.

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Creating user creates duplicated partner_id
v15
Avatar
Avatar
1
sept 25
3066
Sales order line comment to Purchase order line comment Resuelto
v15
Avatar
Avatar
3
jul 25
4374
attribute is not applied when dynamically rendering
v15
Avatar
1
may 25
2491
Odoo Custome Module Language Creation
v15
Avatar
Avatar
Avatar
Avatar
4
may 25
3898
Odoo 15 previous question papers/practice tests. Resuelto
v15
Avatar
Avatar
1
feb 25
8133
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 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