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

Show or hide a server action button based on a field value on odoo V17 CE

Suscribirse

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

Se marcó esta pregunta
actiondevelopementvisibilityserver_actions17.0
3 Respuestas
2172 Vistas
Avatar
Master

Hi,

How can I show or hide a server action button based on a field value in my model?

For example, if the state field is 'closed', I want the "Open" button to be visible.

And if the state is 'open', I want the "Close" button to be displayed instead.

Is there a way to conditionally show or hide these server actions depending on the record's state?


<record id="mymodel_open_action_server" model="ir.actions.server">

<field name="name">Open mymodel</field>

<field name="model_id" ref="model_mymodel"/>

<field name="binding_model_id" ref="model_mymodel"/>

<field name="binding_view_types">form</field>

<field name="state">code</field>

<field name="code">

action = records.open_action()

</field>

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

Please refer to the solved forum:

1. https://www.odoo.com/id_ID/forum/help-1/how-to-hide-action-button-based-on-condition-246523

2. https://www.odoo.com/id_ID/forum/help-1/hide-a-menu-inside-action-button-based-on-condition-168198


Hope it helps.

0
Avatar
Descartar
Avatar
slckatav
Mejor respuesta

Hey, could you share your open_action() function as well? Since you’d prefer not to use a button seeing that code will help me suggest the right approach. In general you can add an attrs to your XML to toggle visibility. For example:

attrs="{'invisible': [('state', 'in', ['sale'])]}"

This will hide the element when state is not in the “sale” stage. Of course, you can adjust the domain or use different attribute just a quick example to get you started.

0
Avatar
Descartar
Master
Autor

Hi, you can see my code below for more details:

<!-- Server Action -->
<record id="mymodel_closed_action_server" model="ir.actions.server">
<field name="name">Close</field>
<field name="model_id" ref="model_mymodel"/>
<field name="binding_model_id" ref="model_mymodel"/>
<field name="state">code</field>
<field name="code">action = records._action_close()</field>
</record>

def _action_close(self):
for rec in self:
if rec.state != "closed":
print("My logic goes here!")
rec.state = "closed"

slckatav

I once hid some action buttons by finding their generated names. Odoo assigns its own names to action buttons like button name="356". In your case, after you add your action button find the name that Odoo generated and then add XML like this:

<xpath expr="//button[@name='466']" position="attributes">
<attribute name="invisible">True</attribute>
</xpath>

I hope this helps!

Avatar
D Enterprise
Mejor respuesta

Hiii,

To show/hide buttons based on the state field in Odoo 17 Community Edition , you must use button elements inside the form view , not ir.actions.server bindings, because ir.actions.server buttons do not support dynamic visibility using attrs .

Here's the correct and clean implementation :

Model: mymodel.py

Define state , action_open , and action_close :

from odoo import models, fields class MyModel (models.Model): _name = 'mymodel' _description = 'My Model' state = fields.Selection([ ( 'open' , 'Open' ), ( 'closed' , 'Closed' ) ], default= 'open' , string= 'State' ) def action_open ( self ): for record in self: record.state = 'open' def action_close ( self ): for record in self: record.state = 'closed'

View: mymodel_form_view.xml

Inherit or define your form view and add two buttons, conditionally shown using attrs .

<record id ="view_form_mymodel" model="ir.ui.view"> <field name = "name" >mymodel.form </field> <field name = "model" >mymodel </field> <field name = "arch" type = "xml"> <form string = "My Model"> <header> <button name="action_open"

​ ​ ​ ​ ​        type="object"

​ ​ ​ ​​        string="Open"

        ​ ​ ​ ​ ​invisible="state != 'closed'"/> <button name="action_close"

​ ​ ​ ​ ​        type="object"

​ ​ ​ ​ ​        string="Close"

​ ​ ​ ​ ​        invisible="state != 'open'"/> </header> <sheet> <group> <field name = "state"/> <!-- other fields --> </group> </sheet> </form > </field > </record>

i hope it is use full

0
Avatar
Descartar
Master
Autor

This works with a normal <button> tag. However, in my case, I need to show or hide my custom choices Close/Open in the default server action, similar to the behavior of the Archive/Unarchive button in

D Enterprise

Use the binding_filter_domain field (Best Practice)
From Odoo 15+, ir.actions.server supports a field called binding_filter_domain, which defines when a server action appears in the action dropdown.

Example: Show “Open” action only if state == 'closed'
<record id="mymodel_open_action_server" model="ir.actions.server">
<field name="name">Open</field>
<field name="model_id" ref="model_mymodel"/>
<field name="binding_model_id" ref="model_mymodel"/>
<field name="binding_view_types">form</field>
<field name="binding_filter_domain">[('state', '=', 'closed')]</field>
<field name="state">code</field>
<field name="code">
action = records.action_open()
</field>
</record>
Example: Show “Close” action only if state == 'open'
<record id="mymodel_close_action_server" model="ir.actions.server">
<field name="name">Close</field>
<field name="model_id" ref="model_mymodel"/>
<field name="binding_model_id" ref="model_mymodel"/>
<field name="binding_view_types">form</field>
<field name="binding_filter_domain">[('state', '=', 'open')]</field>
<field name="state">code</field>
<field name="code">
action = records.action_close()
</field>
</record>
please try this
i hoe it is use full

¿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 planned actions? Resuelto
action actions server_actions
Avatar
Avatar
2
mar 23
3273
(!!copair~rápido!!) Cómo puedo hablar con una persona real en Copa?
action
Avatar
0
nov 25
4
Notification Email Alias – What Emails Are Sent?
action
Avatar
0
nov 25
5
odoo 19, Enterprise version odoo on - premise.
action
Avatar
Avatar
2
nov 25
132
in POS orderline is it possible to add background color to the discounted product line
17.0
Avatar
Avatar
1
nov 25
72
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