Archive

Archive for the ‘Component’ Category

Adding colspan to a datagrid

March 17th, 2009

Recently at my job, our User Interface guru came up with the design and interface that she wanted for our users. However, the design she came up with required adding a colspan to a datagrid. As many know who have tried it, this is not really a possibility right out of the box with a Flex DataGrid. It is apparently a possibility with the AdvancedDataGrid, but I have just never really liked the visuals of the datagrid, especially with how it outputs the rows of data…it seems very cluttered to me when grouping is added. Plus, I have a PagedArrayCollection that I wrote and use quite regularly, that (currently) does not play nicely with the AdvancedDataGrid (I think it has something to do with the grouping), and currently just works with the regular DataGrid. So, in order to accommodate the business and my PagedArrayCollection, rather than just have multiple rows of data in multiple columns, I came up with a solution to allow for the spanning of multiple columns, as many as is necessary.

I tried to figure out, visually and programmatically, I could mimic the HTML table colspan. My solution actually involves 2 datagrids + single datagrids as itemrenderers within the rows. As Flex recycles its itemrenderers, this appeared to be a pretty practical solution. My first datagrid is used solely for the headers. I made the height of the datagrid match the height of the headers of the first datagrid, so all that is visible is the headers themselves.

DataGrid Header

DataGrid Header

The code for this is as follows (notice the small height of the datagrid):

<mx:DataGrid id="headerDataGrid" x="70" y="40" width="780" height="23" dataProvider="{ dataProvider }">
	<mx:columns>
		<mx:DataGridColumn headerText="Name" dataField="name"/>
		<mx:DataGridColumn headerText="Location" dataField="location"/>
		<mx:DataGridColumn headerText="Exp" dataField="exp"/>
	</mx:columns>
</mx:DataGrid>

From here I created another datagrid, but this one contains only a single column. I also removed the headers from this datagrid as I will be using the datagrid headers from the previously created datagrid (headerDataGrid), so this one just looks like the rows from a datagrid.

DataGrid Body

DataGrid Body

Once I had these 2 datagrids, I put them right next to each other so it looks like they’re actually the same datagrid, but without vertical lines between the columns.

The code for the 2nd grid is:

<mx:DataGrid x="70" y="61" id="dgMain" width="780" height="444" showHeaders="false" dataProvider="{ dataProvider }" paddingTop="0" paddingBottom="0"
	variableRowHeight="true" selectable="true">
	<mx:columns>
		<mx:DataGridColumn headerText="All data" dataField="col1" itemRenderer="com.flexoop.utility.renderer.ColSpanRowRenderer" />
	</mx:columns>
</mx:DataGrid>

Both of these datagrids are bound to the same dataprovider. This makes manipulation of the arraycollection extremely simple. I had thought I would be writing my own sort and filter functions, overriding the headers, but I forgot that once these datagrids are bound to the same arraycollection, Flex automatically handles all of that and everything just works. Simple! :) The headertext and dataField are irrelevant in this datagrid as they will not be used. I set the variableRowHeight=”true” so the itemrenderer will show the multiple rows of data correctly.

As you can see from the above code, I created a ColSpanRowRenderer itemRenderer. This handles the final part of the colspanned datagrid…the actual colspan.

ColSpan Row Renderer

ColSpan Row Renderer

The code for this looks like:

<mx:DataGrid id="dgLocal" x="0" y="0" width="100%" showHeaders="false" height="23" dataProvider="{ data }" backgroundAlpha="0" selectable="false"
	borderSides="{ parentDocument.detailed ? 'bottom top' : 'bottom' }">
	<mx:columns>
		<mx:DataGridColumn headerText="Name" dataField="name" />
		<mx:DataGridColumn headerText="Location" dataField="location" />
		<mx:DataGridColumn headerText="Exp" dataField="exp" />
	</mx:columns>
</mx:DataGrid>
<mx:Text visible="{ parentDocument.detailed }" includeInLayout="{ parentDocument.detailed }"
	htmlText="This is where the detailed text will go.&lt;br /&gt;This is not formatted now but can be once it goes live" y="22" width="100%" />

