Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar 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
  • Proyecto
  • 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
1208 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.

Inscribirse
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información 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 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