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

How to fix TypeError: Cannot convert undefined or null to object

Підписатися

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

Це запитання позначене
javascript18.0
1 Відповісти
6263 Переглядів
Аватар
Omar El Zaatari

Hello, I'm trying to integrate an open source odoo 16 module that I found online in Odoo 18 but I'm receiving the following error in the developer console of chrome.

web.assets_web.min.js:17 Uncaught Error: Error while loading "@datetime_calendar/components/datetime_calendar":
TypeError: Cannot convert undefined or null to object
    at ModuleLoader.startModule (web.assets_web.min.js:17:225)
    at ModuleLoader.startModules (web.assets_web.min.js:16:57)
    at ModuleLoader.addJob (web.assets_web.min.js:13:39)
    at ModuleLoader.define (web.assets_web.min.js:12:127)
    at web.assets_web.min.js:20259:6

And here's the code:

/* @odoo-module */

import { dateField, DateTimeField } from "@web/views/fields/datetime/datetime_field";import { patch } from "@web/core/utils/patch";const { DateTime } = luxon;const { useState } = owl;

console.log(DateTimeField);

function setCalendar(date, calendar, format = DateTime.DATE_FULL) { console.log("setCalendar called with:", date, calendar); if (!date) return ''; const luxonDate = DateTime.fromISO(date); if (!luxonDate.isValid) return ''; return luxonDate.reconfigure({ outputCalendar: calendar }).toLocaleString(format);}

patch(dateField.prototype, { setup() { this._super?.(); console.log("setup: Value of this.props.value:", this.props.value);

this.calendar = useState({ 'hebrew': setCalendar(this.props.value || DateTime.now().toISO(), "hebrew"), 'islamic': setCalendar(this.props.value || DateTime.now().toISO(), "islamic"), }); },

onDateTimeChanged(date) { this._super?.(date); this.calendar.islamic = setCalendar(date, "islamic"); },

get formattedValue() { return this.isDateTime ? setCalendar(this.props.value, "islamic", DateTime.DATETIME_MED) : setCalendar(this.props.value, "islamic"); },});

patch(DateTimeField.prototype, { setup() { this._super?.(); console.log("setup: Value of this.props.value:", this.props.value);

this.calendar = useState({ 'hebrew': setCalendar(this.props.value || DateTime.now().toISO(), "hebrew"), 'islamic': setCalendar(this.props.value || DateTime.now().toISO(), "islamic"), }); },

onDateTimeChanged(date) { this._super?.(date); this.calendar.islamic = setCalendar(date, "islamic"); },

get formattedValue() { return setCalendar(this.props.value, "islamic"); },});

Why is this error showing, and how can I fix it?
Thank you!

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

The error TypeError: Cannot convert undefined or null to object typically occurs because an object or property you're trying to use in your code is either undefined or null. Based on the provided code and error message, here's a detailed analysis and fix for the issue:

Root Cause

The error arises when the patch function tries to apply a patch to dateField.prototype or DateTimeField.prototype, but one or both of these are undefined or improperly imported in your module.

The problem seems to stem from this line:

javascriptCopy codeimport { dateField, DateTimeField } from "@web/views/fields/datetime/datetime_field";
  • Odoo 18 (or 16) may not define dateField or DateTimeField as exported members in the module @web/views/fields/datetime/datetime_field. This means you're importing something that does not exist or has changed in the newer version.

Steps to Fix

1. Check the Imports

Ensure the imports match the actual exported objects in @web/views/fields/datetime/datetime_field. Check the source code of this module to confirm whether dateField and DateTimeField are available.

  • You can inspect Odoo’s source code for this module or log the imported objects:
    javascriptCopy codeimport * as datetimeField from "@web/views/fields/datetime/datetime_field";
    console.log(datetimeField);
    
  • If dateField or DateTimeField is undefined, it means these are not part of the module's exports.

2. Update the Module Path or Import Statement

In newer Odoo versions, there might be changes in the structure of the module. Check if dateField or DateTimeField is located in another module. For instance:

javascriptCopy codeimport { DateTimeField } from "@web/views/fields/fields";

If dateField does not exist, you can drop it from your imports.

3. Ensure Luxon Is Properly Imported

Ensure that the luxon library is available in your environment and properly imported:

javascriptCopy codeimport { DateTime } from "luxon";

Odoo typically includes Luxon in its dependencies, but verify this by logging DateTime:

javascriptCopy codeconsole.log(DateTime);

If DateTime is undefined, install Luxon in your development environment:

bashCopy codenpm install luxon

4. Update the patch Function Calls

The patch function attempts to extend the prototypes of dateField and DateTimeField. If either is undefined, it will throw an error.

To prevent this error, add defensive checks before applying patches:

javascriptCopy codeif (dateField) {
    patch(dateField.prototype, {
        setup() {
            this._super?.();
            console.log("setup: Value of this.props.value:", this.props.value);

            this.calendar = useState({
                'hebrew': setCalendar(this.props.value || DateTime.now().toISO(), "hebrew"),
                'islamic': setCalendar(this.props.value || DateTime.now().toISO(), "islamic"),
            });
        },

        onDateTimeChanged(date) {
            this._super?.(date);
            this.calendar.islamic = setCalendar(date, "islamic");
        },

        get formattedValue() {
            return this.isDateTime
                ? setCalendar(this.props.value, "islamic", DateTime.DATETIME_MED)
                : setCalendar(this.props.value, "islamic");
        },
    });
}

if (DateTimeField) {
    patch(DateTimeField.prototype, {
        setup() {
            this._super?.();
            console.log("setup: Value of this.props.value:", this.props.value);

            this.calendar = useState({
                'hebrew': setCalendar(this.props.value || DateTime.now().toISO(), "hebrew"),
                'islamic': setCalendar(this.props.value || DateTime.now().toISO(), "islamic"),
            });
        },

        onDateTimeChanged(date) {
            this._super?.(date);
            this.calendar.islamic = setCalendar(date, "islamic");
        },

        get formattedValue() {
            return setCalendar(this.props.value, "islamic");
        },
    });
}

This ensures the patch is only applied when the target object exists.


5. Debugging Missing Objects

If dateField or DateTimeField is completely missing from Odoo 18, it may have been deprecated or replaced. In this case:

  1. Search the Odoo source code for similar objects.
  2. Update your module to patch the replacement objects or write a custom implementation.

Conclusion

Here’s the key takeaway:

  • Ensure dateField and DateTimeField exist in your version of Odoo.
  • Use defensive programming (e.g., checks for undefined) when applying patches.
  • Verify dependencies like luxon are correctly installed and accessible.

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 Відповіді Переглядів Дія
Cannot import @website_sale/js/utils
javascript
Аватар
Аватар
2
лист. 25
556
How To Hide Action Report By Picking Type Code ?
18.0
Аватар
Аватар
Аватар
3
лист. 25
532
How do I set up budget management / planning Вирішено
18.0
Аватар
Аватар
2
серп. 25
1066
Cómo cerrar una transferencia interna al recibirla desde la vista de código de barras stock.picking
javascript
Аватар
0
лип. 25
1114
Why use the Lazy Translation function _lt()
javascript
Аватар
Аватар
1
лип. 25
6402
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
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