This is all contained within a VBox with all padding set to zero to aid in visual layout, and to make it look like it is a row in the dgMainBody datagrid. The height of the datagrid forces it to just show the single row of data, with showHeaders=”false” again. I bind it to the “data” value that is passed in to the itemrenderer, then output the properties of that data object within the single row datagrid. I have a variable named “detailed” in the parentDocument (the page containing my header and main body datagrids). This allows me to show or hide the extra colspanned row of data. This was part of the requirement from the business, so I added it in. As the header, main body, and colspanrowrenderers all need to be tightly coupled, I was not so worried about referring to the “parentDocument”. Had this been something I was going to be moving around to other components, I would have tried to think of another solution. The “includeInLayout” attribute will completely remove the “Text” box from the view, so as not to take up any space when it is not visible. In order to prevent the user from selecting the single row datagrid item, I set ’selectable=”false”‘, then in the outer datagrid (dgMainBody), I set ’selectable=”true”‘. This will then allow the user to select the complete itemrenderer (both datagrid row and colspanned text field).

I had found that when detailed=’false’, the single datagrid rows did not alternate colors, which made sense as they were all the first row. In order to fix this problem, I set backgroundAlpha=”0″ in the colspanrowrenderer. This then used the colors of the dgMainBody datagrid for coloring the itemrenderer. The final visual part was setting the borderSides=”bottom” or “bottom top” depending on whether the view was detailed or not.

The final part of getting this to look and act like a regular datagrid was to adjust the column widths of all of the ColSpanRowRenderer rows when the header items were moved, as the rows are not actually linked directly back to the dgHeader. To catch these changes, I added a creationComplete=”init()” to the vbox in my ColSpanRowRenderer. Then in my init() function (along with a setColumnWidth function):

private function init():void {
	setColumnWidth();
	parentDocument.headerDataGrid.addEventListener( DataGridEvent.COLUMN_STRETCH, setColumnWidth );
}
private function setColumnWidth( event:DataGridEvent=null ):void {
	var _i:uint = 0;
	var _length:uint = parentDocument.headerDataGrid.columns.length;
	while ( _i < _length ) {
		dgLocal.columns[ _i ].width = parentDocument.headerDataGrid.columns[ _i ].width;
		_i++;
	}
}

At first, I was only changing the width of the column that was being stretched, but I found that the flash player must do some other computations on the other columns, so I just decided to loop over all of the columns and resize each one to match the header columns. I found that I had to add a ‘render=”setColumnWidth()”‘ also as some of my columns were a little screwy at times. This adds a slight adjustment after the page renders, but is not all that noticeable and fixes any column width issues I was having.

So the final product looks like this:

DataGrid With ColSpan

DataGrid With ColSpan

And code is DataGridColSpan.mxml and ColSpanRowRenderer.mxml

Hopefully I haven’t bored anyone to tears with my explanation, but I wanted to be sure that everyone understands my reasoning for doing everything that I did to the datagrids. Enjoy!

Gareth Component, Flex, code , , ,

Update to MenuItem class

February 24th, 2009

I have recently begun using my MenuItem and MenuItemWithChildren classes at my work, and have made a slight modification to the code to lessen some of the code writing required.

As I was using the menuItem class, I realized that when I selected the item, I was usually just calling some function based upon the label of that menu item. Using my updated MenuItem class, you can now pass in a function as one of the parameters.

My MenuItem class now looks like this:

