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 Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Консалтинг
    • Бухгалтерська компанія
    • Партнер Odoo
    • Агенція маркетингу
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Меблі
    • Їжа
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Системи сонячної енергії
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Інші
    • 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
Про цей форум
Допомога

After inheritance, and create new view, it shows all fields

Підписатися

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

Це запитання позначене
viewsinheritancehr_expense
3 Відповіді
11543 Переглядів
Аватар
David Yao

Hi all, I'm really new to Odoo. yeah, again, I got another inheritance problem.

The issue I'm facing is that: After inheritance hr.expense to my custom module "expense_new", I would like to create new view to it, tree view seems works fine (maybe I did it wrong tho) but its form view display all the fields including new field I added. (all field display regardless its invisible attribute, more than 25 fields displayed on the screen). I believe It is something wrong on XML file.

The way I'm using to inherit is "_inherits", and here is my code:   

class expenseNew(models.Model):    
    _name = 'expense_new.expense_new'
    _inherits = {'hr.expense': 'expense_new_id'}
    expense_new_id = fields.Many2one('hr.expense', help="This is a many2one field in expense_new module, and this field is used as a link to hr.expense module")
    # ......Override original fields......
    name = fields.Char(string='Expense Summary', readonly=True, required=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]})
    ...
    # ......Extra fields/ my own fields......
    calculate_total_amount = fields.Float(string='Total Cost', store=True, compute='_compute_amount_my', digits=dp.get_precision('Account'))
    ...
<record id="expense_new_tree_view" model="ir.ui.view">        
    <field name="name">expense_new.expense_new.tree.view</field>
    <field name="model">expense_new.expense_new</field>
    <field name="arch" type="xml">
        <tree string="Expenses">
            <field name="name"/>
            <field name="employee_id"/>
            <field name="date" required="True"/>
            <field name="state"/>
            <field name="calculate_total_amount"/>
        </tree>
    </field>
</record>
<record id="expense_new_form_view" model="ir.ui.view">
    <field name="name">expense_new.expense_new.form.view</field>
    <field name="model">expense_new.expense_new</field>
    <!--<field name="inherit_id" ref="hr_expense.hr_expense_form_view"/>-->
    <field name="arch" type="xml">
        <form string="Expenses" class="o_expense_form">
            <sheet>
                ......    
                <div class="oe_title">
                    <label for="name"/>
                    <h1>
                        <field name="name" placeholder="e.g. Lunch with Customer"/>
                    </h1>
                </div>
                <group>
                    <group>
                        <field name="date"/>
                        <field name="employee_id" groups="hr_expense.group_hr_expense_user"/>
                        <field name="calculate_total_amount"/>
                    </group>
                </group>
            </sheet>
        </form>
    </field>
</record>
<record id="submit_your_expense_action" model="ir.actions.act_window">
    <field name="name">My Expenses to Submit ("draft" expenses))</field>
    <field name="res_model">expense_new.expense_new</field>
    <field name="view_mode">tree,form</field>
</record>
<menuitem .../>

 

And also, In "_inherits" way, is it possible to inherit its "hr_expense.hr_expense_form_view" view by using "inherit_id" on XML and add my own field to it? I guess I cant because, in terms of database, my own field doesn't stored in the "hr_expense" table but it is stored in my own database "expense_new.expense_new", am I right? 

So, If I inherit a view then I should write <field name="model">original_module.model</field> and on the action, <field name="res_model">original_module.model</field> Otherwise (e.g. in this case) I use my own model name, right?

Can somebody please help me out, any hint, reference or suggestion will be useful. Thx a lot!

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

Hi all, following is my solution for my question (this link helps me a lot, similar solution, https://www.odoo.com/forum/help-1/question/how-to-inherit-prototype-inheritance-from-one-module-to-another-new-module-86223), the key is Odoo don't know which view to apply, I believe that's why my issue occurs. Please point out if I missed anything! Thx.

PY file:

class expenseNew(models.Model):        
    _name = 'expense_new.expense_new'     
    # _inherits = {'hr.expense': 'expense_new_id'}
    _inherit = 'hr.expense' # you can still use "_inherits" tho if you need  
    expense_new_id = fields.Many2one('hr.expense', help="This is a many2one field in expense_new module, and this field is used as a link to hr.expense module")     
    # ......Override original fields......     
    name = fields.Char(string='Expense Summary', readonly=True, required=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]})     
    ...     
    # ......Extra fields/ my own fields......     
    calculate_total_amount = fields.Float(string='Total Cost', store=True, compute='_compute_amount_my', digits=dp.get_precision('Account'))     
    ...

