Leonardo Coelho
Leonardo Coelho

Reputation: 185

mxGraph codec.decode not adding cells to the actual graph

I am trying to load and convert an XML file to a mxGraph, however when I call the codec it doesn't update my graph.

This is my function, where the container is the div where my graph will be located:

function loadXml(container, xml)
{
   // Checks if the browser is supported
   if (!mxClient.isBrowserSupported())
   {
      // Displays an error message if the browser is not supported.
      mxUtils.error('Browser is not supported!', 200, false);
   }
   else
   {
     // Creates the graph inside the given container
     var graph = new mxGraph(container);

     // Adds rubberband selection to the graph
     new mxRubberband(graph);

     var doc = mxUtils.parseXml(xml);
     var codec = new mxCodec(doc);
     codec.decode(doc.documentElement, graph.getModel());
   }
};

PS: I inspected the doc.documentElement and it seems correct.

Upvotes: 2

Views: 790

Answers (2)

NickAth
NickAth

Reputation: 1112

I know this question is very old but I will give an answer for the community. You can parse the xml String using the mxUtils.parseXml(xml) function and get the cells out of it, then just import the cells into your mxGraph object, code shown below:

// Creates the graph inside the given container
var graph = new mxGraph(container);
let doc = mxUtils.parseXml(xml);
let codec = new mxCodec(doc);
codec.decode(doc.documentElement, graph.getModel());
let elt = doc.documentElement.firstChild;
let cells = [];
while (elt != null)
{  
    let cell = codec.decode(elt)
    if(cell != undefined){
        if(cell.geometry != undefined){
            if(cell.id != undefined && cell.parent != undefined && (cell.id == cell.parent)){
                elt = elt.nextSibling;
                continue;
            }
            cells.push(cell);
        }
    }
    elt = elt.nextSibling;
}
graph.addCells(cells);

This should do the trick :)

Upvotes: 0

Pierluca
Pierluca

Reputation: 69

I had this same issue pop up due to mxGraph being imported with Webpack's exports-loader, but I believe it could happen in other circumstances.

The mxCodec.prototype.decode(doc, graphModel) function expects all mxGraph objects/constructors to be available in the global scope through the window[objectName] accessor.

If mxGraph is encapsulated within a module, the objects are not within global scope and the decoding fails.

To confirm that this is the issue, add a breakpoint in mxGraph's mxCodec.prototype.decode function and load your page. You can then validate whether the objects can be found or not.

Upvotes: 3

Related Questions