package com.flexoop.utility {
 
	[Bindable]
	public class MenuItem {
 
		/***********************************
		 * properties
		 **********************************/
 
		private var _enabled:Boolean = true;
		private var _groupName:String = "";
		private var _icon:Class;
		private var _label:String = "";
		private var _menuHandler:Function;
		private var _toggled:Boolean = true;
		private var _type:String = "";
 
		/***********************************
		 * getters
		 **********************************/
 
		public function get enabled():Boolean {
			return this._enabled;
		}
 
		public function get groupName():String {
			return this._groupName;
		}
 
		public function get icon():Class {
			return this._icon;
		}
 
		public function get label():String {
			return this._label;
		}
 
		public function get menuHandler():Function {
			return this._menuHandler;
		}
 
		public function get toggled():Boolean {
			return this._toggled;
		}
 
		public function get type():String {
			return this._type;
		}
 
		/***********************************
		 * setters
		 **********************************/
 
		public function set enabled( value:Boolean ):void {
			this._enabled = value;
		}
 
		public function set groupName( value:String ):void {
			this._groupName = value;
		}
 
		public function set icon( value:Class ):void {
			this._icon = value;
		}
 
		public function set label( value:String ):void {
			this._label = value;
		}
 
		public function set menuHandler( value:Function ):void {
			this._menuHandler = value;
		}
 
		public function set toggled( value:Boolean ):void {
			this._toggled = value;
		}
 
		[Inspectable(enumeration=separator,check,radio,normal)]
		public function set type( value:String ):void {
			this._type = value;
		}
 
		public function MenuItem( label:String="", menuHandler:Function=null, enabled:Boolean=true, type:String="normal", toggled:Boolean=true, groupName:String="", icon:Class=null ) {
			this.enabled = enabled;
			this.groupName = groupName;
			this.icon = icon;
			this.label = label;
			this.menuHandler = menuHandler;
			this.toggled = toggled;
			this.type = type;
		}
 
	}
}

And similarly for the MenuItemWithChildren class:

package com.flexoop.utility {
 
	public class MenuItemWithChildren extends MenuItem {
 
		/***********************************
		 * properties
		 **********************************/
 
		private var _children:Array = [];
 
		/***********************************
		 * getters
		 **********************************/
 
		public function get children():Array {
			return this._children;
		}
 
		/***********************************
		 * setters
		 **********************************/
 
		public function set children( value:Array ):void {
			this._children = value;
		}
 
		public function MenuItemWithChildren( label:String="", menuHandler:Function=null, enabled:Boolean=true, type:String="normal", toggled:Boolean=true, groupName:String="", icon:Class=null ) {
			super( label, menuHandler, enabled, type, toggled, groupName, icon );
		}
 
	}
}

The 2nd parameter is now the menuHandler function. So in order to use this, you could set up something like this:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" xmlns:flexoop="com.flexoop.utility.*">
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
 
			import mx.events.MenuEvent;
			import mx.controls.Alert;
 
			import com.flexoop.utility.MenuItemWithChildren;
			import com.flexoop.utility.MenuItem;
 
			[Bindable] private var menuData:ArrayCollection = new ArrayCollection;
 
			public function init():void {
				var menuItem:MenuItemWithChildren = new MenuItemWithChildren( "test 1", showMe );
				menuItem.children.push( new MenuItem( "test 4", showMe ) );
				menuItem.children.push( new MenuItem( "test 5", showMe ) );
				menuData.addItem( menuItem );
				menuData.addItem( new MenuItem( "test2", showMe ) );
				menuData.addItem( new MenuItem( "test3", showMe ) );
				mb.dataProvider = menuData;
 
			}
 
			private function menuItemHandler( event:MenuEvent ):void {
				( event.item as MenuItem ).menuHandler();
			}
 
			private function showMe():void {
				Alert.show( 'this was fired from my menuItem' );
			}
 
		]]>
	</mx:Script>
	<mx:VBox>
		<mx:ApplicationControlBar id="acb">
			<mx:MenuBar id="mb" dataProvider="{ menuData }" click="menuItemHandler( event )" />
		</mx:ApplicationControlBar>
	</mx:VBox>
</mx:Application>

(I didn’t get a chance to test the above example code so, if anyone finds that something doesn’t work correctly, feel free to ping me about it and I’ll try to get it working properly). It’s a somewhat basic example as all items point to the same function, but it would be very simple to alter this so each menuItem points to a separate method instead, or pass a certain value to the function to display.

Gareth Component, Flex, code , , ,

Databinding with MenuBar DataProvider

November 29th, 2008

A slight update to my previous post about databinding in the MenuBar’s dataProvider.

