Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Validations
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Maison d’hôtes
    • Distributeur de boissons
    • Hôtel
    Immobilier
    • Agence immobilière
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consultance
    • Cabinet d'expertise comptable
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Métal
    • Meubles
    • Alimentation
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et support
    • Systèmes photovoltaïques
    • Cordonnier
    • Services de nettoyage
    • Services CVC
    Autres
    • Organisation à but non lucratif
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Browse all Industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenez partenaire
    • Services for Partners
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

Request one2many tree refresh from widget (javascript call)

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
javascripttreeviewwidgetrefresh
2 Réponses
8351 Vues
Avatar
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
Avatar
Ignorer
Maxime MARAIS
Auteur

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.

Avatar
Maxime MARAIS
Auteur Meilleure réponse

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
Avatar
Ignorer
Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
Set hotkey focus input text
javascript widget
Avatar
0
août 20
4024
creation a widget of items as tree
javascript treeview widget items odoo
Avatar
0
juin 20
3517
Javascript migration from 10 to 8
javascript widget
Avatar
0
févr. 18
4257
Reload/refresh data in one2many form view after dragging records through widget handle
widget refresh
Avatar
1
nov. 17
12818
Odoo widget $el
javascript widget
Avatar
0
sept. 17
5143
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenez partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة 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 est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

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