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
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Consulting
    • Accounting Firm
    • Партнер Odoo
    • Marketing Agency
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • 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
Про цей форум
Допомога

Request one2many tree refresh from widget (javascript call)

Підписатися

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

Це запитання позначене
javascripttreeviewwidgetrefresh
2 Відповіді
8241 Переглядів
Аватар
Maxime MARAIS

Hi All,

I'm adapting the "web_one2many_selectable_10" widget in order to make it more flexible. To do it short, this widget displays a checkbox on the left for each record referenced in a one2many field + add a button on top of the list + call an action server side with selected record IDs.

I managed to do what I wanted to with this widget: custom text, custom action defined in the caller template. My problem is, after I called a function server-side, to be able to update the tree view displayed in order to reflect changes made server side.

To do, so I'm trying to refresh only the <tree> node defined in the template for the one2many field displayed with this widget. Up to now, I made it the ugly way by refreshing the whole view (it's not efficient at all) with this javascript call:

self.do_action('reload');

I noticed, this seems to be achievable. Using the "Lot split" button in stock operation ("Operation" tab, when products have lots or serial numbers: opens a pop-up window, you can then register lots or serial numbers and, when you save and close the pop-up, only the tree view in parent view is updated.)

Up to now, I could not figure how the hell this happens and how to call this action from my widget. Help would be much appreciated.

Bellow, the full code.

/*
    Usage in templates:
    <field name="One2many_name" widget="one2many_selectable" action="server_action" callback="javascript_callback>
    If defined, "server_action" will be RPC called and executed by server
    If defined, "javascript_callback" will be executed client side after "server_action" is executed server side,
    if also defined. "javascript_callback" will be sent results returned from "server_action" if any.
*/
odoo.define('web_one2many_selectable_10.form_widgets', function (require) {
    "use strict";
    var core = require('web.core');
    var _t = core._t;
    var Model = require('web.Model');
    var FieldOne2Many = core.form_widget_registry.get('one2many');
    function executeFunctionByName(functionName, context /*, args */) {
        var args = Array.prototype.slice.call(arguments, 2);
        var namespaces = functionName.split(".");
        var func = namespaces.pop();
        for (var i = 0; i < namespaces.length; i++) {
            context = context[namespaces[i]];
        }
        return context[func].apply(context, args);
    }
    var One2ManySelectable = FieldOne2Many.extend({
        template: 'One2ManySelectable',
        events: {
            'click .web_one2many_selectable': 'button_pressed',
        },
        multi_selection: true,
        // Retrieve options from caller template to have them available in the widget 'One2ManySelectable' template
        init: function () {
            this._super.apply(this, arguments);
            // Default options
            this.options = {
                caption: 'Apply',
                action: null,
                callback: null
            }
            // User defined options from field attributes in caller template
            if (arguments[1].attrs.hasOwnProperty('options')) {
                this.options = JSON.parse(arguments[1].attrs.options);
            }
            // Translate caption
            this.options.caption = _t(this.options.caption)
        },
        start: function () {
            this._super.apply(this, arguments);
        },
        // Catch button pressed event, collect IDs, call action server side, then callback client side if defined.
        button_pressed: function () {
            var self = this;
            var selected_ids = self.get_selected_ids_one2many();
            if (selected_ids.length === 0) {
                this.do_warn(_t("You must choose at least one record."));
                return false;
            }
            // If an action was defined in template, let's call this action server side
            if (this.options.action) {
                /* Here is a python example function to parse the selected objects
                    @api.multi
                    def your_action_name(self):
                         for record in self:
                             print record
                */
                var model_obj = new Model(this.dataset.model);
                model_obj.call(this.options.action, [selected_ids], {context: self.dataset.context})
                    .then(function (result) {
                        // If a callback was defined in template, let's call this callback client side with
                        // results from server call above.
                        if (self.options.callback) {
                            executeFunctionByName(self.options.callback, window, result);
                        } else {
                            self.do_action('reload');
                        }
                    });
            }
        },
        // Collect the object IDs for checked checkboxes
        get_selected_ids_one2many: function () {
            var ids = [];
            this.$el.find('td.o_list_record_selector input:checkbox:checked').closest('tr').each(function () {
                ids.push(parseInt($(this).context.dataset.id));
            });
            return ids;
        }
    });
    // Register this widget
    core.form_widget_registry.add('one2many_selectable', One2ManySelectable);

    // Make the widget available for other add-ons
    return {
        One2ManySelectable: One2ManySelectable
    }
});



