itemEditors – Part 3

,

The previous article in this series discussed item editing events. Using events can make your application respond to what the user enters and help the user make fewer mistakes.

This article is about using itemRenderers as itemEditors – one class to do both display data and edit the data. I tend to think of it more as an itemEditor used as an itemRenderer. But that’s just me.

Download source for these examples.

Further, I have to be honest and say I am not a big fan of the renderer-as-editor; I think renderers should present data and editors should edit it. There are a few occasions when I think it is a good idea to use a single class for both, but those times are very few in my opinion.

Examples

Here is an example of over-using the itemRendererAsEditor. The DataGrid on the left is a nice, clean DataGrid. All of the cells are editable and when you click or tab into a cell its editor appears. The DataGrid on the right uses itemEditors to render the cells and edit them. All you see are the editors: TextInput controls for some columns, a ComboBox for another, and a NumericStepper for the last. Lots going on, very busy to look at.

itemEditors only itemRenderers as itemEditors

Here is an example of using the CheckBox as both an itemRenderer and an itemEditor. I think the CheckBox works really well for this. It is clean, simple control and you can readily see whether a value is true or false. Plus you can just click it to change it. Straightforward implementation, good user experience.

Here is another example of using an itemEditor as a renderer. This List control represents a shopping cart. In it are all of the things you have added to your cart while shopping online at your favorite grocery store.

As you can see, the quantity of each item in the cart is represented by a NumericStepper. All the user has to do is change the quantity and the cart is updated. A delete button would also be a good idea here, too.

Shopping Cart

This complex editor/renderer class works as follows:

<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" verticalAlign="middle" paddingRight="4" paddingLeft="4" >

<mx:Script>
<![CDATA[
public function get quantity() : Number
{
return itemQuantity.value;
}
]]>
</mx:Script>

<mx:CurrencyFormatter id="cfmt" precision="2" />

<mx:Label text="{data.name}" fontWeight="bold" fontSize="12"/>
<mx:Spacer width="100%"/>
<mx:NumericStepper id="itemQuantity" value="{data.quantity}"
minimum="0"
maximum="100"/>
<mx:Label text="{cfmt.format(data.price*itemQuantity.value)}" width="66"/>

</mx:HBox>

As with every itemEditor, this one has a property used as the editorDataField. In this case it is the quantity property getter function. The function retrieves the value setting of the NumericStepper (with id itemQuantity).

As an itemRenderer, this component must also display the current quantity (as well as the product name, price, and sub-total). These values are displayed through data binding. The sub-total is actually an ActionScript expression, multiplying the price by the value of the NumericStepper. As the NumericStepper is changed so does the sub-total.

Now you are probably wondering how to get the grand total below the shopping cart to update as the NumericSteppers are changed. Simply changing the sub-total and the quantity field of the itemRenderer/Editor will not update the grand total. Remember that the editor does not commit the new value into the data provider until after the edit completes. In other words, if you increase the value of the NumericStepper for the Snow Peas row, the grand total will not update until focus leaves the Snow Peas row. This is so you can validate the information as shown in previous articles.

For a shopping cart like this, you want the grand total to update as the user changes the NumericSteppers. So you have to force the situation a little.

The first thing you do is have the itemRenderer class implment the IDropInListItemRenderer interface. This gives you access to the listData which contains a reference to the list itself and, through that, to the dataProvider.

The code demonstrating this is available in the download. Look for the ShoppingCartRendererExtra.mxml file.

Once you have the listData you can have the change event on the NumericStepper force an update on the dataProvider:

private function forceUpdate() : void
{
// Access the collection - listData.owner is the List and from there you have its dataProvider.
var ac:ArrayCollection = (listData.owner as List).dataProvider as ArrayCollection;

// update the quantity field from the numeric stepper. This is what the List will automatically
// do when editing completes, but since you want to see the grand total change as the NumericStepper
// changes, you have to force things a bit.
data.quantity = itemQuantity.value;

// finally, tell the collection the data changed. this will cause the collection to
// dispatch its own change event which is then picked up by the main application.
ac.itemUpdated(data);
}

When the NumericStepper’s change event triggers this event handler, the ArrayCollection has the item updated immediately, rather than waiting for the List to complete editing the cell. If the main application is listening for a COLLECTION_CHANGE event on the collection, the grand total can be calculated:

    <mx:ArrayCollection id="shoppingCartDB"
source="{shoppingCartArray}"
collectionChange="updateCartTotal()" />
...
private function updateCartTotal() : void
{
if( cartTotal ) {
var total:Number = 0;
for(var i:int=0; i < shoppingCartDB.length; i++)
{
var record:Object = shoppingCartDB.getItemAt(i);
total += record.price * record.quantity;
}

cartTotal.text = cfmt.format(total);
}
}

 

Conclusion

Take care when turning an itemRenderer into an itemEditor. The user should have a straightforward interface with a single purpose when editing a cell or record. I personally prefer to separate the functions, but there are times when using an itemRenderer as an itemEditor can make sense, even if you have to go the extra mile as with this shopping cart grand total example.

itemEditors – Part Two

Editing Events and Complex Editors

In the last article of this series you saw how to make some simple inline itemEditors. If you have read the series on itemRenderers, then you noticed how similar the two are.

The key to making an itemEditor work is a) naming the class using the itemEditor property and b) naming the value property of the itemEditor using the editorDataField property.

In this article I’ll show you how to use events to do some simple data validation and to prevent certain cells from being edited. In the course of this you will see how to make more complex itemEditors.

You can download the source code for this example here.

A word of caution here: by "complex" I do not mean editors with many controls and layouts. I really mean slightly more complex than inline itemEditors. The reason being is that I think it is unfair to ask users to make complex edits within a list or cell of a DataGrid. An editor should be focused only one one thing: the contents of a cell. For example, if you are using the List control and presenting a shopping cart, it is not unreasonable to allow the user to change the quantity of the items in the cart by letting them edit that value right in the cell. What would be unreasonable is to allow them to change the item itself, the colors, quantity, special instructions, and so forth. Or in other words, allow them to shop for items right from the cart when you have a whole site that does that. The cart is just a checkout convenience. Sure, let them add an extra tub of ice cream or delete a bag of chips, but don’t have them turn the bag of chips into a two boxes of whole wheat pasta.

The itemEditEnd event

Let’s say you have a DataGrid which helps you mange inventory. One of things you can do is change part numbers, but you cannot allow a part number to be blank. Using the default itemEditor, the TextInput control, you can click on a cell in the "Part #" column, press the delete key and erase the part number. This is one technique to prevent that.

	<mx:DataGrid x="10" y="64" editable="true" dataProvider="{inventoryDB}"
itemEditEnd="verifyInput(event)">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="Type" dataField="type"
itemEditor="editors.ProductTypeEditor" editorDataField="type"/>
<mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
</mx:columns>
</mx:DataGrid>

The list controls dispatch an itemEditEnd event whenever editing is about to be completed. The event happens before the data is commited back to the dataProvider. By handling this event you have the option of changing the data, validating the data, and stopping the commit if necessary. For this example, the verifyInput() function will make sure the product part number is not empty.

		private function verifyInput( event:DataGridEvent ) : void
{
// it is OK if the user cancels the edit
if( event.reason == DataGridEventReason.CANCELLED ) return;

// grab the instance of the itemEditor. For this DataGrid, only the
// TextInput control is used as the editor, so it is safe to get the
// editor no matter what column has been edited.
var editor:TextInput = (event.currentTarget as DataGrid).itemEditorInstance as TextInput;

// if  the edit is on the part number column, make sure it is not blank
if( event.dataField == "part" )
{
if( editor.text.length == 0 ) {
// call event.preventDefault() so the edit will not continue and store the
// blank value
event.preventDefault();
// give the editor an error to display to the user
editor.errorString = "You must enter a part number";
return;
}
}

// handle other columns here
}

The event is a DataGridEvent and contains some very useful properties. The reason property tells you why the event was dispatched. If the user pressed the ESCAPE key or clicked outside of the DataGrid the reason will be DataGridEventReason.CANCELLED. You may want to ignore this event as I have done and just let the DataGrid to its default action which is to cancel the edit and restore the previous value.

If you have decided to handle the event then you will need the itemEditor to get to its properties. The event’s currentTarget property contains the control which I have cast to DataGrid. The DataGrid has an itemEditorInstance property which I cast to TextInput which is the type of itemEditor for this example.

This event handler is called for any cell so you must determine if the edit is something you are interested in pursuing. I check the event’s dataField property to make sure it is the "part" column. If so, I test the editor’s text property to see if there are any characters in it. If there are no characters, two things happen:

First: the event.preventDefault() is called. This is how to prevent the edit from happening – prevent the DataGrid from storing the new value back into the dataProvider.  For the user, they will have pressed TAB or ENTER and nothing will appear to happen. The preventDefault() function will keep the itemEditor in place.

