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
Про цей форум
Допомога

Issue with understanding how Owl template integrate in odoo 14

Підписатися

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

Це запитання позначене
javascriptdevelopmentowlodooV14
1 Відповісти
1573 Переглядів
Аватар
Daniel Palumbo

Hello,

I am fairly new to developing on odoo with owl. I am currently working on a project that use odoo 14 and owl 1.4


I am trying to implement a component that will render in a page renderer by the backend controller. I have this timeline.js file


odoo.define('my_module.My2ChildTimeline', ['web.ajax'], function (require) {
"use strict";

const { Component } = owl;
const { useState, onWillStart, onMounted } = owl.hooks;
const ajax = require("web.ajax");

/**
* ChildTimeline component for displaying a timeline of records related to a specific child.
*/
class ChildTimeline extends Component {

setup() {
...

onWillStart(async () => {
try {
console.info("Loading initial records for ChildTimeline"); // Debug
await this.loadMore();
} catch (error) {
console.error("Error loading initial records:", error);
this.state.loading = false;
}
});

onMounted(() => {
window.addEventListener('scroll', this.onScroll.bind(this));
});
}

onScroll() {
const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 100;
if (!this.state.loading && this.state.hasMoreRecords && nearBottom) {
this.loadMore();
}
}

async loadMore() {
this.state.loading = true;

const res = await ajax.jsonRpc(`/somewhere`, "call", {
offset: this.state.offset,
limit: this.state.limit,
});
console.info("Loaded more records:", res); // Debug

const tempDiv = document.createElement('div');
tempDiv.innerHTML = res.html;

const newItems = [...tempDiv.children];
const container = this.el.querySelector('.timeline-list');

if (container) {
newItems.forEach(el => container.appendChild(el));
}

this.state.offset += this.state.limit;
this.state.hasMoreRecords = res.has_more_records;
this.state.loading = false;
}
};

ChildTimeline.template = "my_module.My2ChildTimelineComponent";

// Mount immediately when DOM is ready
if (document.getElementById("timeline-root")) {
const dataScript = document.getElementById("timeline-data");
const props = JSON.parse(dataScript.textContent);

owl.mount(ChildTimeline, {
target: document.getElementById("timeline-root"),
props,
});
}

return ChildTimeline;
});

and an xml component

<templates xml:space="preserve">
<t t-name="my_module.My2ChildTimelineComponent" owl="1">
<div class="timeline-list">
<t t-foreach="state.records" t-as="record" t-key="record.id">
<div class="timeline-card d-flex">
<t t-if="record.model == 'sponsorship_gift'">
<My2ChildTimelineRecordGiftComponent record="record"/>
</t>
<t t-elif="record.model == 'correspondence'">
<My2ChildTimelineRecordCorrespondenceComponent record="record"/>
</t>
<t t-else="">
<div>This record type is not supported in the timeline.</div>
</t>
</div>
</t>

<t t-if="state.loading">
<div class="text-center py-2">Loading more...</div>
</t>
</div>
</t>
</templates>


The script will be called in a my2_child_timeline.xml page

...
<div class="mb-3">
<div id="timeline-root">
<script type="application/json" id="timeline-data">
<t t-raw="json.dumps({
'child_id': child.id,
'records': records,
'pageable': pageable,
})"/>
</script>
<script type="module" src="/my_module/static/src/components/timeline/My2ChildTimeline.js"></script>
</div>
</div>
...


The issue is that it does not find the My2ChildTimelineComponent and I cannot figure it out what is the issue. Is there somebody who could help me?



0
Аватар
Відмінити
Daniel Palumbo
Автор

Thanks for sharing! It got better but I had to change a few things like 

odoo.__ready.then

does not exist in odoo 14. But I got over it and unfortunately the template is recognized but not used by the system. There is another underlying problem. After so many hours spend on it, I talked to my senior and we decided to go vanilla js for our use case and maybe later go back to owl as we will upgrade to odoo 17 probably

Thanks anyway!

Аватар
D Enterprise
Найкраща відповідь

Hii,


Here is updated code 


my_module/views/timeline_templates.xml


<odoo>

  <!-- Register the template -->

  <template id="My2ChildTimelineComponent">

    <t t-name="my_module.My2ChildTimelineComponent" owl="1">

      <div class="timeline-list">

        <t t-if="state.loading">

          <div class="text-center py-2">Loading more...</div>

        </t>

      </div>

    </t>

  </template>

</odoo>


Update __manifest__.py

Make sure this is included:


'qweb': [

    'views/timeline_templates.xml',

],


JavaScript Component


odoo.define('my_module.My2ChildTimeline', function (require) {

    "use strict";


    const { Component } = owl;

    const { useState, onWillStart, onMounted } = owl.hooks;

    const ajax = require("web.ajax");


    class ChildTimeline extends Component {

        setup() {

            this.state = useState({

                loading: false,

                offset: 0,

                limit: 10,

                hasMoreRecords: true,

            });


            onWillStart(() => this.loadMore());

            onMounted(() => window.addEventListener('scroll', this.onScroll.bind(this)));

        }


        async loadMore() {

            this.state.loading = true;

            const res = await ajax.jsonRpc(`/somewhere`, "call", {

                offset: this.state.offset,

                limit: this.state.limit,

            });


            const container = this.el.querySelector('.timeline-list');

            const tempDiv = document.createElement('div');

            tempDiv.innerHTML = res.html;

            [...tempDiv.children].forEach(el => container.appendChild(el));


            this.state.offset += this.state.limit;

            this.state.hasMoreRecords = res.has_more_records;

            this.state.loading = false;

        }


        onScroll() {

            const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 100;

            if (!this.state.loading && this.state.hasMoreRecords && nearBottom) {

                this.loadMore();

            }

        }

    }


    ChildTimeline.template = "my_module.My2ChildTimelineComponent";


    odoo.__ready.then(() => {

        const target = document.getElementById("timeline-root");

        const script = document.getElementById("timeline-data");


        if (target && script) {

            const props = JSON.parse(script.textContent);

            owl.mount(ChildTimeline, { target, props });

        }

    });


    return ChildTimeline;

});


In views/assets.xml:

<odoo>

  <template id="assets_frontend" inherit_id="web.assets_frontend" name="Timeline Assets">

    <xpath expr="." position="inside">

      <script type="module" src="/my_module/static/src/components/timeline/My2ChildTimeline.js"/>

    </xpath>

  </template>

</odoo>

And include assets.xml in __manifest__.py under data.


i hope it is use full

0
Аватар
Відмінити
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 can I use my only web url domain using odoo?
javascript development
Аватар
Аватар
1
вер. 25
1372
How to Load Related Many2Many Data (pos.ticket.type) into the Frontend?
javascript development
Аватар
0
черв. 25
1739
Odoo 18 POS - Discount Button Group Permissions Not Working
javascript development
Аватар
Аватар
2
черв. 25
1921
¿Cómo puedo crear un Dashboard con KPIs y gráficos con Chart.js?
javascript development
Аватар
0
квіт. 25
1913
Odoo icon change Вирішено
javascript development
Аватар
Аватар
2
січ. 25
2451
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
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