Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    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
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

How to override onchange old api vs new ?

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
v7apionchangeoverridev8.0
7 Ответы
15837 Представления
Аватар
Temur

Need to override onchange function from old v7 API, like this one:

Python (v7 API):

...
def onchange_field_a(self, cr, uid, ids, field_a, field_b, field_c, context=None):
    vals = {'value':{} }
    #
    # A huge code here to be executed on field_a changes...
    #
    return vals
...

XML (v7 API):

...
    <field name="field_a" on_change="onchange_field_a(field_a, field_b, field_c)"
...

v7 onchange function said to be incompatible with the new v8 api. here is related posts on this forum that I've found for now:

https://www.odoo.com/forum/help-1/question/75299 

https://www.odoo.com/forum/help-1/question/73893 

- however, we'd like to override onchange_field_a function using new v8.0 API and 1) we do not want to rewrite a huge code written in v7 onchange function, which is well tested and working in the parent model and 2) we do not want to copy-paste it either. Beside that it's bad practice to have copy of a same code in several places, it should be harder to maintain such a copy, as it's likely to receive further bugfixes and improvements (if any) in the same v7 implementation and the same place where it's defined. So, we need to reuse existing v7 onchange_field_a function code defined in the superclass by calling it from overridden v8 onchange_field_a function and add our additional code afterwards (or before,depending on case). 

1
Аватар
Отменить
Аватар
Temur
Автор Лучший ответ

right question to ask here is what it makes incompatible onchange v7 vs v8? and can we overcome this incompatibility in order to reuse existing code? Actually it's possible by applying quite simple workaround to the onchange v7 vs v8 incompatibility:

Python (v8 API):

...
@api.onchange("field_a")
@api.depends("field_b", "field_c", "custom_field_in_my_class")
def onchange_field_a(self):

### section 1. get result of original onchange_field_a from superclass:
orig_result = super(my_class,self).onchange_field_a(self.field_a, self.field_b, self.field_c)

### section 2. workaround for api incompatibility:
if type(orig_result) is dict and orig_result.has_key('value'):
for field, value in orig_result.get('value').items():
if hasattr(self, field):
setattr(self, field, value)


### section 3. your additional code, for example:
if self.field_c:
self.custom_field_in_my_class = True
...

Old api way was to return value dictionary for changed fields, whereas new api way is to assign changes directly to fields of virtual record inside the onchange function, so in the "section 2" we turn value return through dictionary into direct assignments to fields. that's it, api incompatibility is handled by the "section 2".

Note:
field's "on_change" property in XML is no more necessary in v8 

2
Аватар
Отменить
Temur
Автор
XML part: we can just ignore XML part in this case. it'll work with or without removing on_change property from corresponding XML record, this record just become redundant, but do not interfere normal execution of this overridden function.
Temur
Автор
Note for Relational Fields: if any field from @api.onchange or @api.depends lists are relational fields, then in "section1" you have to use self.field_name.id or self.field_name.ids respectively for many2one and x2many fields. for example, if field_a has a type Many2one and field_b has a type one2many or many2many, then instead of:
orig_result = super(my_class,self).onchange_field_a(self.field_a, self.field_b, self.field_c)
we'll have:
orig_result = super(my_class,self).onchange_field_a(self.field_a.id, self.field_b.ids, self.field_c)
Temur
Автор
Return Value: as it's v8.0 style onchange function (@api.onchange), we do NOT need to return anything. the "orig_result" result of call parent function is just used in the "section 2", where it's turned into direct assignments. No need to return anything, "section 3" is just normal v8.0 @api.onchange code with direct assignments to fields of "self"
Gavin Yap

Hi Temur, I've tried to over the onchange methood fo hr.payslip

 
    @api.onchange("contract_id")
    @api.depends( "date_from", "date_to", "employee_id", "contract_id")
    def onchange_field_a(self):
        print "do something"
it doesn't work for contract_id. Can you advise?
Temur
Автор

if there is already a XML entry with on_change in a corresponding form view, then it may require to be replaced with on_change="1", Try to add attribute directly: <field name="contract_id" position="attributes"> <atribute name="on_change" >1</attribute></field>, if it does not work then you can simply replace entire contract_id field with itself, but with on_change="1" (pay attention to other properties in field definition as well, if there is any, in order to preserve them by the way)

Temur
Автор

Here is original definition of contract_id in it's view:

<field name="contract_id" domain="[('employee_id','=',employee_id),('date_start','&lt;=',date_to),'|',('date_end','&gt;=',date_from),('date_end','=',False)]" on_change="onchange_contract_id(date_from, date_to, employee_id, contract_id)" context="{'default_employee_id': employee_id}"/>
There is "domain" and "context" attributes as well, most probably you'll need to preserve them, but change the existing "on_change" property, in order to have the on_change="1" record in it's place. There is a few ways to do so. Here is one of the options, inherit the view and replace on_change property of contract_id (Note: please try the "attribute" way described in the previous comment first, it's interesting if that one will work), by replacing an entire field with itself, like:
<field name="contract_id" position="replace" >
<field name="contract_id" domain="[('employee_id','=',employee_id),('date_start','&lt;=',date_to),'|',('date_end','&gt;=',date_from),('date_end','=',False)]" on_change="1" context="{'default_employee_id': employee_id}" />
</field>
Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
Override Onchange Method : onchange_partner_id on account_voucher [v7]
v7 method onchange override
Аватар
Аватар
Аватар
5
апр. 17
8286
How to override the onchange_product_tmpl_id with new api?
api inherit onchange override
Аватар
Аватар
Аватар
Аватар
3
нояб. 15
7960
API 8.0 onchange() and depends() decorators only work for UI changes and 1 record only?
api onchange
Аватар
Аватар
1
июн. 15
5886
Is there a v7 API guide? Решено
v7 api
Аватар
Аватар
1
мар. 15
4922
Preventing On change recursion
v7 onchange
Аватар
1
мар. 15
6232
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة 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, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

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