It turns out that by just changing my initial menuData property from an Array to an ArrayCollection, everything “just works”. I guess it has to do with the ArrayCollection actually monitoring when its source changes and firing CollectionChange events. These events must then be picked up by the MenuBar parent, and it then updates its bindings. Here’s the updated code:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" xmlns:flexoop="com.flexoop.utility.*">
	<mx:Script>
		<![CDATA[
			import com.flexoop.utility.MenuItemWithChildren;
			import com.flexoop.utility.MenuItem;
			import mx.collections.ArrayCollection;
 
			[Bindable] private var menuData:ArrayCollection = new ArrayCollection;
 
			public function init():void {
				var menuItem:MenuItemWithChildren = new MenuItemWithChildren( "test 1", true );
				menuItem.children.push( new MenuItem( "test 4", true ) );
				menuItem.children.push( new MenuItem( "test 5", false ) );
				menuData.addItem( menuItem );
				menuData.addItem( new MenuItem( "test2", true ) );
				menuData.addItem( new MenuItem( "test3", false ) );
 
			}
 
		]]>
	</mx:Script>
	<mx:VBox>
		<mx:ApplicationControlBar id="acb">
			<mx:MenuBar id="mb" dataProvider="{ menuData }" />
		</mx:ApplicationControlBar>
	</mx:VBox>
</mx:Application>

Just wanted to thank Fotis Chatzinikos over on the flexcoders group for helping to solve this, at least partially. I’m still curious as to what specifically would need to change in order to switch back to an array, but at least I know the quick and easy solution.

Gareth Component, Flex, code , ,

MenuItem Class

November 28th, 2008

I am not completely sure why Adobe decided not to include this in their base classes when creating the Flex framework. They have, more or less, given all of the class structure in the definition of what a menuitem must contain…enabled, toggle, groupName, etc. I decided that there’s absolutely no point in rewriting the same thing over and over again, so why not create a MenuItem class.

package com.archfamily.utility {
 
	[Bindable]
	public class MenuItem {
 
		/***********************************
		 * properties
		 **********************************/
 
		private var _enabled:Boolean = true;
		private var _groupName:String = "";
		private var _icon:Class;
		private var _label:String = "";
		private var _toggled:Boolean = true;
		private var _type:String = "";
 
		/***********************************
		 * getters
		 **********************************/
 
		public function get enabled():Boolean {
			return this._enabled;
		}
 
		public function get groupName():String {
			return this._groupName;
		}
 
		public function get icon():Class {
			return this._icon;
		}
 
		public function get label():String {
			return this._label;
		}
 
		public function get toggled():Boolean {
			return this._toggled;
		}
 
		public function get type():String {
			return this._type;
		}
 
		/***********************************
		 * setters
		 **********************************/
 
		public function set enabled( value:Boolean ):void {
			this._enabled = value;
		}
 
		public function set groupName( value:String ):void {
			this._groupName = value;
		}
 
		public function set icon( value:Class ):void {
			this._icon = value;
		}
 
		public function set label( value:String ):void {
			this._label = value;
		}
 
		public function set toggled( value:Boolean ):void {
			this._toggled = value;
		}
 
		[Inspectable(enumeration=separator,check,radio,normal)]
		public function set type( value:String ):void {
			this._type = value;
		}
 
		public function MenuItem( label:String="", enabled:Boolean=true, type:String="normal", toggled:Boolean=true, groupName:String="", icon:Class=null ) {
			this.enabled = enabled;
			this.groupName = groupName;
			this.icon = icon;
			this.label = label;
			this.toggled = toggled;
			this.type = type;
		}
 
	}
}

I added the properties to the constructor so that the menu items could be created without have to first create a variable for them, but could rather just do something like “myArray.push( new MenuItem( “myLabel”, true ) )”. Initially I added the “children” as a property of this class, but then I found out that this will cause the menu items to show an arrow next to their name as if the MenuItem actually had children (even though the item is an empty array). In order to circumvent this problem, I decided to create a second class, MenuItemWithChildren, that extends MenuItem, but adds the property “children”:

