Flex 3: Dynamic MenuBars via HTTPService

This is a quick code post on how to get a dynamic menu running in Flex 3. This will work for Menus, MenuBars, and PopUpMenuButtons.

For the sake of brevity, I will assume you already have your menu being generated by server-side scripts from a database or other data source. This output should be in XML/E4X format.

Click here if you’re unfamiliar with how to form your XML for Flex Menus

The below code is the minimum required to get a menu dynamically loading its hierarchy from a well-formed XML file:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute"
	creationComplete="{menuSrv.send();}">
	<mx:HTTPService
		id="menuSrv"
		url="menudata.xml"
		resultFormat="e4x" />
	<mx:MenuBar
		showRoot="false"
		labelField="@label"
		dataProvider="{menuSrv.lastResult as XML}">
	</mx:MenuBar>
</mx:Application>

We have defined only an HTTPService and MenuBar. In the <mx:Application> tag we have the creationComplete event call the send() method of the HTTPService. This makes sure that when our application loads, so does the XML data.

Next, in HTTPService we give it an id, which was used to call the send() method previously. We give it a url to get the data from, which here is a .xml file but as long as it is well formed XML in the file it will work absolutely fine. Finally, we define the resultFormat as being E4X.

In MenuBar, we decide not to show our root item. If we don’t set this, Flex will simply create a single menuitem with the entirety of our XML file as the label. We also define the labelField as being @label, as this will allow Flex to access the proper attribute in the E4X format. Finally, we pass the lastResult of the HTTPService as XML to the dataProvider attribute.

Now we’re done! Your menu should run perfectly smoothly as long as the XML is well formed.

One Response to “Flex 3: Dynamic MenuBars via HTTPService”

  1. Emerica Says:

    Thanks

Leave a Reply