This tutorial will demonstrate how to do code re-use using a user defined function to generate graph colors on the fly.

Let's say you have to query your database and want to show your visitors a nice graph, however if you do it out of the box then you will end up with a graph that uses a single color for all elements... hard to read to say the least.

Now you can come up with a list of hex colors, pass them in and then you're good to go... but there has to be a better way... there is... using a UDF... let's see one now:

    function returnRandomHEXColors(numToReturn){

        var returnList = ""; // define a clear var to return in the end with a list of colors
        var colorTable = "A,B,C,D,E,F,0,1,2,3,4,5,6,7,8,9"; // define all possible characters in hex colors

        // loop through and generate as many colors as defined by the request
        for (i=1; i LTE val(numToReturn); i=i+1){
            // clear the color list
            tRandomColor = "";
            for(c=1; c lte 6; c=c+1){
            // generate a random (6) character hex code
            tRandomColor = tRandomColor & listGetAt(colorTable, randRange(1, listLen(colorTable)));

        // append it to the list to return in the end
        returnList = listAppend(returnList, tRandomColor);
        // return the list of random colors
        return returnList;


That UDF simply loops through and generates random colors... it's that simple! Now you need to have the UDF (cfscript) code above on the same page or request as the cfchart request. What I tend to do with UDF's is include a file in the Application.cfm/Application.cfc page then it will be available at all times in your application (with the exception of custom tags... on those you have to also include it again!)

Anyways, now let's see how you would call it on your actual code, to simplify your life:

<cfquery name="qGetTutorialStats" datasource="#application.dsn#">
    select tutorialID, title, views
    from tutorials
    where authorID = #val(session.authorID)#
    order by title

<!--- my stats --->
<div align="center">
    <cfchart format="flash" title="Tutorial Views" chartwidth="700" chartheight="400" show3d="yes">
        <cfchartseries type="bar" colorlist="#returnRandomHEXColors(qGetTutorialStats.recordCount)#">
            <cfloop query="qGetTutorialStats">
                <cfchartdata item="#title#" value="#views#" />


That's all she wrote... The UDF is called in the green code above... it's that simple! Let me know if you have any questions or need additional help with this.... see you in the forums!

About This Tutorial
Author: Pablo Varando
Skill Level: Beginner 
Platforms Tested: CF5,CFMX,CF8,BlueDragon,Railo
Total Views: 88,351
Submission Date: June 05, 2009
Last Update Date: June 05, 2009
All Tutorials By This Autor: 47
Discuss This Tutorial

Sponsored By...
Healing Touch Massage - $39.00 - 50 Minute Deep Tissue Massage Dripping Springs, Texas!