Second: I put an errorString onto the TextInput control. This is optional, but it does signal the user that there is something wrong. Afterall, they pressed the TAB or ENTER key and nothing happened.

The itemEditBeginning Event

There are times you might want to prevent a cell from being edited. You could set the DataGridColumn’s editable property to false, but that prevents every cell from being edited. Suppose you just want to make some of the cells in the column uneditable? You can determine whether a cell is editable or not using the itemEditBeginning event.

    <mx:DataGrid x="10" y="64" editable="true" dataProvider="{inventoryDB}"
itemEditEnd="verifyInput(event)"
itemEditBeginning="allowForEdit(event)">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="Type" dataField="type"
itemEditor="editors.ProductTypeEditor" editorDataField="type"/>
<mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
</mx:columns>
</mx:DataGrid>

Handling the itemEditBeginning event gives you the option of dynamically deciding the editability of a cell. In this example, the data has a field called permanent on each record. The idea is that permanent=true means the product name is an unchangable value so the product cell for that row cannot be edited. This is handled by the allowForEdit() function:

        private function allowForEdit(event:DataGridEvent) : void
{
// if the field to be edited is a product, prevent the user from making
// changes if the permanent flag is true<. You can use more complex logic, 
// of course.
if( event.dataField == "product" ) {

var item:Object = ((event.currentTarget as DataGrid).dataProvider as ArrayCollection)[event.rowIndex];
if( item.permanent ) {
event.preventDefault();
}
}

// handle other columns here
}

Again, the event is a DataGridEvent and here I have checked the dataField property of the event to make sure it is the "product" field I am dealing with. I can then get the record from the dataProvider of the DataGrid using the currentTarget property of the event and cast that to DataGrid. I then cast the DataGrid’s dataProvider to ArrayCollection and get the event.rowIndex value. I could also have used the inventoryDB ArrayCollection directly in this function since they are in the same file, but this is more generic.

Once I have the record I can query its permanent property and if it is true, call the event.preventDefault() function to disable editing of that cell. In the case, the default behavior of itemEditBeginning is to present the itemEditor; preventing the default behavior makes the cell uneditable.

Editing Limitations

While I was proof reading this article I thought of something you might try and do and offer a warning. When you are using these edit events and trying to determine if the event should proceed, you may be tempted to make a call to a backend or server process. For example, you may have a web service where you can validate a part number. You may be tempted, while inside of the itemEditEnd event, to make a web service call and validate what the user just entered. Seems logical, right?

Logical maybe, but it won’t work. The reason is that data service calls are asynchronous. You can make the call, sure, but the result will be returned sometime later – well after your event handler has exited. In fact, your call won’t actually be made until your function exits. Your call is queued and when the Flex framework exits the function the request will be made and then the result will be returned by your web service’s result handler.

So there is no way to do this type of server-side validation while editing cells. You should query the server, when your application starts, for the data to validate against, then use that while the cells are being edited.

Conclusion

The ability to dynamically allow editing and to validate the edit is a excellent way to give your users a better experience. You can help them make fewer mistakes and give feedback during the editing process. You can prevent them from editing certain data and make it easier for yourself to write the application since you do not have to validate what the user cannot change.

In next article I’ll cover itemRenderers used as itemEditors.

itemEditors – Part 1

inline itemEditors

I recently completed a series on itemRenderers – customizations to list controls which format the display of the list contents. Displaying and rendering content is very cool and with Flex you can do nearly anything you can imagine.

This new series covers itemEditors – a way to allow data to be changed directly inside of a list control. This first article covers inline itemEditors which are very simple, though quite useful, components you write directly inside your MXML files. The other articles in the series will cover more complex editing, validation, events, and using itemRenderers as itemEditors.

The source code to this article is available by downloading it here.

TextInput Editor

It is nice to edit directly in the list controls. You can imagine a DataGrid of warehouse inventory where you can adjust the content right in the grid without needing a special pop-up. The list controls have a built in editor – a TextInput control – which appears whenever the user clicks the mouse in an editable area, either a row (for a List), a branch (for a Tree), or a cell (for a DataGrid). All you need to do is set the list control’s editable property to true. For a DataGrid you can exclude a column from being edited by setting the DataGridColumn’s editable property to false.

Before editing a cell
After clicking on a cell, the editor opens and the content is ready for editing.

itemEditors differ from itemRenderers in that only one instance of the itemEditor is seen – just on the cell being edited. The itemEditor is not seen until the cell to be edited receives input focus. Then the itemRenderer is hidden and the itemEditor is moved to that position, sized to fit the area, and given the data for the record. When editing is finished (by moving focus to another location), the list control copies the new value from the editor to the dataProvider record.

