Перейти к содержимому
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 add a field conditional to tree view of customer?

Подписаться

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

Этот вопрос был отмечен
treeviewviewres.partnerhideinherit
4 Ответы
40152 Представления
Аватар
Anabela Damas

Hi,

I've added a supplier number and a customer number, and now I need to add this number in the tree view but I just want that the "Supplier number " appears if there is a partner is a supplier or in the view. I'll try to explain with images.

In this case when a partner is both(supplier and a costumer), it's ok to look like this: both

In this case I didn't want to show the Supplier Number: image description

And in this case I didn't want to show the Client Number: image description

I'm using this code:

<record id="view_partner_tree_inherit" model="ir.ui.view">
    <field name="name">res.partner.tree.inherit</field>
    <field name="model">res.partner</field>
    <field name="inherit_id" ref="base.view_partner_tree" />
    <field name="arch" type="xml">
    <xpath expr="/tree/field[@name='name']" position="after">
        <field name="supplier" invisible="1"/>
        <field name="customer" invisible="1"/>
        <field name="n_client" attrs="{'invisible':[('customer','!=',True)]}"/>
        <field name="n_supplier" attrs="{'invisible':[('supplier','!=',True)]}"/>
        </xpath>
    </field>
</record>

Someone know how to hide the columns depending on if it is a Suppliers tree view or a Customers tree view ?

Thanks

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

Having just scoured the internet looking for an answer to a similar problem myself I can tell you how I finally got something similar working:

Instinct told me to try the

attrs="{'invisible':[('customer','!=',True)]}"

approach too. But, I believe attrs don't work to stop the column name itself from appearing in a tree view (works only on the values of each row).

Instead, you need to overwrite the fields_view_get method from within your res_partner python code, which will allow you to change the viability of each column by checking the context. In my case I was looking at Supplier vs Customer invoices, so I checked for the context 'type' being 'out_invoice'/'in_invoice'. In your case I believe customers vs suppliers are given a context value, something like "default_customer" and "default_supplier".

Anyway, in the end you want to remove the attrs element from you xml view and then add something like this to the python code:

  from lxml import etree

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

    if context is None:
        context = {}

    res = super(res_partner,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'])

    if view_type == 'tree':
        if context.get('default_customer', '0') in ('1'):
            for node in doc.xpath("//field[@name='n_supplier']"):
                doc.remove(node)
        if context.get('default_supplier', '0') in ('1'):
            for node in doc.xpath("//field[@name='n_client']"):
                doc.remove(node)

        res['arch'] = etree.tostring(doc)
    return res

I can't guarantee this will work straight off as I havn't tested it for your case, you might need to tweak some values above. Nor can I guarantee this is the best way to achieve this. But I can say very similar code is working perfectly for me in my situation.

Hope that helps :)

2
Аватар
Отменить
Аватар
Mohamad Chamra
Лучший ответ

in tree view, you should use  column_invisible instead of invisible:

attrs="{'column_invisible ':[('customer','!=',True)]}"


1
Аватар
Отменить
Andres Brigard

Thanks, worked great in Odoo 12

Аватар
Tintumon
Лучший ответ

For other view like "form view" it works fine

attrs="{'invisible':[('customer','!=',True)]}"

If you use this attrs in Tree view it just hide the data/content which shown in that column. Not the complete column.


So I just tried using this instead of above code:

invisible = "context.get('customer') != True"

And it helped me to hide the complete column from Tree view.

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

Using the attrs XML attributes to set the invisible attribute of an element is not working. In fact, this attrs will only show or hide the content of the tree view, not the entire column. After searching for some solutions from google, i found this one is working. As an example, i add two new fields on invoice model (called ref_partner_id and sales_inv) and it will shows on the invoice tree view only if the type is out_invoice (supplier invoice):

<field name=”ref_partner_id” string=”Customer (name)” invisible=”context.get(‘type’) == ‘out_invoice’ “/>
<field name=”sales_inv”  invisible=”context.get(‘type’) == ‘out_invoice’ “/>

This will work because we got the context variable that inform us the type of invoices currently being displayed on the tree. This comes from the account module (account_invoice_view.xml), for example on the action_invoice_tree2:

<record id=”action_invoice_tree2″ model=”ir.actions.act_window”>
<field name=”name”>Supplier Invoices</field>
<field name=”res_model”>account.invoice</field>
<field name=”view_type”>form</field>
<field name=”view_mode”>tree,form,calendar,graph</field>
<field eval=”False” name=”view_id”/>
<field name=”domain”>[('type','=','in_invoice')]</field>
    <field name=”context”>{‘default_type’: ‘in_invoice’, ‘type’: ‘in_invoice’, ‘journal_type’: ‘purchase’}</field>
</record>

Source: http://vitraining.com/show-hide-columns-in-openerp-tree-view-xml/

0
Аватар
Отменить
Не оставайтесь в стороне – присоединяйтесь к обсуждению!

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

Регистрация
Похожие посты Ответы Просмотры Активность
Creating new view from a old view Решено
view res.partner inherit
Аватар
Аватар
11
янв. 24
14467
inherit res.partner view
view res.partner inherit
Аватар
Аватар
1
мар. 15
12025
Hide the misc group in res.partner view in sale & purchases page
view res.partner hide group odoo18
Аватар
Аватар
1
мая 25
1526
How to inherit list (tree) view? Решено
treeview inherit
Аватар
Аватар
Аватар
3
янв. 24
16007
Why is my Custom TreeView showing only one record, instead of a list of records? Решено
treeview view
Аватар
Аватар
2
мая 18
4892
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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