Friday 23 October 2009

FLEX - What to do when your returned data has only one record

In Flex the easiest way to get data back from the server (any server) is to provide it with nicely formatted XML which Flex can cope with very easily and pop it into an ArrayCollection object. However what happens when your data set has only one record?

Yes Flex falls over because it cannot force the returned single item data type into an ArrayCollection object for example you may have this actionscript assuming you have some XML coming down that is called myData with rows of myArticles that have fields called myType and myKey in it
private var myData:ArrayCollectionmy;
Data = event.result.myData.myArticle;
If only one or no records are returned then flex throws an error and you have to code your way around it like this
private var myData:ArrayCollectionmy;
     myData = event.result.myData.myArticle;
} catch(error:Error) {
     var rcd:Object= new Object();
     rcd.myType = event.result.myData.myArticle.myType;
     rcd.myKey = event.result.myData.myArticle.myKey;
     myData = new ArrayCollection()

What is this code doing?
Well the bit in the TRY{} tries to stuff the returned data into the Defined but uninstansiated ArrayCollection object called myData, if it succeeds (ie there was more than one record) everything is fine and the code will continue. If however there is only one record the CATCH{} code is run. I am not particularly interested in the error that is produced but it must be defined in the catch(error:Error) structure.

First I have to instansiate the ArrayCollection object with a new statement otherwise the object is null and you will get another error.

Then I create a new vanilla flex object called rcd

This object is populated with properties with names that match exactly the properties of the XML node

Once all the properties are set I add it into the ArrayCollection object and everything is fine

*** Note *** this code does not pick up on ZERO records.. this is because I NEVER return an empty data set. If the data set is empty i will construct a row that indicated to the user that no records where available. I suggest you do the same.

Disqus for Domi-No-Yes-Maybe