Using the image above as an example, when the user clicks in a cell of the "Part #" column, the dataProvider[row][dataField] value is given to the text property of the itemEditor (TextInput) control. When editing is finished, the text property value from the itemEditor (TextInput) control is copied to the dataProvider[row][dataField]. The dataProvider, being a collection, dispatches an event in response to the update.

While the default TextInput control makes a fine editor, it really only works for the most simple of cases. It works fine for String values, for example, such as a book title, author name, or product number. If you need more control or want to validate the user’s input, then you need to take matter into your own hands.

Flex Controls as itemEditors

Here is how you make an itemEditor which only accepts numeric values:

	<mx:DataGrid x="46" y="270" editable="true" dataProvider="{employeeDB}">
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Position" dataField="position"/>
<mx:DataGridColumn headerText="Age" dataField="age">
	<mx:itemEditor>
<mx:Component>
<mx:TextInput restrict="0-9" maxChars="3" />
</mx:Component>
</mx:itemEditor> 
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>

A very common control to use for an itemEditor is the CheckBox. This is very useful for editing Boolean values. Here is an example of using the CheckBox to edit the values for an "In Stock" column of an inventory program:

<mx:DataGrid x="531" y="273" editable="true" dataProvider="{inventoryDB}">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
	<mx:DataGridColumn headerText="In Stock?" dataField="inStock"
labelFunction="inStockLabeler"
itemEditor="mx.controls.CheckBox" editorDataField="selected" /> 
<mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
</mx:columns>
</mx:DataGrid>

In this example the content of the cells in this column are rendered using a labelFunction (inStockLabeler) which could display anything such as "Yes", "No", "In Stock", or "Out of Stock". The itemEditor property is set to the mx.controls.CheckBox class. And there is another, equally important, property set on the DataGridColumn: editorDataField. This field indicates the property of the itemEditor class to use to fetch the value when editing is finished. In this case it is the CheckBox’s selected property. When editing is finished, the DataGrid will use the CheckBox’s selected property to replace the inStock property in the data record.

You may wonder why the example with the TextInput did not supply the editorDataField property. That is because the default value for editorDataField is "text" which just happens to be name of the property on the TextInput control holding the value.

You can use this same technique with a number of Flex controls. Here is one for an order quantity column using NumericStepper:

	<mx:DataGrid x="531" y="82" editable="true" dataProvider="{inventoryDB}">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="In Stock?" dataField="inStock"/>
	<mx:DataGridColumn headerText="Quantity" dataField="quantity"
itemEditor="mx.controls.NumericStepper" editorDataField="value"/> 
</mx:columns>
</mx:DataGrid>

Notice the editorDataField is "value" – the property of the NumericStepper which holds the current value of the control. Make sure you use the fully-qualified class name for the itemEditor property.

Complex Editor

Now suppose you want to do something a little more complex that doesn’t have a ready-made Flex control available. Here is one which allows a credit card number to be entered using 4 separate 4-digit fields:

	<mx:DataGrid x="46" y="463" editable="true" dataProvider="{accountDB}" width="302">
<mx:columns>
<mx:DataGridColumn headerText="Account" dataField="account" width="100"/>
<mx:DataGridColumn headerText="Credit Card" dataField="ccard" editorDataField="value">
<mx:itemEditor>
<mx:Component>
<mx:HBox>
<mx:Script>
<![CDATA[
public function get value() : String
{
return part1.text+part2.text+part3.text+part4.text;
}
override public function set data(value:Object):void
{
super.data = value;
part1.text = value.ccard.substr(0,4);
part2.text = value.ccard.substr(4,4);
part3.text = value.ccard.substr(8,4);
part4.text = value.ccard.substr(12,4);
}
]]>
</mx:Script>
<mx:TextInput id="part1" maxChars="4" restrict="[0-9]" width="40" />
<mx:TextInput id="part2" maxChars="4" restrict="[0-9]" width="40" />
<mx:TextInput id="part3" maxChars="4" restrict="[0-9]" width="40" />
<mx:TextInput id="part4" maxChars="4" restrict="[0-9]" width="40" />
</mx:HBox>
</mx:Component>
</mx:itemEditor>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>

This inline itemEditor follows the same rules as other itemEditors and names the editorDataField as "value". The component chosen for the itemEditor is the HBox – which does not have a "value" property. To make this itemEditor work, a getter function named value is created to return the concatenation of the 4 input fields. Now when editing for the cell completes, the DataGrid can call upon the value property of the itemEditor and it will receive the combined fields.

