Wednesday, February 18, 2009

Checkbox Renderer Ignores Editable Property in a Grid Column

I've been having problems getting a Flex 3 checkbox to pay attention to a datagrid columns editable status. I finally found a solution using a component I had previously lifted from Alex's Flex Closet. The solution was in the code for the clickHandler - an override with a test of the parent columns editable status seems to have done the trick for me. This took me a while to work out - and even then there may be some issues with it. If anybody has a more efficient working method please let me know. I will come back soon and update this post with a full working example - but for now the code for extending the checkbox class is below.



package
{

import flash.display.DisplayObject;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.text.TextField;
import mx.controls.CheckBox;
import mx.controls.dataGridClasses.DataGridListData;
import mx.controls.listClasses.BaseListData;
import mx.controls.DataGrid;

/**
* The Renderer.
*/
public class CentredCheckBox extends CheckBox
{

private var _listData:DataGridListData;

public function CentredCheckBox()
{
focusEnabled = false;
}

override public function set data(value:Object):void
{
super.data = value;
if (listData is DataGridListData)
{
selected = Boolean(data[DataGridListData(listData).dataField]);
}
}
override public function get listData():BaseListData
{
return _listData;
}
override public function set listData(value:BaseListData):void
{
_listData = DataGridListData(value);
}

/* eat keyboard events, the underlying list will handle them */
override protected function keyDownHandler(event:KeyboardEvent):void
{
}

/* eat keyboard events, the underlying list will handle them */
override protected function keyUpHandler(event:KeyboardEvent):void
{
}

/* eat mouse events, the underlying list will handle them */
/* unless we are in edit mode - in which case process them */
override protected function clickHandler(event:MouseEvent):void
{
var allowEdit:Boolean;
if (listData is DataGridListData)
{
allowEdit = DataGrid(DataGridListData(listData).owner).columns[DataGridListData(listData).columnIndex].editable;
}
if (allowEdit)
{
super.clickHandler(event);
}
}

/* center the checkbox if we're in a datagrid */
override protected function updateDisplayList(w:Number, h:Number):void
{
super.updateDisplayList(w, h);

if (listData is DataGridListData)
{
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var c:DisplayObject = getChildAt(i);
if (!(c is TextField))
{
c.x = (w - c.width) / 2;
c.y = 0;
}
}
}
}
}
}

No comments: