Перейти к содержимому
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
Об этом форуме
Помощь

Dynamically update cart icon after adding products from a reorder popup in Custom Odoo portal

Подписаться

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

Этот вопрос был отмечен
portal
1 Ответить
263 Представления
Аватар
Saksham Khanal

I’ve built a custom portal dashboard in Odoo with a “reorder” feature. When a user clicks reorder, a popup appears showing products from a previous order, and the user can add them back to the cart.

The problem: after adding products via the popup, the cart icon in the navigation bar does not update automatically. By default, Odoo’s “Order Again” redirects users to the shop/cart page, which updates the cart icon, but I don’t want to redirect—the popup closes instead.

I want a clean way to update or rerender the cart icon dynamically after adding products from the popup, ideally using Odoo’s framework (RPC calls, JS widgets, or events) rather than direct DOM hacks.


website_sale_reorder.js

export class ReorderConfirmationDialog extends ConfirmationDialog {

static template = "website_sale.ReorderConfirmationDialog";

}

export class ReorderDialog extends Component {

static template = "website_sale.ReorderModal";

static props = {

close: Function,

orderId: Number,

accessToken: String,

};

static components = {

Dialog,

};

setup() {

this.orm = useService("orm");

this.dialogService = useService("dialog");

this.formatCurrency = formatCurrency;

onWillStart(this.onWillStartHandler.bind(this));

}

async onWillStartHandler() {

// Cart Qty should not change while the dialog is opened.

this.cartQty = parseInt(sessionStorage.getItem("website_sale_cart_quantity"));

if (!this.cartQty) {

this.cartQty = await rpc("/shop/cart/quantity");

}

// Get required information about the order

this.content = await rpc("/my/orders/reorder_modal_content", {

order_id: this.props.orderId,

access_token: this.props.accessToken,

});

// Get required information about each products

for (const product of this.content.products) {

product.debouncedLoadProductCombinationInfo = debounceFn(() => {

this.loadProductCombinationInfo(product).then(this.render.bind(this));

}, 200);

}

}

get total() {

return this.content.products.reduce((total, product) => {

if (product.add_to_cart_allowed) {

total += product.combinationInfo.price * product.qty;

}

return total;

}, 0);

}

get hasBuyableProducts() {

return this.content.products.some((product) => product.add_to_cart_allowed);

}

async loadProductCombinationInfo(product) {

for (const comboItem of product.selected_combo_items) {

comboItem.combinationInfo = await rpc("/website_sale/get_combination_info", {

product_template_id: cReorderDialogomboItem.product_template_id,

product_id: comboItem.product_id,

combination: comboItem.combination,

add_qty: comboItem.qty,

context: {

website_sale_no_images: true,

},

});

}

product.combinationInfo = await rpc("/website_sale/get_combination_info", {

product_template_id: product.product_template_id,

product_id: product.product_id,

combination: product.combination,

add_qty: product.qty,

context: {

website_sale_no_images: true,

},

});

}

getWarningForProduct(product) {

if (!product.add_to_cart_allowed) {

return _t("This product is not available for purchase.");

}

return false;

}

changeProductQty(product, newQty) {

const productNewQty = Math.max(0, newQty);

const qtyChanged = productNewQty !== product.qty;

product.qty = productNewQty;

this.render(true);

if (!qtyChanged) {

return;

}

product.debouncedLoadProductCombinationInfo();

}

onChangeProductQtyInput(ev, product) {

const newQty = parseFloat(ev.target.value) || product.qty;

this.changeProductQty(product, newQty);

}

async confirmReorder(ev) {

if (this.confirmed) {

return;

}

this.confirmed = true;

const onConfirm = async () => {

await this.addProductsToCart();

window.location = "/shop/cart";

};

if (this.cartQty) {

// Open confirmation modal

this.dialogService.add(ReorderConfirmationDialog, {

body: _t("Do you wish to clear your cart before adding products to it?"),

confirm: async () => {

await rpc("/shop/cart/clear");

await onConfirm();

},

cancel: onConfirm,

dismiss: () => {}, // Prevents fallback of 'cancel' from Confirmation Dialog

});

} else {

await onConfirm();

}

}

async addProductsToCart() {

for (const product of this.content.products) {

if (!product.add_to_cart_allowed) {

continue;

}

if (product.selected_combo_items.length) {

await rpc("/website_sale/combo_configurator/update_cart", {

combo_product_id: product.product_id,

quantity: product.qty,

selected_combo_items: product.selected_combo_items,

});

} else {

await rpc("/shop/cart/update_json", {

product_id: product.product_id,

add_qty: product.qty,

no_variant_attribute_value_ids: product.no_variant_attribute_value_ids,

product_custom_attribute_values: JSON.stringify(product.product_custom_attribute_values),

display: false,

});

}

}

}

}