You can also see that I have overridden the data setter function. In that function I split up the credit card number among the four TextInput fields. This is the technique you use to display the data to be edited. The editorDataField is the property used to retrieve the new value.

Conclusion

In this article you’ve seen how to create an inline itemEditor – from simply naming a class to creating a complex class right within the MXML tags. By naming the property of the editor class which contains the final editor value, the DataGrid can retreive the value from the editor instance and replace the current value in the data.

The next article covers more complex itemEditors and editing events.

Registration Open for MAX 2008

MAX 2008 will be held in San Francisco this year and is now ready for you to register.

Each year MAX has gotten bigger and better. If you haven’t attended MAX, make this year your first. MAX is a great place to network and to see the new things coming from Adobe and other companies. MAX is also the place to meet the Adobe staff and there are always plenty of Adobe people on hand.

Following this link and make your reservation: http://max.adobe.com/blog/

Hope to see you at MAX!

Ruth G. Chamberlain

In memoriam…

Ruth Chamberlain

Early in the morning of April 28, 2008, my mother, Ruth Chamberlain, passed away. She was 89 years old and suffered from emphysema.

My mother often worked two jobs while I was growing up and it was while she was working that she was most happy. She managed to work until she was 86 and was, at the time, the oldest employee of A.C. Moore. I think I take after her in that respect.

I am not writing this article for your sympathy, but to be another voice and to challenge you and remind you of the effects of smoking. You see, my mother smoked most of her adult life. She quit smoking in her 60s, but still, 20 years later, it caught up with her.

She spent her last years in a nursing home because of her breathing. She had to be on oxygen all of the time and took medication several times a day. Toward the end her breathing became more and more difficult until she couldn’t do it any longer.

If you smoke – STOP NOW. For yourself, for those you love and who love you. STOP NOW for your friends and co-workers. STOP NOW for your pets too.

My mother was fond of St. Jude’s Children’s Hospital. If you care to make a donation I know they would love it.

Thanks to my mom for raising me and giving me the opportunity to work and do what I love to do best.

Return to Normal

Our blogging server is back and my blog, along with a bushel of others, have been restored.

Now I can work on my back-log of articles.

Adobe Media Player

,

Adobe’s just released a new product- the Adobe Media Player. This application is built upon AIR using the Flex 3 SDK. The AMP is a new type of video player.

As I write this I’m watching an episode of Star Trek: The Original Series from January 1968. It looks terrific and streams smoothly. There are a dozens of shows to choose from.

I personally think this is paving the way for the future of home entertainment. Why be at the mercy of the cable or satellite companies when the content you want to watch is available when you want to watch it. Right now you can download movies from iTunes and Amazon Unbox. NBC and FOX have the Hulu joint venture with movies and TV shows. I haven’t rented a movie at a movie rental store in who-knows-how-long.

For me, the problem is making the interface to these services as easy as bringing up the guide on my TiVo and as simple to connect all the boxes together.

Here’s an excerpt from the announcement:

It [AMP] provides high quality video playback of streamed, downloaded, or locally stored Internet TV shows and video podcasts. Users can subscribe to Internet television shows and other online video content, have them download automatically in the background, and later view them on demand. AMP’s user interface optimizes the user experience, allowing users to easily enjoy finding and viewing their favorite shows.

AMP represents a tool that is not only important to consumers, but publishers who want to monetize advertisements.  The last couple of months we have been working very hard to get the top broadcasters signed to provide content through AMP. We have successfully signed CBS, MTV and Food Network as just a few that will be part of our launch.

Download Adobe Media Player today!

itemRenderers: Part 5: Efficiency

,,,

If you are displaying a large number of itemRenderers – either in the DataGrid or AdvancedDataGrid – your application’s performance may be adversely affected if you do not code these itemRenderers effeciently. Here are some tips that might help:

  • Limit the number of columns using itemRenderers. Do you really need to have every column be a custom itemRenderer? Sometimes you do, but is all that glitz overwhelming the user?
  • Try not to change the style of the elements in your itemRenderer too frequenty. If you need to switch styles (eg, green for positive values, red for negative values), consider having 2 controls preset with those styles and making one visible. Changing styles is one of the more time-consuming tasks in Flex.
  • Do not use Containers as the basis for your itemRenderers. Containers have a lot of overhead. They are fine for limited use, but it would be more efficient to write your itemRenderers based on UIComponent.

