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

can not get the context value in my function field_view_get

Suscribirse

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

Se marcó esta pregunta
1 Responder
1213 Vistas
Avatar
mokhtar

hello all,

Please help overcome this issue I can not get context value 

@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
# Call the super method to get the base view structure
res = super(HrEmployeePrivate, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar,
submenu=submenu)

if view_type == 'form':
# Ensure the branch category is correctly set in the context
rec = self.env['flex.branch'].search([('id', 'in', self.branch_name_id.ids)]).ids
branch_cate = self.branch_name_id.branch_cate if self.branch_name_id else "tttttt"
# Add branch category to the context
print('the value is :', rec)
self = self.sudo().with_context(bra_class=branch_cate)
# Retrieve the value from the context
bra_class_value = self._context.get('bra_class', 'لايوجد') # Default to 'لايوجد' if not found
print("Context Value for 'bra_class':", bra_class_value)

# Iterate through fields in the view
for field_name, field_data in res.get('fields', {}).items():
if field_name == 'job_ids':
# Dynamically set the domain for the field
field_data['domain'] = [
'|',
('company_id', '=', False),
('company_id', '=', self.env.user.company_id.id),
('bra_class', '=', bra_class_value) # Use the context value dynamically
]
return res
0
Avatar
Descartar
Avatar
Mohammad Al Khatib
Mejor respuesta

our issue seems to stem from how the context is being set and accessed in your custom Odoo method. Let’s break it down and identify why the context value (bra_class) might not be retrieved as expected.

Issues in Your Code:

1. Context Setting on self:

  • In this line:
self = self.sudo().with_context(bra_class=branch_cate)

You’re modifying self to include the context, but this doesn’t actually persist the new context to the method. The self reference is local to this method and does not affect the surrounding environment or the call stack.

2. Accessing Context with self._context:

  • Later in the method, when you attempt to retrieve the value using:

bra_class_value = self._context.get('bra_class', 'لايوجد')

The _context attribute on self refers to the original context of the method call, not the modified context you attempted to set with with_context.

3. Improper Use of with_context:

  • The with_context method returns a new recordset with the added context, but it does not retroactively apply that context to the method already in progress.


Suggested Fix:

Modify your approach to work directly with the context passed to the fields_view_get method. Here’s the corrected code:

@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
    # Call the super method to get the base view structure
    res = super(HrEmployeePrivate, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar,
                                                         submenu=submenu)

    if view_type == 'form':
        # Get branch category and add it to the context
        branch_cate = self.branch_name_id.branch_cate if self.branch_name_id else "tttttt"

        # Add branch category to the context
        ctx = dict(self._context, bra_class=branch_cate)

        # Retrieve the value from the updated context
        bra_class_value = ctx.get('bra_class', 'لايوجد')  # Default to 'لايوجد' if not found
        print("Context Value for 'bra_class':", bra_class_value)

        # Iterate through fields in the view
        for field_name, field_data in res.get('fields', {}).items():
            if field_name == 'job_ids':
                # Dynamically set the domain for the field
                field_data['domain'] = [
                    '|',
                    ('company_id', '=', False),
                    ('company_id', '=', self.env.user.company_id.id),
                    ('bra_class', '=', bra_class_value)  # Use the context value dynamically
                ]
    return res

Key Changes:

1. ctx = dict(self._context, bra_class=branch_cate)

  • This creates a new dictionary by copying the current context and adding the bra_class key.

2. Access Context via the Updated ctx:

  • Instead of attempting to modify self, you work with the ctx variable and extract bra_class from it.

3. Use ctx for Further Logic:

  • The updated context is used to dynamically set the domain for job_ids.

Debugging Tips:

1. Ensure branch_name_id is Set:

  • Add a check to verify that branch_name_id is populated; otherwise, branch_cate will default to “tttttt”.

2. Log the Context:

  • Use print or logging to confirm the structure of the context before and after modifications.

3. Validate Domains:

  • Test the resulting domain to ensure it’s applied correctly in the form view.


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
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.

Sitio web hecho con

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