Multi Level Dropdown in newform.aspx

Multi Level Dropdowns in NewForm

Multi Level Dropdowns in NewForm.aspx / EditForm.aspx

Step 1: Create one Custom List where it holds all Multilevel data. (Backend
database for Multi Levels)

Step 2: Create the MainList Customlist with the following Columns

Level 1-> Single line of text
Level 2-> Single line of text
Level 3-> Single line of text

Step 3: Open Newform.aspx [MainList]  in SharePoint Designer

i
 – NewForm.aspx has to be customized  so Close the existing
ListFormWebpart

 Step 4: Include Customized form and include three dropdowns (level1,
level2,level2)
         Ex: for Level1
<SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="New" FieldName="Level_x0020_1"
__designer:bind="{ddwrt:DataBind(‘i’,concat(‘ff2′,$Pos),’Value’,’ValueChanged’,’ID’,ddwrt:EscapeDelims(string(@ID)),’@Level_x0020_1′)}"/>
<select id="Level1"></select>

Step 5:Create one javascript file[main.js] and include in newform.aspx
    <script language="javascript" src="Main.js"></script>

Step 6: In Main.js Use Microsoft.XMLDom to access the sharePoint list as XML
Microsoft.XMLDOM will work only in IE. use XMLHttpRequest to make it work in
Firefox and Chrome
|   xml_doc = new ActiveXObject("Microsoft.XMLDOM");

Step7:  Create three different arrays and one object and collect all levels
value to respective array

var L1=new Array()
var L2=new Array()
var l3=new Array()
var DataC=[];
xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("<server>/_vti_bin/owssvr.dll?Cmd=Display&List={ListID}&Query=*&XMLDATA=TRUE");

//STRVALUE = xml_doc.documentElement.childNodes(1).childNodes;
STRVALUE = xml_doc.getElementsByTagName("z:row");
alert(STRVALUE.length)
for(i=0;i<STRVALUE.length;i++)
{
L1[i]=STRVALUE[i].getAttribute("ows_Level1")
L2[i]=STRVALUE[i].getAttribute("ows_Level2")
L3[i]=STRVALUE[i].getAttribute("ows_Level3")
}


Step 8: Get unique values of first level value. Use the below javascript
function to get unique values for array

Array.prototype.unique = function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};

Step 9: Get unique values for first level and populate the first dropdown

L1=L1.unique();
for(j=0;j<L1.length;j++)
document.getElementById("Level1").options.add(new Option(L1[j],L1[j]))

Step 10: Collate all level2 and level 3 data into objects
  Ex: For Level 2 Data object DataC["ServerLevel2-Sample1"]
will hold all
level2 data for Serverlevel1-Sample1
  Ex: For Level 3 Data object DataC["ServerLevel2-Sample1ServerLevel2-Sample11"]
will hold all level 3 data for the selection of Level1: Serverlevel1-Sample1 and
Level2 : ServerLevel2-Sample11

Step 11: Collecting level2 and level3 data into Object

for(SL1=0;SL1<L1.length;SL1++)
{
DataC[L1[SL1]]=[];  // Create object Ex: DataC["ServerLevel2-Sample1"]
for(M=0;M<STRVALUE.length;M++)
{
if( STRVALUE[M].getAttribute("ows_Level1")==L1[SL1])
DataC[L1[SL1]].push(STRVALUE[M].getAttribute("ows_ServiceLevel2"))
}
DataC[L1[SL1]]=DataC[L1[SL1]].unique();
for(SL2=0;SL2<L2.length;SL2++)
{
DataC[L1[SL1]+L2[SL2]]=[];
for(M=0;M<STRVALUE.length;M++)
if( STRVALUE[M].getAttribute("ows_Level1")==L1[SL1] &&
STRVALUE[M].getAttribute("ows_Level2")==L2[SL2])
DataC[L1[SL1]+L2[SL2]].push(STRVALUE[M].getAttribute("ows_Level3"))

}
}