Switching Styles

Here’s an itemRenderer which switches components depending on the value of the data field.

<mx:Canvas>
<mx:Script><![CDATA
private function lessThanZero() : Boolean {
return data.price < 0;
}
]]></mx:Script>
<mx:Label text="{data.price}" color="#FF0000" visible="{lessThanZero()}" />
<mx:Label text="{data.price}" color="#00FF00" visible="{!lessThanZero()}" />
</mx:Canvas>

This will be faster than setting the style. Some other things to keep in mind:

  • Avoid data binding to styles. Not only is changing styles slower than most operations, adding data binding code on top of it just makes it worse.
  • Use a Canvas or extend ListItemRenderer or as the root of the itemRenderer. This allows you to place controls on top of each other.

Extending UIComponent

By far the most efficient way to write an itemRenderer is to extend UIComponent using an ActionScript class. You’ll have complete control of the code and the renderer will be as efficient as possible.

Let’s start with the example above, switching styles, and write a simple itemRenderer extending UIComponent.

package renderers
{
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;

public class PriceItemRenderer extends UIComponent implements IListItemRenderer
{
public function PriceItemRenderer()
{
super();
}

}
}

You’ll notice that not only did I write the class to extend UIComponent, I also have it implementing the IListItemRenderer interface. It is necessary to do this because a list control will expect any renderer to implement this interface and if you do not, you’ll get a runtime error as the list attempts to cast the renderer to this interface.

If you read the documentation on IListItemRenderer you’ll see that is an amalgamation of many other interfaces, most of which UIComponent implements for you. But there is one interface extended by IListItemRenderer that UIComponent does not implement: IDataRenderer. This requires you to add the code to give the itemRenderer class the data property you’ve been using all along.

If you attempt to use this class without implementing IDataRenderer you’ll get these errors when you compile the code:

1044: Interface method get data in namespace mx.core:IDataRenderer not implemented by class renderers:PriceItemRenderer.
1044: Interface method set data in namespace mx.core:IDataRenderer not implemented by class renderers:PriceItemRenderer.

Edit this class and change it to the following:

package renderers
{
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;
import mx.events.FlexEvent;


public class PriceItemRenderer extends UIComponent implements IListItemRenderer
{
public function PriceItemRenderer()
{
super();
}

// Internal variable for the property value.
private var _data:Object;

// Make the data property bindable.
[Bindable("dataChange")]

// Define the getter method.
public function get data():Object {
return _data;
}

// Define the setter method, and dispatch an event when the property
// changes to support data binding.
public function set data(value:Object):void {
_data = value;

dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
}

}
}

I took the code directly from the Flex documentation for IDataRenderer, so you don’t even have to type it yourself.

With that out of the way we can add in the two labels.

  1. Add variables to hold the two labels.
    		private var posLabel:Label;
    private var negLabel:Label;
  2. Modify the set data function to call invalidateProperties(). This is important because the change of the data has to make the text in the labels change AND to change their visibility.
    	    public function set data(value:Object):void {
    _data = value;
    
    invalidateProperties();
    dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
    }

    Calling invalidateProperties() tells the Flex framework to call the commitProperties() function at the apppriate time.

  3. Override createChildren() and create the labels, adding them to the display list of the component.
    Notice that in addition to creating the labels, their styles and visible are also set.

    		override protected function createChildren() : void
    {
    super.createChildren();
    
    posLabel = new Label();
    posLabel.visible = false;
    posLabel.setStyle("color", 0x00FF00);
    addChild(posLabel);
    
    negLabel = new Label();
    negLabel.visible = false;
    negLabel.setStyle("color", 0xFF0000);
    addChild(negLabel);
    }
  4. Override commitProperties() to set the labels’ text and visibility.
    In the past you’ve been overriding set data to make this type of change, and you can do that in this class, too, if you prefer.

    		override protected function commitProperties():void
    {
    super.commitProperties();
    posLabel.text = data.price;
    negLabel.text = data.price;
    
    posLabel.visible = Number(data.price) > 0;
    negLabel.visible = Number(data.price) < 0;
    }
  5. Override updateDisplayList() to size and position the labels.
    You must size the labels because their default size is 0×0. This is another thing a Container class will do for you. Since this is a pretty simple itemRenderer you can just set the labels’ size to match the size of the itemRenderer.

    		override protected function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number ) : void
    {
    super.updateDisplayList(unscaledWidth, unscaledHeight);
    
    posLabel.move(0,0);
    posLabel.setActualSize(unscaledWidth,unscaledHeight);
    
    negLabel.move(0,0);
    negLabel.setActualSize(unscaledWidth, unscaledHeight);
    }

