Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Real Estate
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Consulting
    • Accounting Firm
    • Партнер Odoo
    • Marketing Agency
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Отримати демо
  • Ціни
  • Допомога

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

  • CRM
  • e-Commerce
  • Бухоблік
  • Склад
  • PoS
  • Проект
  • MRP
All apps
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

'on_change' alternative for dynamic domain on form edit

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
domainon_changev7
5 Відповіді
26073 Переглядів
Аватар
Obay Albadri

I am facing this problem:

"I need to change the domain of a field from within an on_change event handler because it needs special computation. While it works as expected when the field is changed, the event isn't triggered when the value is loaded into the field at form init time."

so i tried: 1. on_change: not called when editing form, and that is reasonable. 2. Just using a domain: i found my domain is more complex and needs special computation. 3. 'fields_view_get': i couldn't get the current values to construct my domain. 4. custom function to get domain: i am too close with this, but have a problem with return type.

So what is the best alternative for on_change, for this case?

here is a summarized code for 'fields_view_get':

def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
    res = super(taskmng_task, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
    doc = etree.XML(res['arch'])
    for node in doc.xpath("//field[@name='user_id']"):
        node.set('domain', 'MY DOMAIN') # here i need the current form values (if applicable)
    res['arch'] = etree.tostring(doc)
    return res

Code for custom function:

def _get_user_id_domain(self, cr, uid, ids, field_name, arg, context=None):
    record_id = ids[0] 
    project_id = self.browse(cr, uid, ids, context=context)[0].project_id   # here i can get the values (eg. 'project_id')
    # do some computation....
    return {record_id: "MY DOMAIN"} # returning domain as string rises an exception*

and then i made a field to hold domain value:

'domain_field': fields.function(_get_user_id_domain, type='char', size=255, method=True, string="Domain"),

and i use it in XML:

<xpath expr="//field[@name='user_id']" position="replace">
       <field name="user_id" domain="domain_field" />
</xpath>

*When edit the filed, this exception occur "TypeError: second argument to Function.prototype.apply must be an array", (only if i returned domain as string, and i need to do that!)

Am i going in the wrong direction, and what is the best way to make such a domin?

1
Аватар
Відмінити
Obay Albadri
Автор

Sorry for posting all these details, it may solve another question :)

Obay Albadri
Автор

I found a way to avoid returning domain as string in last function, and it works.

Ákos Sebestyén

Can you please share your solution with us?

Аватар
51anygo
Найкраща відповідь

Hello, first,thank you everyone, i get some way to solve the problem from this article , After continuous attempts, i have solved this problem perfect, the way is use onchange and add field with function type, code like this

_columns = {
        'ts_id': fields.many2one('trainstation.trainstation', 'ts', help="",required=True,),
        'get_department_id': fields.function(_get_department_id, type='integer',  method=True, string="Domain"),
        'employee_id': fields.many2one('hr.employee', 'operator', ,required=True),

}

    _defaults = {
    'ts_id':  None,
}


    def _get_department_id(self, cr, uid, ids, field_name, arg, context=None):
    result = {} 
    if not ids:
        return result           
    for record in self.browse(cr, uid, ids, context=context):
        result[record.id] = record.ts_id.area_id.manage_department_id.id
    return result

def onchange_ts(self, cr, uid, ids, ts_id,employee_id, context=None):
    domain = {}
    value =  {}
    if context is None:
        context = {}
    if not ts_id:
        return {'domain':domain}       
    obj_ts = self.pool.get('trainstation.trainstation')
    ts = obj_ts.browse(cr, uid, ts_id, context=context)
    if employee_id:
        obj_emp = self.pool.get('hr.employee')
        emp = obj_emp.browse(cr, uid, employee_id, context=context)         
        if emp.department_id.id == ts.area_id.manage_department_id.id:
            return {'domain':domain}
    domain = {'employee_id':[('department_id','=',ts.area_id.manage_department_id.id)]}
    value = {'employee_id': False}
    return {'value':value,'domain':domain}

 add this to xml file
<field name='ts_id' on_change="onchange_ts(ts_id,employee_id)" />
<field name="get_department_id" invisible="1"/>    
<field name='employee_id'  domain="[('department_id','=',get_department_id)]" />
3
Аватар
Відмінити
Аватар
Jeudy Nicolas
Найкраща відповідь

Hello,

We have implemeted this, but you need to patch openerp-server and openerp-web to enable en new setup option in form definition and a new invisible parameter that trigger invisibility state change.

you can find branch we just pushed here:

  • openerp-server : https://code.launchpad.net/~0k.io/openobject-server/add-setup-to-rng-syntax
  • openerp-web: https://code.launchpad.net/~0k.io/openerp-web/invisible-keyword-in-onchange-dict

And next if you want to execute onchange like function when form is loaded, just add this to your form definition:

<form string="Project" version="7.0" setup="my_func(name,'test')">
   ...
</form>

and in python, create a function just like onchange one:

class project(osv.osv):
    ...
    def my_func(self, cr, uid, ids, part=False, context=None):
        return {'invisible': {'partner_id': True},  'domain' : {'my_field':[]}}
    ...

Hope this will help.

2
Аватар
Відмінити
Obay Albadri
Автор

Thanks, that what i was looking for previously, and this is a good news for me, any way i approached another way (domain via function, and it works now), but i think this is a better way, right?

Anton Chepurov

Anybody to port this to v8?

Аватар
Adil Akbar
Найкраща відповідь

You can follow this: https://youtu.be/XGqXEL2qQmE 

Hope it helps, Thanks

0
Аватар
Відмінити
Аватар
Simplify it!
Найкраща відповідь

The onchange method works too if you are just defining by default a value. If you set
_defaults = { 'type': 'issue' }
for example.
Automatically system is going to call onchange function when the form loads. I hope that answers your question.

Regards

0
Аватар
Відмінити
Аватар
Keyur
Найкраща відповідь

Hi Obay,

Yes ofcourse there is an easy way to apply domain on field from within an on_change event.

Like this,

I have applied domain on the basis of type field. My type field is a selection field of values issue and return. On the basis of type field I am changing the domain of location_id.

def onchange_type(self, cr, uid, ids, type):
    domain = {}
    if type=='issue':
        domain = {'location_id':[('usage','=','internal')]}
    elif type=='return':
        domain = {'location_id':[('usage','=','inventory')]}
    return {'domain':domain}

Hope this solution solve your problem too.

Thanks.

0
Аватар
Відмінити
Obay Albadri
Автор

thanks Keyur, but the problem with 'on_change' is that "While it works as expected when the field is changed, the event isn't triggered when the value is loaded into the field at form init time.", that is why i am looking for alternative.

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
How to Set Fixed Filter for a User / User group ?
domain v7
Аватар
Аватар
1
серп. 15
6606
Change the domain of a many2one field depending on other field value Вирішено
domain on_change odoo12
Аватар
Аватар
Аватар
Аватар
3
бер. 24
17997
How can i set team sales permissions in CRM?
crm domain v7
Аватар
Аватар
Аватар
Аватар
Аватар
5
вер. 22
12621
How to update domain set in fields_view_get? Вирішено
domain v7 fields_view_get
Аватар
Аватар
1
лют. 22
26949
How to write a Domain in a filter? [SOLVED] Вирішено
filter domain v7
Аватар
Аватар
1
квіт. 24
14766
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة 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 - це набір програм для роботи з відкритим кодом, які охоплюють всі ваші потреби компанії: CRM, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція Odoo - це одночасно дуже проста у використанні та повністю інтегрована.

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