Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Validations
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Guest House
    • Distributeur de boissons
    • Hotel
    Real Estate
    • Real Estate Agency
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consulting
    • Accounting Firm
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et support
    • Solar Energy Systems
    • Cordonnier
    • Services de nettoyage
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Browse all Industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenez partenaire
    • Services for Partners
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide

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

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

Conditionally apply Domain on a field

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
domainv7domainscondition
3 Réponses
29269 Vues
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
Ignorer
Shaumyadeep Chaudhuri
Auteur

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

Avatar
Shaumyadeep Chaudhuri
Auteur Meilleure réponse

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
Ignorer
Avatar
Daniel Reis
Meilleure réponse

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
Ignorer
Shaumyadeep Chaudhuri
Auteur

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
Auteur

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
Meilleure réponse

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
Ignorer
Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
Add my own domain via NameCheap in Odoo
domain domains
Avatar
Avatar
2
déc. 20
6278
How to Set Fixed Filter for a User / User group ?
domain v7
Avatar
Avatar
1
août 15
6600
'on_change' alternative for dynamic domain on form edit Résolu
domain on_change v7
Avatar
Avatar
Avatar
Avatar
Avatar
5
mai 24
26064
Are Odoo free domains applicable to free users? Résolu
domain free domains
Avatar
Avatar
1
mai 24
7477
WEBSITE NOT WORKING!!! PLEASE HELP!
domain domains website
Avatar
0
janv. 24
2194
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenez partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة 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 est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

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