Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

Conditionally apply Domain on a field

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
domainv7domainscondition
3 Respostas
29270 Visualizações
Avatar
Shaumyadeep Chaudhuri

Is it posssible to apply a domain only when some condition is true otherwise the domain should not be applied in V7

For eg. in a many2one field to hr.employee, the manager should be able to see only the employee under him but someone from the hr department should be able to view all the employees in the view.

1
Avatar
Cancelar
Shaumyadeep Chaudhuri
Autor

No one know how to do it? is it even possible?

Avatar
Shaumyadeep Chaudhuri
Autor Melhor resposta

I solved the problem I couldn't find a regular way to do what i wanted. I feel this is a bit hackish way to achieve what i wanted; what i did was override the fields-view_get method and implemented what i wanted in that. here's a sample code of what i did, maybe it'll help other looking to implement similar functionality

def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):

    """
    Overrides orm field_view_get.
    @return: Dictionary of Fields, arch and toolbar.
    """

    res = {}
    res = super(employee_exit, self).fields_view_get(cr, user, view_id, view_type,
                                                   context, toolbar=toolbar, submenu=submenu)

    hr_employee = self.pool.get('hr.employee')
    emp = hr_employee.search(cr, user, [('user_id', '=', user)])[0]
    logged_employee = hr_employee.browse(cr, user, emp)
    from lxml import etree
    doc=etree.XML(res['arch'])
    for node in doc.xpath("//field[@name='target_employee_id']"):
        if not logged_employee.department_id.name == "Human Resources":        
            node.set('domain', "['&','|',('parent_id.user_id', '=', uid),('department_id.manager_id.user_id','=',uid),('user_id','!=',uid)]")
        elif logged_employee.department_id.manager_id.user_id.id==user:
            node.set('domain', "[('user_id','!=',uid)]")
        else:
            node.set('domain', "['&','&',('user_id','!=',uid),('user_id','!=',"+str(logged_employee.department_id.manager_id.user_id.id)+\
                     "),('user_id','!=',"+str(logged_employee.parent_id.user_id.id)+")]")
    res['arch']=etree.tostring(doc)
    return res

EDIT: I can't mark this as the answer as i don't have sufficient points. if somebody finds it useful and doesn't know of any better method please mark this as the answer so it may be visible to others in need at the top

1
Avatar
Cancelar
Avatar
Daniel Reis
Melhor resposta

Funny enough, the question and the example provided can have two different answers:

Is it possible to have a a "conditional" domain?

Yes, by building the domain in a smart way, using OR (|) operators. For example, on a particular Model having a company_id field, you could use:

['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]

Here the "child of" condition will only be enforced if the record's "company_id" has a value.

The manager should see only his employees, but hr department should see all

To easiest way to achieve this is to have two user Groups. The Managers group has a record rule to view only his employees and the HR manager group has a record rule to see all employees. You can find a similar example in the CRM app: there is a "Sales / See Own Leads" group and a "Sales / See All Leads" group.

Record rules apply to current record based on User attributes. You would need to know the Department to use for the current User, but AFAIK that info is not available in the User model. You would somehow need to have a department_id in the User and then could create a record rule (or many2one domain) similar to:

['|',('department_id','child_of',[user.department_id.id]),(False,'=',user.department_id)]
2
Avatar
Cancelar
Shaumyadeep Chaudhuri
Autor

Thanks, that was educational but i have a many2one field to hr.employee which is being displayed in the view obviously as a dropdown, now what i want is if the logged in user has department the HR then when he uses the drop down he should be able to see all the employees of the other departments and all the employees below him in HR Department, but if the logged in user is a not of the HR Department and uses the dropdown he should be able to see only the employees he the parent of. Also please explain in the above example which company_id do you mean the user.company_id or 'company_id'

Daniel Reis

Expanded the answer. The feature you need would ge a great addition to lp:openerp-hrms.

Shaumyadeep Chaudhuri
Autor

So in short its not posssible to get exactly what i need with exisiting functionality?

Umashankar Subramani

res.user doesnt have any field like department_id.... how is it possible to use this?....i have got error.....

Avatar
Michael Jurke
Melhor resposta

Unfortunately, you cannot add the same fieldname twice with an "invisible" condition and different domains (only the last fields domain has effect).

A domain like 

"(False,'=',user.department_id)"

 will lead to 

"ValueError: Invalid leaf (False, '=', False)"

To use different domains, you can use multiple fields, where the latter ones are related to the first.

parent_target_employee_id = fields.Many2one(
related="target_employee_id",
domain=[...],
)
# or add the domain in the view only

While I like this solution the most, it has a side effects: the write method will be called multiple times. This is at least how Odoo 14 works: the related keyword causes a "write" call on the target, which is "self" in those cases. This can be ignored for simple models, but if the write method performs a lot of checks and is not side effect free, the approach to override _fields_view_get is a more performant solution.


0
Avatar
Cancelar
Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
Add my own domain via NameCheap in Odoo
domain domains
Avatar
Avatar
2
dez. 20
6278
How to Set Fixed Filter for a User / User group ?
domain v7
Avatar
Avatar
1
ago. 15
6600
'on_change' alternative for dynamic domain on form edit Resolvido
domain on_change v7
Avatar
Avatar
Avatar
Avatar
Avatar
5
mai. 24
26064
Are Odoo free domains applicable to free users? Resolvido
domain free domains
Avatar
Avatar
1
mai. 24
7477
WEBSITE NOT WORKING!!! PLEASE HELP!
domain domains website
Avatar
0
jan. 24
2194
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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