This is the dialog that I have inherited and made changes to 


website_sale>templates.xml

<template id="header_cart_link" name="Header Cart Link">

<t t-nocache="The number of products is dynamic, this rendering cannot be cached."

t-nocache-_icon="_icon"

t-nocache-_text="_text"

t-nocache-_badge="_badge"

t-nocache-_badge_class="_badge_class"

t-nocache-_icon_wrap_class="_icon_wrap_class"

t-nocache-_text_class="_text_class"

t-nocache-_item_class="_item_class"

t-nocache-_link_class="_link_class">

<t t-set="website_sale_cart_quantity" t-value="request.session['website_sale_cart_quantity'] if 'website_sale_cart_quantity' in request.session else website.sale_get_order().cart_quantity or 0"/>

<t t-set="show_cart" t-value="website.has_ecommerce_access()"/>

<li t-attf-class="#{_item_class} divider d-none"/> <!-- Make sure the cart and related menus are not folded (see autohideMenu) -->

<li t-attf-class="o_wsale_my_cart #{not show_cart and 'd-none'} #{_item_class}">

<a href="/shop/cart" t-attf-class="#{_link_class}" aria-label="eCommerce cart">

<div t-attf-class="#{_icon_wrap_class}">

<i t-if="_icon" class="fa fa-shopping-cart fa-stack"/>

<sup t-attf-class="my_cart_quantity badge bg-primary #{_badge_class} #{'d-none' if (website_sale_cart_quantity == 0) else ''}" t-esc="website_sale_cart_quantity" t-att-data-order-id="request.session.get('sale_order_id', '')"/>

</div>

<span t-if="_text" t-attf-class="#{_text_class}">My Cart</span>

</a>

</li>

</t>

</template>


This is the template that I want to re-render

0
Аватар
Отменить
Аватар
Cybrosys Techno Solutions Pvt.Ltd
Лучший ответ

Hi,


Odoo’s website_sale.cart public widget listens for the updateCart event.

So, after your RPC calls in addProductsToCart(), simply trigger that event using the website’s event bus:


Try the following code.


import { publicWidget } from "@web/legacy/js/public/public_widget";

import { browser } from "@web/core/browser/browser";


async addProductsToCart() {

    for (const product of this.content.products) {

        if (!product.add_to_cart_allowed) continue;


        if (product.selected_combo_items.length) {

            await rpc("/website_sale/combo_configurator/update_cart", {

                combo_product_id: product.product_id,

                quantity: product.qty,

                selected_combo_items: product.selected_combo_items,

            });

        } else {

            await rpc("/shop/cart/update_json", {

                product_id: product.product_id,

                add_qty: product.qty,

                no_variant_attribute_value_ids: product.no_variant_attribute_value_ids,

                product_custom_attribute_values: JSON.stringify(product.product_custom_attribute_values),

                display: false,

            });

        }

    }


    // Trigger cart update after products are added

    browser.trigger("updateCart");

}


Hope it helps

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
Trying to replace default “Invoices & Bills” breadcrumb in Odoo portal
portal
Аватар
Аватар
1
нояб. 25
314
is possible to add 2 filters to the web portal similar to searchbar_filters?
portal
Аватар
Аватар
Аватар
2
июл. 25
2212
How can I allow one portal user to see another portal user's information (like Sales Orders, Invoices)? Решено
portal
Аватар
Аватар
1
мая 24
3801
Use worksheets in Odoo Portal
portal
Аватар
Аватар
2
февр. 24
2965
Portail Access
portal
Аватар
0
апр. 23
2085
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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