Step 12:
On Selecting level 1 , populating level 2 values in dropdown 2.
So initiate the onchange event for dropdown 1 and call a function LevelChange
<select id="Level1" onchange="LevelChange(‘Level2’,this.options[this.selectedIndex].text,this)"></select>
(LevelChange(TargetDropdown, Dropdown1value,this))
On Selecting level2 , populating level 3 values in dropdown 3
So initiate the onchange event for dropdown 2 and call a functio LevelChange
<select id="Level2" onchange="var t=document.getElementById(‘Level1’);LevelChange(‘Level3’,t.options[t.selectedIndex].text+this.options[this.selectedIndex].text,this)"></select>


(LevelChange(TargetDropdown, Dropdown1value+Dropdown2value,this))
On Selecting Level3 , No dropdown should populate
<select id="Level3" onchange="LevelChange(”,”,this)"></select>
(LevelChange(null, null,this))
 

Step 13: Create function levelChange

function LevelChange(ID,Data,this)
{
document.getElementById(ID).options.length=0;
for(i=0;i<DataC[Data].length;i++)
{
document.getElementById(ID).options.add(new
Option(DataC[Data][i],DataC[Data][i]))
}
}

Step 14: Now on select each dropdown, the corresponding textbox should
populate the selected dropdown value.
So modifying the levelChange function a bit to pass the dropdown value to
textboxes. Grab the ID for each textbox from "ViewSource"

 

function LevelChange(ID,Data,Current)
{
if(Current.id!="Level3")
{
document.getElementById(ID).options.length=0;
for(i=0;i<DataC[Data].length;i++)
{
document.getElementById(ID).options.add(new
Option(DataC[Data][i],DataC[Data][i]))
}
}
if(Current.id=="Level1")
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff2_1_ctl00_ctl00_TextField").value=Current.options[Current.selectedIndex].text
if(Current.id=="Level2")
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff3_1_ctl00_ctl00_TextField").value=Current.options[Current.selectedIndex].text
if(Current.id=="Level3")
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff4_1_ctl00_ctl00_TextField").value=Current.options[Current.selectedIndex].text
}

Step 15: Hide all three textboxes.
 

document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff2_1_ctl00_ctl00_TextField").style.display="none"
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff3_1_ctl00_ctl00_TextField").style.display="none"
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff4_1_ctl00_ctl00_TextField").style.display="none"

Complete js file

Array.prototype.unique = function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};

var L1=new Array()
var L2=new Array()
var L3=new Array()
var DataC=[];
xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("<SharePointLink>/_vti_bin/owssvr.dll?Cmd=Display&List={ListID}&Query=*&XMLDATA=TRUE");

STRVALUE = xml_doc.getElementsByTagName("z:row");
for(i=0;i<STRVALUE.length;i++)
{
L1[i]=STRVALUE[i].getAttribute("ows_Level1")
L2[i]=STRVALUE[i].getAttribute("ows_Level2")
L3[i]=STRVALUE[i].getAttribute("ows_Level3")
}
L1=L1.unique();
for(j=0;j<L1.length;j++)
document.getElementById("Level1").options.add(new Option(L1[j],L1[j]))

for(SL1=0;SL1<L1.length;SL1++)
{
DataC[L1[SL1]]=[];
for(M=0;M<STRVALUE.length;M++)
{
if( STRVALUE[M].getAttribute("ows_Level1")==L1[SL1])
DataC[L1[SL1]].push(STRVALUE[M].getAttribute("ows_Level2"))
}
DataC[L1[SL1]]=DataC[L1[SL1]].unique();
for(SL2=0;SL2<L2.length;SL2++)
{
DataC[L1[SL1]+L2[SL2]]=[];
for(M=0;M<STRVALUE.length;M++)
if( STRVALUE[M].getAttribute("ows_Level1")==L1[SL1] &&
STRVALUE[M].getAttribute("ows_Level2")==L2[SL2])
DataC[L1[SL1]+L2[SL2]].push(STRVALUE[M].getAttribute("ows_Level3"))
}
}

