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

How to create a custom discard button?

Suscribirse

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

Se marcó esta pregunta
odooodoo17
4 Respuestas
3564 Vistas
Avatar
Sebastian

I have these buttons:




def update(self):

evaluation_cycle_model = self.env[
'sst.initial.evaluation.by.cycles'].search([('id', '=',self.evaluation_id.id)],limit=1)

if evaluation_cycle_model:
evaluation_cycle_model.update_records()

view_id = self.env.ref('sst.view_sst_qualification_form').id
return {
'type': 'ir.actions.act_window',
'name': 'Calificar Items',
'res_model': 'sst.initial.evaluation.by.cycles',
'res_id': self.id,
'view_mode': 'form',
'views': [[view_id, 'form']],
'target': 'new',
'tag': 'reload'
}

def action_discard(self):

view_id = self.env.ref('sst.view_sst_qualification_form').id
return {
'type': 'ir.actions.act_window',
'name': 'Calificar Items',
'res_model': 'sst.initial.evaluation.by.cycles',
'res_id': self.id,
'view_mode': 'form',
'views': [[view_id, 'form']],
'target': 'new',
}


I have this action_discard button, which returns an action to return to a specific view, my question is, how can I make the button works? The action it returns works, but it does not discard the information, on the contrary it saves it in the database.

0
Avatar
Descartar
Avatar
Simon Mburu Njoroge
Mejor respuesta

To implement a custom "Discard" button in Odoo 17 that effectively reverts unsaved changes, you can follow these steps:

  1. Define the Discard Button in Your XML View:
    Add a button to your form view with the special="cancel" attribute. This attribute ensures that the button functions as a discard action.
    xml Copy code < footer > 
        < button  string = "Discard"  special = "cancel"  class = "oe_link" /> 
    </ footer >
    
    The special="cancel" attribute is recognized by Odoo to trigger the discard operation, reverting any unsaved changes and closing the form view.
  2. Implement the Discard Functionality in Your Python Model:
    If you need to perform additional actions when the discard button is pressed, you can define a method in your model. However, for the standard discard behavior, the special="cancel" attribute handles the necessary operations.
    python Copy code from odoo import models, fields, api
    
    class  YourModel (models.Model):
        _name = 'your.model'
    
        # Define your fields here
    
        @api.multi 
        def  action_discard ( self ):
             # Custom actions before discarding changes 
            self.env.cr.rollback()   # Revert unsaved changes 
            return {
                 'type' : 'ir.actions.act_window' ,
                 'name' : 'Your Form ' ,
                 'res_model' : 'your.model' ,
                 'view_mode' : 'form' ,
                 'res_id' : self. id ,
                 'target' : 'current' ,
            }
    
    In this method, self.env.cr.rollback() is used to discard any uncommitted changes in the current transaction. The returned action reloads the form view without saving the modifications.

Additional Considerations:

  • Using special="cancel" : This attribute is a built-in feature in Odoo that provides standard discard functionality without the need for custom methods.
  • Custom Discard Logic: If your discard operation requires additional logic, such as resetting specific fields or triggering other actions, you can define a method like action_discard in your model and link it to a button without the special="cancel" attribute.

By following these steps, you can create a custom discard button in Odoo 17 that effectively reverts unsaved changes, ensuring a seamless user experience.

Sources

1
Avatar
Descartar
Avatar
Eileen Duran
Mejor respuesta
  • self.env.cr.rollback() will discard any changes made in the current transaction.
  • This prevents the record from being saved when returning to the form view.

Now, when the action_discard button is clicked, the record’s changes will be discarded and the user will be taken back to the form view without saving any modifications.

0
Avatar
Descartar
Eileen Duran

Hope this answer helps you. If you have any questions, you can contact me via the following page: https://basketballlegends.pro
Playing in the basketball competition is a great way to get in on the championship race and join the other competitors.

Avatar
ZaraBisliev
Mejor respuesta

Hi! I like yours very much. I think you should check out for some custom dismiss button options. It helps you a lot in this regard.

0
Avatar
Descartar
ZaraBisliev

The best idea is to refer to https://geometrydashdeadlocked.com/ to have suitable selection methods for the above problem.

Avatar
Sebastian
Autor Mejor respuesta

I did it guys.
I just save each field in the context:

'context': {
'default_item_id': self.id,
'default_evaluation_id': evaluation_id,
'default_item_weight': self.weight,
'default_date': evaluation.date,
'default_compliance': evaluation.compliance,
'default_weight': evaluation.compliance_weight,
'default_responsible': evaluation.responsible.id,
'default_observation': evaluation.observation
}
def action_discard(self):
original_data = {
'date': self.env.context.get('default_date'),
'compliance': self.env.context.get('default_compliance'),
'compliance_weight': self.env.context.get('default_weight'),
'responsible': self.env.context.get('default_responsible'),
'observation': self.env.context.get('default_observation')
}
self.write(original_data)
view_id = self.env.ref('sst.view_sst_qualification_form').id
return {
'type': 'ir.actions.act_window',
'name': 'Calificar Items',
'res_model': 'sst.initial.evaluation.by.cycles',
'res_id': self.id,
'view_mode': 'form',
'views': [[view_id, 'form']],
'target': 'new',
}
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
How to create a dynamic domain in Odoo 17? Resuelto
odoo odoo17
Avatar
Avatar
Avatar
Avatar
3
mar 25
4225
How to Change the Error Dialog Box, Odoo Title Name, and Odoo Server Name?
odoo odoo17
Avatar
0
mar 25
2273
'\n' new line option not working in UserError in Odoo 17
odoo odoo17
Avatar
Avatar
1
nov 24
3451
Error when entering settings
odoo odoo17 Odoo17
Avatar
Avatar
Avatar
2
abr 25
4150
Odoo JsonRPC : Get m2m, m2o or o2m nested field with read method
odoo jsonrpc odoo17
Avatar
0
feb 25
1928
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