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.