コンテンツへスキップ
メニュー
この質問にフラグが付けられました
1 返信
600 ビュー

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

アバター
破棄

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.

最善の回答
  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.

アバター
破棄
関連投稿 返信 ビュー 活動
3
5月 25
2353
1
5月 25
573
1
5月 25
761
4
5月 25
2044
1
2月 25
5612