All this probably seems a bit complicated just to do this, but keep in mind that using a container will add a lot more code than this.

UIComponent Notes

The UIComponent class is the basis for all visual Flex components – controls and containers. Here are some tips about using UIComponent as your itemRenderer.

  • UIComponent imposes no layout restrictions on its children (unlike a Container). You have to position and size the children yourself.
  • It is also possible to draw graphics and position children beyond the size specified in updateDisplayList().
  • If you plan on using variableRowHeight in your list, you should also override the measure() function to give the list an idea of how big the itemRenderer is.
  • To use UIComponent as an itemRenderer you must implement IDataRenderer.
  • To use the listData property you must implement IDropInListItemRenderer; that was covered in a previous article of this series.

itemRenderers: Part 4: States and Transitions

,,,

Communicating the with the user of your application is what your itemRenderer does best. Sometimes that communication is as simple as presenting a name; sometimes more elborately using colors; and sometimes with interactivity.

itemEditors are truely interactive controls, but they are not the focus of this article. In these examples we’ll look at itemRenderers that change their visual appearance based on either the data itself or the user’s actions.

States

The Flex <mx:State> is a very good way to change the appearance of an itemRenderer. States are easy to use, and when combined with Transitions, give the user feedback and pleasent experience.

In this example we’ll create a new MXML itemRenderer (and remember, you can do this completely in ActionScript if you prefer) for the List. All this shows is the image, title, author, price, and a Button to purchase the book.

<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" >

<mx:Image id="bookImage" source="{data.image}" />
<mx:VBox height="115" width="100%" verticalAlign="top" verticalGap="0" paddingRight="10">
<mx:Text text="{data.title}" fontWeight="bold" width="100%"/>
<mx:Label text="{data.author}" />
<mx:HBox id="priceBox" width="100%">
<mx:Label text="{data.price}" width="100%"/>
<mx:Button label="Buy" />
</mx:HBox>
</mx:VBox>
</mx:HBox>

What we want however, is if the book is not in stock (the data has <instock> nodes which are either yes or no) for the price and Book to be invisible. I’ve made things a bit convenient for myself here because I gave the HBox parent of the price and Button an id. This allows me to change the visibility of both of those items by changing the visibility of the HBox, priceBox.

You can do this by overridding the set data function, which we’ll do, but instead of directly changing the visibility of priceBox, we’ll use this state defintion:

	<mx:states>
<mx:State name="NoStockState">
<mx:SetProperty target="{priceBox}" name="visible" value="false"/>
</mx:State>
</mx:states>

    Place this just below the root tag.

This example is a bit far-fetched in that it is overly complicated to do a simple task, but it shows how to use states. There are 2 states:

  • The base state – this is the normal state of a component. Components that do not use states simply have this base state. In this example, the base state has the priceBox visible property as true (the default). This is the case when instock is "yes".
  • The NoStockState – this is the state when the value of nostock is "no". When this state is active the SetProperty instructions are carried out. The target determines which member of the class is in question, the name property is the name of the property to change on the target, and value is the new value for the property.

The set data function determines which state to use by looking at the value of instock:

		override public function set data( value:Object ) : void
{
super.data = value;

if( data )
{
if( data.instock == "yes" )
currentState = "";
else
currentState = "NoStockState";
}
}

The currentState is a property of all UIComponent controls. It determines which State is the active one. When switching between states the Flex framework begins with the base state and then applies the rules for the given state.

Remember that itemRenderers are recycled, so you must always restore values; never leave an if without an else in an itemRenderer.

If you are feeling adventurous, you can do away with the set data override in this example. Instead, set currentState directly in the root tag by using data binding expression:

<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400"
currentState="{data.instock == 'yes' ? '' : 'NoStockState'}" >

The currentState’s value is set by examining data.instock right inline with the root tag. A nice trick, but it might be harder to maintain.

Adding Elements

In this itemRenderer the price and Buy button appears only if the instack value is yes. You could do this without a state of course, but if your itemRenderer has more controls to be added or removed, a state will make more sense as their appearance is controlled simply by setting the itemRenderer’s currentState property.

Instead of just removing the price and Button, we’ll have the state add a label telling the user the item is out of stock. Here’s the modified state:

	<mx:states>