XML file:

<record id="expense_new_tree_view" model="ir.ui.view">    
    <field name="name">expense_new.expense_new.tree.view</field>
    <field name="model">expense_new.expense_new</field>
    <field name="inherit_id" ref="hr_expense.view_expenses_tree"/>
    <field name="arch" type="xml">
        <field name="name"/>
        <field name="employee_id"/>
        <field name="date" required="True"/>
        <field name="state"/>
        <xpath expr="//field[@name='state']" position="after">
            <field name="calculate_total_amount"/>
        </xpath>
    </field>
</record>
<record id="expense_new_form_view" model="ir.ui.view">
    <field name="name">expense_new.expense_new.form.view</field>
    <field name="model">expense_new.expense_new</field>
    <field name="inherit_id" ref="hr_expense.hr_expense_form_view"/>
    <field name="arch" type="xml">
        <xpath expr="//field[@name='employee_id']" position="after">
            <field name="calculate_total_amount"/>
        </xpath>
    </field>
</record>
<!-- this is where magic happen -->
<record model="ir.actions.act_window.view" id="action_test_tree">
    <field name="sequence" eval="1"/>
    <field name="view_mode">tree</field>
    <field name="view_id" ref="expense_new_tree_view"/>
    <field name="act_window_id" ref="submit_your_expense_action"/>
</record>
<record model="ir.actions.act_window.view" id="action_test_form">
    <field name="sequence" eval="1"/>
    <field name="view_mode">form</field>
    <field name="view_id" ref="expense_new_form_view"/>
    <field name="act_window_id" ref="submit_your_expense_action"/>
</record>
<!-- this is where magic happen -->
<menuitem ... />


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

If you want to extend an existing view, you need to use XPath expression, XPath expression has two attributes the path (expr = "//path") that you want to place your custom field and the position(position=" after/before/replace/inside"), so here you should do like this;


<record id="expense_new_form_view" model="ir.ui.view">        
    <field name="name">expense_new.expense_new.form.view</field>        
    <field name="model">expense_new.expense_new</field>        
    <field name="inherit_id" ref="hr_expense.hr_expense_form_view"/>     
    <field name="arch" type="xml">            
        <xpath expr=”//path” position=”specify the position”>
		<field name=”your 1 custom field />
		<field name=”your 2 custom field />
	  </xpath>        
    </field>

For more details, refer to this link,

https://www.odoo.yenthevg.com/xpath-expressions-in-odoo-8/

0
Аватар
Відмінити
David Yao
Автор

hi Subhanullah, thx for reply. I have tried XPath before and it doesn't work as well, I just figure out the key to my problem is I need to tell Odoo which view I want. I will post my solution later. Hope it helps others

Subhanullah

Hi David,

Sounds good, but this is how you tell ODOO which view you want to access,

<field name="inherit_id" ref="hr_expense.hr_expense_form_view"/>

David Yao
Автор

yes, it is used to inherit certain view. BTW, What about "ir.actions.act_window.view"? Do you know what does it do? As you can see, I also used mode_id, view_id and act_window_id, I guess these are telling Odoo --- for A (act_window_id) action I want open B (view_id) view in C (form) way, am I right? Any documents you found for those?And please tell me if my understanding is incorrect. Thx.

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 Відповіді Переглядів Дія
View inheritance hiding a field
views inheritance
Аватар
Аватар
1
лист. 24
2811
Change the Position of field in Xpath Вирішено
views inheritance
Аватар
Аватар
Аватар
Аватар
Аватар
5
лип. 24
96517
How to extend a base template for a specific page only, without affecting other pages that use the same base template?
views inheritance
Аватар
Аватар
1
груд. 23
4171
removing elements from an inherited view
views inheritance
Аватар
Аватар
1
трав. 22
5267
I am building a custom module that has a dependent module that has extended the base view of res_partner. In my custom module I also have an inherited view of the base res_partner view. In it how do I hide the inherited view of my dependent module?
views inheritance
Аватар
0
січ. 20
3638
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
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