function LevelChange(ID,Data,Current)
{
if(Current.id!="Level3")
{
document.getElementById(ID).options.length=0;
for(i=0;i<DataC[Data].length;i++)
{
document.getElementById(ID).options.add(new
Option(DataC[Data][i],DataC[Data][i]))
}
}
if(Current.id=="Level1")
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff2_1_ctl00_ctl00_TextField").value=Current.options[Current.selectedIndex].text
if(Current.id=="Level2")
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff3_1_ctl00_ctl00_TextField").value=Current.options[Current.selectedIndex].text
if(Current.id=="Level3")
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff4_1_ctl00_ctl00_TextField").value=Current.options[Current.selectedIndex].text

}
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff2_1_ctl00_ctl00_TextField").style.display="none"
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff3_1_ctl00_ctl00_TextField").style.display="none"
document.getElementById("ctl00_m_g_4ec47aa8_03c3_4083_b395_a581c10b60ba_ff4_1_ctl00_ctl00_TextField").style.display="none"
 

Refresh Chart data

This tutorial will show you how to create component chart out of an XML file.

Step1 :Create Country.xml with the following data and upload into <src> folder

Country.XML

<main>
<item Country= “USA” Gold=”35″ Silver=”39″ Bronze=”29″/>
<item Country= “China” Gold=”32″ Silver=”17″ Bronze=”14″/>
<item Country= “Russia” Gold=”27″ Silver=”27″ Bronze=”38″/>
</main>

Step2: Create panel component with ColumnChart

ColumnCompChart.mxml
 Adding the below function  to the component column chart, that again assigns the medalAC to the columnchart dataprovider (Updates the data),  If there is a delay between the component initiation and data assignation, Chart wouldnt show the value. So refreshing the data would help to get the data updated. So below function help to manual trigger the chart to get the updated data.

public function refresh() :void  // A function to refresh the data for chart component
{
Column1.dataProvider=medalAC;  //again it assigns medalAC to the columnchart in order to get the data refreshed for column chart
}

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Panel xmlns:mx=”http://www.adobe.com/2006/mxml”
width=”400″ height=”300″ title=”My Chart”>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
public var medalsAC:XMLList; //as the data coming from XML , creating public
variable as XMLList.
public function refresh() :void  // A function to refresh the data for chart component
{
Column1.dataProvider=medalAC;  //again it assigns medalAC to the columnchart in order to get the data refreshed for column chart

}
]]>

</mx:Script>>
<mx:ColumnChart id=”Column1″ height=”100%” width=”100%” dataProvider=”{medalsAC}”>

<mx:horizontalAxis>
<mx:CategoryAxis categoryField=”@Country”/>
</mx:horizontalAxis>

<mx:series>
<mx:ColumnSeries xField=”@Country” yField=”@Gold”
displayName=”@Country” />
<mx:ColumnSeries xField=”@Country” yField=”@Silver”
displayName=”@Country” />
<mx:ColumnSeries xField=”@Country” yField=”@Bronze”
displayName=”@Country” />
</mx:series>
</mx:ColumnChart>

<mx:Legend dataProvider=”{Column1}” />
</mx:Panel >

Step3: Load Country.xml and convert it to XMLList and pass on to the
public variable medalsAC.

ChartDataXML.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”absolute” creationComplete=”createComplete(event)”>
<mx:Script>
<![CDATA[
import MyComps.*;
import flash.utils.getDefinitionByName;
importmx.controls.*;private var CC:ColumnCompChart
private function createComplete(e:Event):void
{
var MainXML:URLLoader=new URLLoader(new URLRequest(“Country.XML”))
MainXML.addEventListener(Event.COMPLETE,MainXMLL)

}
private function MainXMLL(e:Event):void
{
var CL:XML=new XML(e.target.data)
var CountryList:XMLList=new
XMLList
(CL.item)
var cls:Class = getDefinitionByName(“MyComps.ColumnCompChart”) as Class;
var instance:Object = new cls();
instance.medalsAC=CountryList;
instance.refresh() //Calling refresh function to get the data updated
addChild(DisplayObject(instance) );
}

]]>
</mx:Script>
</mx:Application>