<mx:State name="NoStockState">
<mx:SetProperty target="{priceBox}" name="visible" value="false"/>
<mx:AddChild relativeTo="{priceBox}" position="before">
<mx:Label text="-- currently not in stock --" color="#73DAF0"/>
</mx:AddChild>
</mx:State>
</mx:states>

The <mx:AddChild> tag says to add the Label into the priceBox. In addition to setting the priceBox’s visible property to false, a friendly message replaces it.

Again, you could add this label in the set data function – or add it initially and just set its visibility to false and change it to true in the set data function. But I think you can see the value of the State: if the requirement for the instock being no condition gets more complex, all you need to do is adjust the NoStockState; the ActionScript code which switches the state remains the same.

You can modify states in Flex Builder’s Design View.

Expanding List

This example does not work well for list controls but does perform nicely for a VBox and Repeater. This question of expanding an item in place becomes dicy when the list has to be scrolled. Imagine this: you’ve got a list of items will all the same height. Now you exand the height of item 2. So far so good – item 2 is taller than the other visible items. And there’s the catch: the visible items. Now scroll the list. Remember that itemRenderers are recycled. So when item 2 scrolls out of view, its itemRenderer will be moved to the bottom of the list. You’ve got to reset its height. OK, that can work pretty simply. Now scroll the list so item 2 is back in view. You would expect it to be the expanded height. How does the itemRenderer know to do that? From previous articles you know that information either comes from the data itself or from some external source.

I think a resizing itemRenderer is too complex and not really worth the effort. I believe there is a better way to do this using VBox and Repeater. However, the catch with Repeater is that every child will be created. If you have 1,000 records and use a Repeater you will get 1,000 instances of your itemRenderer.

For this example you’ll still write an itemRenderer but will use it as the child of a VBox.  The elements of a list look pretty simple: the name of a book and its author. But click the itemRenderer and it expands in place. This is accomplished using:

  • The itemRenderer has a state which includes the additional information.
  • The itemRenderer uses a Resize transition to give a smoother expansion and contraction of the itemRenderer.

The base state of the itemRenderer is pretty simple:

	<mx:HBox width="100%">
<mx:Label text="{data.author}" fontWeight="bold"/>
<mx:Text  text="{data.title}" width="100%" fontSize="12" selectable="false"/>
</mx:HBox>

The ExpandedState adds the additional elements which contribute to the itemRenderer’s height:

	<mx:states>
<mx:State name="ExpandedState">
<mx:AddChild position="lastChild">
<mx:HBox width="100%">
<mx:Image source="{data.image}"/>
<mx:Spacer width="100%"/>
<mx:Label text="{data.price}"/>
<mx:Button label="Buy"/>
</mx:HBox>
</mx:AddChild>
</mx:State>
</mx:states>

Getting the itemRenderer to change size is as simple as adding a Transition:

	<mx:transitions>
<mx:Transition fromState="*" toState="*">
<mx:Resize target="{this}" />
</mx:Transition>
</mx:transitions>

    Place this below the <mx:states>

The Transition is applied whenever the state changes because its fromState and toState properties are wildcards. Now all you have to do is add event handler for clicking on the itemRenderer (add a click event to the root tag) and change the state:

	<mx:Script>
<![CDATA[

private function expandItem() : void
{
if( currentState == "ExpandedState" )
currentState = "";
else
currentState = "ExpandedState";
}
]]>
</mx:Script>

Summary

States are a great way to make a number of modifications to the visual appearance of the itemRenderer. You can group the changes in a State and simply make it all happen by setting the currentState property of the itemRenderer.

In the next article we’ll look at writing more efficient itemRenderers by extending UIComponent.

Viewing PDFs with AIR

,,,

One of the nice things AIR allows is the ability to view both HTML and PDF content. Here’s a little app that shows how you can view PDF documents on the local computer.

The key is the flash.html.HTMLLoader class. This is a FLASH class and cannot be directly used with Flex components as it extends Sprite and does not implement the Flex IUIComponent interface.

This is easy to remedy though. Just create a new class that extends UIComponent (I called mine PDFViewer) and include an HTMLLoader member. Override createChildren() to make a new HTMLLoader instance and add it to the UIComponent’s display list. Then override updateDisplayList to size and position it.

The main AIR application uses a FileSystemTree to allow the user to navigate to their PDF files and select one. The file’s URL is passed to the PDFViewer which then loads it and displays it.

And that’s pretty much it. There are some caveats to use PDF with AIR which you can read in the documentation, but if you want to use PDFs for help/documentation on your product or to display a PDF generated by a server (eg, ColdFusion), it is pretty easy to do.

Download Example Code