package com.archfamily.utility {
 
	public class MenuItemWithChildren extends MenuItem {
 
		/***********************************
		 * properties
		 **********************************/
 
		private var _children:Array = [];
 
		/***********************************
		 * getters
		 **********************************/
 
		public function get children():Array {
			return this._children;
		}
 
		/***********************************
		 * setters
		 **********************************/
 
		public function set children( value:Array ):void {
			this._children = value;
		}
 
		public function MenuItemWithChildren(label:String="", enabled:Boolean=true, type:String="normal", toggled:Boolean=true, groupName:String="", icon:Class=null) {
			super(label, enabled, type, toggled, groupName, icon);
		}
 
	}
}

Now, whenever I want to create a menu item within one of my menu bars, all I have to do is create an array that holds all of my MenuItem or MenuItemWithChildren classes, and I have strongly typed class rather than a plain, old array of generic objects. The one other thing to note is that if the menu is not created in the property declarations, then you have to set the array to the dataProvider of the menu item, or it will not refresh the view and you will not be able to see your menu items. The implementation would look something like this:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" xmlns:archfamily="com.archfamily.utility.*">
	<mx:Script>
		<![CDATA[
			import com.archfamily.utility.MenuItemWithChildren;
			import com.archfamily.utility.MenuItem;
 
			[Bindable] private var menuData:Array = [];
 
			public function init():void {
				var menuItem:MenuItemWithChildren = new MenuItemWithChildren( "test 1", true );
				menuItem.children.push( new MenuItem( "test 4", true ) );
				menuItem.children.push( new MenuItem( "test 5", false ) );
				menuData.push( menuItem );
				menuData.push( new MenuItem( "test2", true ) );
				menuData.push( new MenuItem( "test3", false ) );
				mb.dataProvider = menuData;
 
			}
 
		]]>
	</mx:Script>
	<mx:VBox>
		<mx:ApplicationControlBar id="acb">
			<mx:MenuBar id="mb" dataProvider="{ menuData }" />
		</mx:ApplicationControlBar>
	</mx:VBox>
</mx:Application>

I haven’t had to use the Menu class very often yet, but I’m sure this will come in handy to someone else. If nothing else, it saves typing in Flex Builder.

Enjoy!

Gareth Component, Flex, code , , , ,

Dedupe ArrayCollection Component

November 26th, 2008

Building off of my last post, I thought I might as well create a deduped arraycollection as well, just in case anyone wanted to use the data for something other than a combobox.  The implementation for this component is very similar to that of the combobox.  The DedupeArrayCollection allows you to pass it an array (one that has some kind of properties to each of the items within it), then set the dedupeProperty to whatever field you wish to dedupe.

The DedupeArrayCollection:

package com.archfamily {
 
	import flash.events.Event;
	import flash.utils.Dictionary;
 
	import mx.collections.ArrayCollection;
	import mx.events.CollectionEvent;
 
	public class DedupeArrayCollection extends ArrayCollection {
 
		private var _dedupeProperty:String = "";
 
		public function set dedupeProperty( value:String ):void {
			_dedupeProperty = value;
			this.source = this.source;
		}
		public function get dedupeProperty():String {
			return _dedupeProperty;
		}
 
		/**
		 * 
		 * Needed to override the standard dataprovider in order to reset
		 * the duplicate value each time
		 * 
		 */
		override public function set source( value:Array ):void {
			var _returnArray:Array = value;
 
			if ( value && dedupeProperty.length > 0 ) {
				var _map:Dictionary = new Dictionary( true );
 
				value.forEach( function( item:*, index:int, array:Array ):void {
					_map[ item[ this ] ] = item; // in the loop, this == dedupeProperty
				}, dedupeProperty );
 
				_returnArray = [];
				for each ( var object:Object in _map ) {
					_returnArray.push( object );
				}
			}
 
			super.source = _returnArray;
		}
 
		public function DedupeArrayCollection( source:Array=null ) {
			super( source );
		}
 
	}
}

