Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Validations
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Maison d’hôtes
    • Distributeur de boissons
    • Hôtel
    Immobilier
    • Agence immobilière
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consultance
    • Cabinet d'expertise comptable
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Métal
    • Meubles
    • Alimentation
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et support
    • Systèmes photovoltaïques
    • Cordonnier
    • Services de nettoyage
    • Services CVC
    Autres
    • Organisation à but non lucratif
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Browse all Industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenez partenaire
    • Services for Partners
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide

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

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

Prevent navigation if records are not save

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
v15
2 Réponses
3144 Vues
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
Ignorer
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
Meilleure réponse

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
Ignorer
Avatar
D Enterprise
Meilleure réponse
  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
Ignorer
Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
Creating user creates duplicated partner_id
v15
Avatar
Avatar
1
sept. 25
3064
Sales order line comment to Purchase order line comment Résolu
v15
Avatar
Avatar
3
juil. 25
4371
attribute is not applied when dynamically rendering
v15
Avatar
1
mai 25
2487
Odoo Custome Module Language Creation
v15
Avatar
Avatar
Avatar
Avatar
4
mai 25
3896
Odoo 15 previous question papers/practice tests. Résolu
v15
Avatar
Avatar
1
févr. 25
8132
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenez partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة 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 est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

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