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

Custom Graph Widget

S'inscrire

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

Cette question a été signalée
OWLv18
1634 Vues
Avatar
Shreya Doodipala

I'm trying to make a custom graph widget that creates a bar chart from a JSON.

model file:

class CrmLead(models.Model):

    _inherit = 'crm.lead'

​

​graph_json = fields.Text(compute='_compute_raw_duration')


​def _compute_raw_duration(self):

        Stage = self.env['crm.stage'].search([])  # get all stages

        for record in self:

            # Get the original duration tracking (e.g., {"15": 71, "19": 85406})

            duration_dict = record.duration_tracking or {}


            # Initialize with all stage names and 0 durations

            mapped_duration = {stage.name: 0 for stage in Stage}


            # Add actual durations for stages that exist

            for stage_id_str, duration in duration_dict.items():

                try:

                    stage_id = int(stage_id_str)

                    stage = Stage.filtered(lambda s: s.id == stage_id)

                    if stage:

                        mapped_duration[stage.name] = duration

                    else:

                        mapped_duration[f"Unknown Stage ({stage_id})"] = duration

                except ValueError:

                    mapped_duration[f"Invalid Stage ID ({stage_id_str})"] = duration


            # Store the result

            record.graph_json = json.dumps(mapped_duration)

custom_crm/static/src/xml/graph_widget_template.xml

<?xml version="1.0" encoding="utf-8"?>

  <templates xml:space="preserve">

    <t t-name="custom_crm.GraphWidget">

      <canvas t-ref="canvas" width="400" height="200"></canvas>

    </t>

  </templates>

custom_crm/static/src/js/graph_widget.js

/** @odoo-module **/


import { Component, useRef } from "@odoo/owl";

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

import { loadJS } from "@web/core/assets";


console.log("✅ graph_widget.js JS loaded")


class GraphWidget extends Component {

    setup() {

        this.canvasRef = useRef("canvas");

        console.log("setup done")

    }

    async willStart() {

        await loadJS("/web/static/lib/Chart/Chart.js");

        console.log("✅ Chart.js loaded successfully");

    }


    mounted() {

        console.log("✅ GraphWidget mounted");


        const jsonString = this.props.record.data.graph_json || '{}';

        console.log("Raw JSON:", jsonString);  

        const data = JSON.parse(jsonString);


        const labels = Object.keys(data);

        const values = Object.values(data);


        //const ctx = this.refs.canvas.getContext('2d');

        const ctx = this.canvasRef.el.getContext('2d');

        if (!ctx) {

            console.warn("Canvas not found");

            return;

        }


        new Chart(ctx, {

            type: 'bar',

            data: {

                labels: labels,

                datasets: [{

                    label: 'Stage Time (s)',

                    data: values,

                    backgroundColor: 'rgba(54, 162, 235, 0.6)',

                    borderColor: 'rgba(54, 162, 235, 1)',

                    borderWidth: 1

                }]

            },

            options: {

                scales: {

                    y: { beginAtZero: true }

                }

            }

        });

    }


    static template = "custom_crm.GraphWidget";

}


registry.category("fields").add("json_graph", {

    component: GraphWidget,

    supportedTypes: ["Text"],

});

  • The canvas is present in the view, but there is no graph.
  • The console has the following messages only:

​✅ graph_widget.js JS loaded

​setup done

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é
[✅ SOLVED] How to get the current user id from a patched method of mail.Activity OWL component ?
OWL v18
Avatar
Avatar
1
mai 25
2397
Is it possible to sell on credit directly at the point of sale and leave the order pending payment?
v18
Avatar
Avatar
2
sept. 25
683
Skills needed for Odoo OWL Development ?
OWL
Avatar
Avatar
Avatar
2
sept. 25
2523
How to segrigate a product into multiple products & at the same time i have to manufacture that product also with separate BOM? Résolu
v18
Avatar
Avatar
1
juin 25
1837
Turkey live currency rates from TCMB
v18
Avatar
Avatar
Avatar
3
mars 25
2957
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