0
Аватар
Відмінити
Maxime MARAIS
Автор

Also tried the bellow instead of do_action('reload'):

var view = self.get_active_view();

view.controller.current_min = 1;

view.controller.reload_content();

without more success.

Аватар
Maxime MARAIS
Автор Найкраща відповідь

After further investigations (thanks Chrome Developer Tool and JavaScript debugger), I finally found the mechanism behind the magic.

Instead of:

self.do_action('reload');

 Replaced with:

var controller = self.get_active_view().controller;
$.each(selected_ids,function(){
    controller.reload_record(controller.records.get(this));
});

Complete code below:

/*
Usage in templates:

<field name="One2many_name" widget="one2many_selectable" action="server_action" callback="javascript_callback>

If defined, "server_action" will be RPC called and executed by server
If defined, "javascript_callback" will be executed client side after "server_action" is executed server side,
if also defined. "javascript_callback" will be sent results returned from "server_action" if any.
*/

odoo.define('web_one2many_selectable_10.form_widgets', function (require) {
"use strict";

var core = require('web.core');
var _t = core._t;
var Model = require('web.Model');
var FieldOne2Many = core.form_widget_registry.get('one2many');

function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}

var One2ManySelectable = FieldOne2Many.extend({
template: 'One2ManySelectable',

events: {
'click .web_one2many_selectable': 'button_pressed',
},

multi_selection: true,

// Retrieve options from caller template to have them available in the widget 'One2ManySelectable' template
init: function () {
this._super.apply(this, arguments);

// Default options
this.options = {
caption: 'Apply',
action: null,
callback: null
}

// User defined options from field attributes in caller template
if (arguments[1].attrs.hasOwnProperty('options')) {
this.options = JSON.parse(arguments[1].attrs.options);
}

// Translate caption
this.options.caption = _t(this.options.caption)
},

start: function () {
this._super.apply(this, arguments);
},

// Catch button pressed event, collect IDs, call action server side, then callback client side if defined.
button_pressed: function () {
var self = this;
var selected_ids = self.get_selected_ids_one2many();
if (selected_ids.length === 0) {
this.do_warn(_t("You must choose at least one record."));
return false;
}

// If an action was defined in template, let's call this action server side
if (this.options.action) {
/* Here is a python example function to parse the selected objects

@api.multi
def your_action_name(self):
for record in self:
print record
*/

var model_obj = new Model(this.dataset.model);
model_obj.call(this.options.action, [selected_ids], {context: self.dataset.context})
.then(function (result) {
if (self.options.callback) {
// If a callback was defined in template, let's call this callback client side with
// results from server call above.
executeFunctionByName(self.options.callback, window, result);
} else {
// Else simply refresh the display for the selected records
var controller = self.get_active_view().controller;
$.each(selected_ids,function(){
controller.reload_record(controller.records.get(this));
});
}
});
}
},

// Collect the object IDs for checked checkboxes
get_selected_ids_one2many: function () {
var ids = [];
this.$el.find('td.o_list_record_selector input:checkbox:checked').closest('tr').each(function () {
ids.push(parseInt($(this).context.dataset.id));
});
return ids;
}

});

// Register this widget
core.form_widget_registry.add('one2many_selectable', One2ManySelectable);

// Make the widget available for other add-ons
return {
One2ManySelectable: One2ManySelectable
}

});
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 Відповіді Переглядів Дія
Set hotkey focus input text
javascript widget
Аватар
0
серп. 20
3930
creation a widget of items as tree
javascript treeview widget items odoo
Аватар
0
черв. 20
3397
Javascript migration from 10 to 8
javascript widget
Аватар
0
лют. 18
4167
Reload/refresh data in one2many form view after dragging records through widget handle
widget refresh
Аватар
1
лист. 17
12684
Odoo widget $el
javascript widget
Аватар
0
вер. 17
5032
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
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