Programmatically create chart in flex

This tutorial will show you how to create  chart programmatically out of an XML file.

Step1 :Create Country.xml with the following data and upload into <src> folder

Country.XML

<main>
<item Country= “USA” Gold=”35″ Silver=”39″ Bronze=”29″/>
<item Country= “China” Gold=”32″ Silver=”17″ Bronze=”14″/>
<item Country= “Russia” Gold=”27″ Silver=”27″ Bronze=”38″/>
</main>


Step2: Load Country.xml and convert it to XMLList

ColumnSeries: Defines a data series for a ColumnChart control.
CategoryAxis: CategoryAxis class to define a set of labels that appear along an axis of a chart.

ChartDataXML.mxml

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”createComplete(event)”>
<mx:Script>
<![CDATA[
import mx.charts.CategoryAxis;
import mx.charts.series.ColumnSeries;
import mx.charts.ColumnChart;
private function createComplete(e:Event):void
{
var MainXML:URLLoader=new URLLoader(new URLRequest(“Country.XML”))
MainXML.addEventListener(Event.COMPLETE,LoadCountry)
}
private function LoadCountry(e:Event):void
{
var CL:XML=new XML(e.target.data)
var CountryList:XMLList=new XMLList(CL.item)
var IColumn1:ColumnChart=new ColumnChart();
IColumn1.dataProvider=CountryList

 //Setting Horizontal Axis
var xAxis:CategoryAxis=new CategoryAxis()
xAxis.categoryField = “@Country”
IColumn1.horizontalAxis=xAxis;

//Column Serier for Silver
var NS:ColumnSeries = new ColumnSeries();
NS.yField = “@Silver”;
IColumn1.series.push(NS) //Pushing columnseries to the column chart (just like a values been pushed to an array)

//Column Serier for Bronze
var NS:ColumnSeries = new ColumnSeries();
NS.yField = “@Bronze”;
IColumn1.series.push(NS) //Pushing columnseries to the column chart (just like a values been pushed to an array)

//Column Serier for Gold
var NS:ColumnSeries = new ColumnSeries();
NS.yField = “@Gold”;
IColumn1.series.push(NS) //Pushing columnseries to the column chart (just like a values been pushed to an array)

addChild(IColumn1)
}
]]>
</mx:Script>
</mx:Application>

You typically use the CategoryAxis class to define a set of labels that appear along an axis of a chart

Pass parameters to event Listener

This tutorial will show you how to pass extra parameters apart from event to event listener.

Event Listener

var ULoader:URLLoader=new URLLoader(new URLRequest(“test.xml”))
ULoader.addEventlistener(Event.COMPLETE, CallFunction(param1,param2))

Function Definition

function callFunction(param1,param2):Function(
return function(e:Event):void

{

<!–
Code goes here
–>

}
}

XML to Chart Component

This tutorial will show you how to create component chart out of an XML file.

Step1 :Create Country.xml with the following data and upload into <src> folder

Country.XML

<main>
<item Country= "USA" Gold="35" Silver="39" Bronze="29"/>
<item Country= "China" Gold="32" Silver="17" Bronze="14"/>
<item Country= "Russia" Gold="27" Silver="27" Bronze="38"/>
</main>

Step2: Create panel component with ColumnChart

ColumnCompChart.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml"
width="400" height="300" title="My Chart">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
public var medalsAC:XMLList; //as the data coming from XML , creating public
variable as XMLList.
]]>
</mx:Script>>
<mx:ColumnChart id="Column1" height="100%" width="100%" dataProvider="{medalsAC}">

<mx:horizontalAxis>
<mx:CategoryAxis categoryField="@Country"/>
</mx:horizontalAxis>

<mx:series>
<mx:ColumnSeries xField="@Country" yField="@Gold"
displayName="@Country" />
<mx:ColumnSeries xField="@Country" yField="@Silver"
displayName="@Country" />
<mx:ColumnSeries xField="@Country" yField="@Bronze"
displayName="@Country" />
</mx:series>
</mx:ColumnChart>

<mx:Legend dataProvider="{Column1}" />
</mx:Panel >

Step3: Load Country.xml and convert it to XMLList and pass on to the
public variable medalsAC.

ChartDataXML.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" creationComplete="createComplete(event)">
<mx:Script>
<![CDATA[
import MyComps.*;
import flash.utils.getDefinitionByName;
import mx.controls.*;

private var CC:ColumnCompChart
private function createComplete(e:Event):void
{
var MainXML:URLLoader=new URLLoader(new URLRequest("Country.XML"))
MainXML.addEventListener(Event.COMPLETE,MainXMLL)

}
private function MainXMLL(e:Event):void
{
var CL:XML=new XML(e.target.data)
var CountryList:XMLList=new
XMLList
(CL.item)
var cls:Class = getDefinitionByName("MyComps.ColumnCompChart") as Class;
var instance:Object = new cls();
instance.medalsAC=CountryList;
addChild(DisplayObject(instance) );
}
]]>
</mx:Script>
</mx:Application>

Custom component chart

The following example shows how you can create a column chart as a component and invoke in application and access component variable.
dynamic values by calling the getDefintionByName() method.


ChartDef.mxml

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”
creationComplete=”createComplete(event)”>
<mx:Script>
<![CDATA[
import MyComps.*;
import flash.utils.getDefinitionByName;
import mx.controls.*;
private var CC:PanelComp;ColumnCompChart // Initiate ColumnCompChart component.
private var MData:ArrayCollection = new ArrayCollection( [
{ Country: “USA”, Gold: 35, Silver:39, Bronze: 29 },
{ Country: “China”, Gold: 32, Silver:17, Bronze: 14 },
{ Country: “Russia”, Gold: 27, Silver:27, Bronze: 38 } ]);

private function createComplete(e:Event):void
{
var cls:Class = getDefinitionByName(“MyComps.ColumnCompChart”) as Class;
var instance:Object = new cls();
instance.medalsAC=MData; // Assigning MData arrayCollection to medalAC [Component Variable]
addChild(DisplayObject(instance) );
}
]]>
</mx:Script>
</mx:Application>

ColumnCompChart.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Panel xmlns:mx=”http://www.adobe.com/2006/mxml” width=”400″ height=”300″title=”My Chart”>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
public var medalsAC:ArrayCollection;
]]>
</mx:Script>
<mx:ColumnChart id=”Column1″ height=”100%” width=”100%”
dataProvider=”{medalsAC}”>
<mx:horizontalAxis>
<mx:CategoryAxis categoryField=”Country”/>
</mx:horizontalAxis>

<mx:series>
<mx:ColumnSeries xField=”Country” yField=”Gold” displayName=”Country” />
<mx:ColumnSeries xField=”Country” yField=”Silver” displayName=”Country” />
<mx:ColumnSeries xField=”Country” yField=”Bronze” displayName=”Country” />
</mx:series>

</mx:ColumnChart>
<mx:Legend dataProvider=”{Column1}” />
</mx:Panel>

Create Column Chart Component

The following example shows how you can create a column chart as a component and invoke in application
by calling the getDefintionByName() method.


ChartDef.mxml

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”
creationComplete=”createComplete(event)”>
<mx:Script>
<![CDATA[
import MyComps.*;
import flash.utils.getDefinitionByName;
import mx.controls.*;
private var CC:PanelComp;ColumnCompChart // Initiate ColumnCompChart component.
private function createComplete(e:Event):void
{
var cls:Class = getDefinitionByName(“MyComps.ColumnCompChart”) as Class;
var instance:Object = new cls();
addChild(DisplayObject(instance) );
}
]]>
</mx:Script>
</mx:Application>

ColumnCompChart.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Panel xmlns:mx=”http://www.adobe.com/2006/mxml” width=”400″ height=”300″ 

title=”My Chart”>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
public var medalsAC:ArrayCollection = new ArrayCollection( [
{ Country: “USA”, Gold: 35, Silver:39, Bronze: 29 },
{ Country: “China”, Gold: 32, Silver:17, Bronze: 14 },
{ Country: “Russia”, Gold: 27, Silver:27, Bronze: 38 } ]);
]]>
</mx:Script>
<mx:ColumnChart id=”Column1″ height=”100%” width=”100%”
dataProvider=”{medalsAC}”>
<mx:horizontalAxis>
<mx:CategoryAxis categoryField=”Country”/>
</mx:horizontalAxis>

<mx:series>
<mx:ColumnSeries xField=”Country” yField=”Gold” displayName=”Country” />
<mx:ColumnSeries xField=”Country” yField=”Silver” displayName=”Country” />
<mx:ColumnSeries xField=”Country” yField=”Bronze” displayName=”Country” />
</mx:series>

</mx:ColumnChart>
<mx:Legend dataProvider=”{Column1}” />
</mx:Panel>

Create component by class Name

The following example shows how you can create a new Flex component instance by using its class name by calling the getDefintionByName() method.

GetDefinition.mxml

getDefinitionByName will retrieve the class name for any components / User Defined Components.

<?xml version=”1.0″ encoding=”utf-8″?> 

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”createComplete(event)”>
<mx:Script>
<![CDATA[
import flash.utils.getDefinitionByName;
import mx.controls.*;
private function createComplete(e:Event):void
{
var cls:Class = getDefinitionByName(“mx.controls.Button“) as Class;  //This will get the class name for Button [Class Button]
var instance:Object = new cls();  //Creating an instance based on the class definition.
instance.label=”My Button” //Accessing Label property for Button
addChild(instance as DisplayObject);  // Add instance to the stage and parse the object as DisplayObject in order to consider the Object as UI COmponent
}
]]>
</mx:Script>
</mx:Application>

For User Defined Component

var Temp:PanelComp // It needs to be added to initiate the Component to the application
var cls:Class = getDefinitionByName(“MyComp.PanelComp“) as Class; //MyComp is the folder and PanelComp is the user defined component
var instance:Object = new cls();
instance.label=”My Button”
addChild(instance as DisplayObject);

Save Chart as Image

This tutorial shows you how to save the chart as an Image

ImageSnapshot
Using ImageSnapshot’s captureImage method we can capture any IBitmapDrawable object and it return ImageSnapshot through it we use it’s data property as byte array so we can make duplicate image object of any IBitmapDrawable object.

var image:ImageSnapshot = ImageSnapshot.captureImage(Overall, 0, new JPEGEncoder() );  //Where overall is the ID for UIComponent
private var file:FileReference = new FileReference();
file.save(image.data, “chart.jpg”);

ChartData.xml

<xml>
<data>
<row Title=’Nov’ Y10=’326526′ Y09=’273832′ Y08=’313892′ />
<row Title=’Dec’ Y10=’302275′ Y09=’300582′ Y08=’281679′ />
<row Title=’Jan’ Y10=’332562′ Y09=’340447′ Y08=’275207′ />
<row Title=’Feb’ Y09=’280497′ Y08=’247873′ />
<row Title=’Mar’ Y09=’328304′ Y08=’303520′ />
<row Title=’Apr’ Y09=’366068′ Y08=’314591′ />
<row Title=’May’ Y09=’286720′ Y08=’363357′ />
</data>
</xml>

ChartToImage.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” initialize=”initializeHandler();” height=”100%” >
<mx:Script>
<![CDATA[
import mx.graphics.codec.JPEGEncoder;
import mx.graphics.ImageSnapshot;
private var file:FileReference = new FileReference();
private function initializeHandler():void
{
var XMLLoader2:URLLoader=new URLLoader(new URLRequest(“ChartData.xml”))
XMLLoader2.addEventListener(Event.COMPLETE,xmlLoaded2)
function xmlLoaded2(event:Event):void
{
var myXML:XML = XML(event.target.data);
var FinalXML:XMLList=new XMLList(XML.data.row)
BarChart.dataProvider=FinalXML;
}
}
private function SaveImage(e:Event):void
{
var image:ImageSnapshot = ImageSnapshot.captureImage(Overall, 0, new JPEGEncoder() );  //It captures the panel data [Overall] which has the ColumnChart in it.
file.save(image.data, “chart.jpg”); //Image is the ImageSnapshot. Image.data has the jpeg data
}
]]>
</mx:Script>
<mx:Panel id=”Overall” title=”Over All Traffic” x=”10″ y=”10″ width=”500″ height=”400″>
<mx:ColumnChart x=”10″ y=”10″ showDataTips=”true” id=”BarChart” width=”100%” height=”308″>
<mx:horizontalAxis>
<mx:CategoryAxis categoryField=”@Title” />
</mx:horizontalAxis>
<mx:series>
<mx:ColumnSeries displayName=”FY10″ yField=”@Y10″ showDataEffect=”seriesInterpolate”/>
<mx:ColumnSeries displayName=”FY09″ yField=”@Y09″ showDataEffect=”seriesInterpolate”/>
<mx:ColumnSeries displayName=”FY08″ yField=”@Y08″ showDataEffect=”seriesInterpolate”/>
</mx:series>
</mx:ColumnChart>
<mx:Legend dataProvider=”{BarChart}” direction=”horizontal” />
</mx:Panel>
<mx:Button x=”518″ y=”19″ label=”Save Chart” click=”SaveImage(event)” /></mx:Application>

Create Customized component in Flex

The easiest way to create a component is using MXML. First, to create a new application: from the Flex Builder menu, choose File > New > Flex Project, and fill out the rest of the wizard queries. Next, within Flex builder again, select File > New > MXML Component.

Step 1: Create a Separate folder to dump up all customized components
– Create a folder “MyComps” under src folder

Folder-Screen

Step2: Creating Component
Create MXML Component (PanelComp.mxml) and Follow the wizard and select Panel as your user Defined component(Likewise component can be Canvas, Checkbox, etc..,)
Screen-Component

Step3: Code for Component
Create two public variables to pickup dynamic values from the application. Below shows “Title and MainText” are two public variables.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Panel xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” width=”400″ height=”300″ title=”{Title}”>  //{Title} is the public  variable, {} refers its a variable not the string
<mx:Script>
<![CDATA[
public var Title; //Define public variable , so the scope will be applied to all applications once imported.
public var MainText;  //Another Public variable
]]>
</
mx:Script>
<mx:Text>
<mx:text>{MainText}</mx:text> //{MainText} is the public variable
</mx:Text>
</mx:Panel>

Step 4: Main Application that invokes User Defined Component


<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”onCreate(event)”>
<mx:Script>
<![CDATA[
import MyComps.*  //Importing all components from the folder MyComps
private function onCreate(e:Event):void
{
var TT:PanelComp=new PanelComp()  //PanelComp is the userDefined component been created to show Panel
TT.Title=”From Main”  // Assign Title as ‘From Main’ ,so it applies {title} to <mx:panel> in PanelComp Component
TT.MainText=”Main Text from Application”  // Assign MainText , So it applies {MainText} to <mx:text> in PanelComp component
addChild(TT)
}
]]>
</mx:Script>
</mx:Application>

Output