Reputation: 479
I am trying to clone a PF5 line chart from one xhtml page (The data page) to another xhtml page (the report page). The chart is:
<div id="lchart">
<p:chart id="ulinechart" type="line" rendered="#{chartDataBean.showLineChart}"
model="#{chartDataBean.userdatLineModel}" responsive="true"/>
</div>
<button id="reportaction" class="controlbutton"
type="button onclick="copyChart()">Add Chart
</button>
function copyChart() {
var idincrement = 0;
var original = document.getElementById('topform:ulinechart');
var reportchartholder = document.getElementById('rchartholder');
var clone = original.cloneNode(true);
clone.id = 'ulinechart' + ++idincrement;
reportchartholder.parentNode.appendChild(clone);
}
The chart LEGEND and title only are cloned but not the chart image itself.
I then tried to clone the chart in jQuery as follows:
function copyChart() {
var imageData = $('ulinechart').jqplotToImageStr({});
var imageElem = $('<img/>').attr('src', imageData);
$('#rchartholder').append(imageElem);
}
Produced the following error:
Uncaught TypeError: Cannot read property 'left' of undefined at e.fn.init.L.fn.jqplotToImageCanvas (charts.js.xhtml?ln=primefaces&v=5.3:1) at e.fn.init.L.fn.jqplotToImageStr (charts.js.xhtml?ln=primefaces&v=5.3:1) at copyChart (dashboard.js.xhtml?ln=js:172) at HTMLButtonElement.onclick (DatDashT.xhtml:1)
The error refers to the second line of the function:
var imageData = $('ulinechart').jqplotToImageStr({});
I am not able to find what this error and how to approach it. It seems to be related with the primefaces chart.js file.
Researching suggests that TypeErrors usually occurs where there are conflicts between manually added jQuery files and the PF jQuery.
Adding jQuery to PrimeFaces results in Uncaught TypeError over all place
I double checked that I am using the bundled PF jQuery. Next, I checked to see if there is some problem with the chart.js file itself and found this:
https://forum.primefaces.org/viewtopic.php?f=3&t=39856
I tried to apply the fixes suggested adding:
<h:outputScript name="charts/charts.js" library="primefaces" />
<h:outputStylesheet name="charts/charts.css" library="primefaces" />
to my template page. The error is exactly the same.
1) Any guidance on the error? 2) Any advice on the correct approach to render the chart? Should I use the first JS method? The second jQuery image method? An alternative method? Thanks in advance for any advice!
Upvotes: 0
Views: 355
Reputation: 479
This is solved. I think the jQuery error was caused by the element div not being read properly. Since colons in jQuery are reserved for jQuery selectors I had to use escape key to define the full PF path for the element div like this:
function copyChart() {
var imageData = jQuery('#topform\\:ulinechart').jqplotToImageStr({});
var imageElem = jQuery('<img/>').attr('src', imageData);
jQuery('#rchartholder').append(imageElem);
}
I am now able to clone the chart as an image. Hope this helps.
Upvotes: 0