Ask a Jedi: Hack for percentage based CFCHART

Mike asked:

Do you know if there is a way to set an auto width to cfchart? Setting a pixel width doesn't work well when coding for touch screens with the different widths for portrait and landscape views. Thanks for any help you can provide.

Interesting question. You may notice that cfchart’s height and width attributes only accept real numbers, not percentages. I first tried a hack where I modified the output HTML containing the SWF:

<cfset d = []> <cfset d[1] = {date="1/1/2011 03:22", value=99}> <cfset d[2] = {date="1/2/2011 04:22", value=80}> <cfset d[3] = {date="1/3/2011 09:22", value=79}>

<cfsavecontent variable=”html”> <cfchart chartheight=”500” chartwidth=”500” title=”Test Chart” backgroundcolor=”red”>

   &lt;cfchartseries type="bar"&gt;
           &lt;cfloop index="item" array="#d#"&gt;
                   &lt;cfchartdata item="#item.date#" value="#item.value#"&gt;
           &lt;/cfloop&gt;
   &lt;/cfchartseries&gt;

</cfchart> </cfsavecontent>

<cfset html=replace(html, “WIDTH=”“500”””, “WIDTH=”“100%”””,”all”)> <cfoutput>#html#</cfoutput> </code>

Technically that works - the resultant object/embed tags are updated and the SWF takes 100% of the available width, but the actual chart inside the SWF doesn’t size with the change. I then tried the non-interactive version with an image. Because an image map is used normally, I had to store the bits of the image to the file system and then output it.

<cfset d = []> <cfset d[1] = {date="1/1/2011 03:22", value=99}> <cfset d[2] = {date="1/2/2011 04:22", value=80}> <cfset d[3] = {date="1/3/2011 09:22", value=79}>

<cfchart chartheight=”500” chartwidth=”500” title=”Test Chart” backgroundcolor=”red” format=”png” name=”img”>

   &lt;cfchartseries type="bar"&gt;
           &lt;cfloop index="item" array="#d#"&gt;
                   &lt;cfchartdata item="#item.date#" value="#item.value#"&gt;
           &lt;/cfloop&gt;
   &lt;/cfchartseries&gt;

</cfchart>

<cfset fileWrite(expandPath(“./mychart.png”),img)>

<style> .chartimage { width: 100%; } </style> <img src=”mychart.png” class=”chartimage”> </code>

If you do use this code (and it does actually work), you would want to modify it to not generate and write on every request. It should intelligently determine if it needs to generate a new file first. I’ll also remind people that while cfchart is pretty powerful, it’s also a bit old. It is not the only way to do charting in ColdFusion. There are numerous other solutions as well.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments