Saturday, June 18, 2011

How to dynamically populate a mx:Tree control in Flex

While I think that Flex gives me an unbelievable boost in quickly developing sweet UIs for my web projects, sometimes it just gets on my nerve. My latest problem has a very simple solution… too bad it took me over 20 minutes to get it to work. I found a couple of solutions online that recommended modifying your view/controller to output specially formatted XML. So for example, I’d have to modify my view to output something like:

<?xml version=”1.0″ encoding=”UTF-8″ ?>
<TREEDATA>
<NODE  LABEL=”Ricin”>
<NODE LABEL=”Plate Maps”/>
<NODE LABEL=”Detector Data”/>
<NODE LABEL=”Data Analysis”/>
</NODE>
</TREEDATA>

This, I refused to do. The fact that I am using Flex today, does not mean I’ll use it tomorrow. So I prefer to keep my view outputs following my standard XML format. So then I started playing with the XML data that arrives at the Flex frontend, and see how I could modify it to magically work with the mx:Tree. This, I expected, would be really quick, since I would just grab the XML, parse out what I wanted, and set it as to the dataProvider of the Tree. So my first version looked something like this:


var parsedData:ArrayCollection = new ArrayCollection();
var i:int;
for (i = 0; i < currentXml.PlateMap.length(); i++)
{
var treeXml:XML = <plateMap></plateMap>;
treeXml.label = String(currentXml.PlateMap[i].CompoundRequest.ScreenProjectName)
parseData.addItem(treeXml);
}
listing.dataProvider = parseData;
listing.dataProvider.refresh();



This didn’t work (although it has work for mx:List)… So after a lot of useless tests, I finally got it work…

var xmlPlateMap:ArrayCollection = new ArrayCollection();
var i:int;
for (i = 0; i < currentXml.PlateMap.length(); i++)
{
var xmlString:String =
“<node label=’” + String(currentXml.PlateMap[i].ScreenProjectName) + “‘>” +
“<node label=’Plate Maps’/>”+
“<node label=’Detector Data’/>”+
“<node label=’Data Analysis’/>”+
“</node>”;
xmlPlateMap.addItem(new XML(xmlString));
}
listing.dataProvider = xmlPlateMap;
listing.dataProvider.refresh()



Hope this helps someone else out… 

No comments:

Post a Comment