The implementation of the arraycollection:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" xmlns:archfamily="com.archfamily.*">
	<mx:Script>
		<![CDATA[
			import com.archfamily.DedupeArrayCollection;
 
			[Bindable] private var ac:DedupeArrayCollection = new DedupeArrayCollection( [ { name: "car", total: 100 },{ name: "bus", total: 200 },{ name: "bike", total: 300 },{ name: "train", total: 200 },{ name: "boat", total: 400 },{ name: "car", total: 500 },{ name: "bus", total: 200 },{ name: "convertible", total: 100 },{ name: "gizmo", total: 300 },{ name: "boat", total: 300 },{ name: "car", total: 100 },{ name: "dune buggy", total:300 },{ name: "motorcycle", total: 100 }] );
 
			public function init():void {
				ac.dedupeProperty = "total";
			}			
		]]>
	</mx:Script>
	<mx:VBox>
		<mx:ComboBox id="testing" dataProvider="{ ac }" labelField="name" />
	</mx:VBox>
</mx:Application>

The only thing I would probably change is to figure out what event needs to fire when my dedupeProperty is set to get the arraycollection to reload the source. Currently I’m just setting the source to itself so that the event fires and reloads the arraycollection, but just firing the event would probably be less overhead.

Gareth Component, Flex, code , , , ,

Deduped ComboBox Component

November 26th, 2008

There are times that I have wanted to remove all duplicates from a combobox’s dataprovider, but haven’t wanted to requery the database or roll my own code snippet each time to remove those duplicates.  To make my life a little easier (and hopefully anyone else that may be in need of this feature), I’ve created the DedupeComboBox class.

This handy little item allows you to set the dataprovider of the combobox to an array or arraycollection, and set the labelField value and the combobox will then handle the rest.  The labelfield is important as that is what allows the component to remove the duplicates from the arraycollection (if it is an array, it must also be an array of objects with properties that match the labelField or it will not remove anything). Also, as the items populate the deduped dictionary instance, the value of that item in the arraycollection is saved to that “key” in the dictionary, allowing for retrieval of it later on if necessary.

package com.archfamily {
 
	import flash.utils.Dictionary;
 
	import mx.collections.ArrayCollection;
	import mx.controls.ComboBox;
 
	public class DedupeComboBox extends ComboBox {
 
		/**
		 * 
		 * Needed to override the standard dataprovider in order to reset
		 * the duplicate value each time
		 * 
		 */
		override public function set dataProvider( value:Object ):void {
 
			var _localArray:Array = ( value is ArrayCollection ) ? ( value as ArrayCollection ).source : value as Array;
			var _map:Dictionary = new Dictionary( true );
 
			if ( labelField.length > 0 ) {
				_localArray.forEach( function( item:*, index:int, array:Array ):void {
					_map[ item[ this ] ] = item; // in the loop, this == labelField
				}, labelField );
			}
 
			var _returnArray:Array = [];
			for each ( var object:Object in _map ) {
				_returnArray.push( object );
			}
 
			super.dataProvider = _returnArray;
		}
 
		public function DedupeComboBox() {
			super();
		}
 
	}
}

then to implement it from your code you could do something as simple as this

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:archfamily="com.archfamily.*">
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			[Bindable] private var ac:ArrayCollection = new ArrayCollection([ { name: "car", total: 100 },{ name: "bus", total: 200 },{ name: "bike", total: 300 },{ name: "train", total: 200 },{ name: "boat", total: 400 },{ name: "car", total: 500 },{ name: "bus", total: 200 },{ name: "convertible", total: 100 },{ name: "gizmo", total: 300 },{ name: "boat", total: 300 },{ name: "car", total: 100 },{ name: "dune buggy", total:300 },{ name: "motorcycle", total: 100 }]);
		]]>
	</mx:Script>
 
	<archfamily:DedupeComboBox id="testing" dataProvider="{ ac }" labelField="name" />
</mx:Application>

You can even get just the non-duplicate totals by changing labelField=”name” to labelField=”total”.

Gareth Component, Flex, code , , , , ,