AdvancedDataGrid dataField - how to use a subarray or object in flex? - apache-flex

I have an advanced data grid in flex (flash builder 4). It's dataProvider is pointing to an ArrayCollection (this._encounters).
Inside that array collection is a property that is an object (a client object).
I tried setting the dataField to "clientObj.firstName" to refer to the first name property within the clientObj property of the this._encounters array collection. It did not show anything.
So, I added a labelFunction to that column (code below) to set the text in the cell. This works fine and now I have values showing in the grid.
The problem is now when I click the title of column to sort it. It throws an error that property clientObj.firstName is not found in my array collection!
So, is there a better way to set the dataField / source for a column and point at a property in a sub-object -- or a way to fix the sort?
Below the first column
<mx:AdvancedDataGrid x="0" y="25" id="adgEncounters" designViewDataType="flat" width="100%" height="100%" dataProvider="{this._encounters}">
<mx:columns>
<mx:AdvancedDataGridColumn headerText="first" dataField="clientObj.firstName" labelFunction="encounterGridLabelFunct"/>
<mx:AdvancedDataGridColumn headerText="first" dataField="thisWorksField"/>
</mx:columns>
</mx:AdvancedDataGrid>
protected function encounterGridLabelFunct(item:Object, column:AdvancedDataGridColumn):String //put just the HH:MM in to the grid, not the whole date string
{
if(column.headerText=="first") result=item.clientObj.firstName;
return result;
}
update:
Here is the final working code I used. 3 example sort functions, 1 for numeric sorting, 1 for String sorting and one for Date sorting (string date from a database).:
// sort adg column numerically
private function numericSortByField(subObjectName:String, fieldName:String):Function
{
return function(obj1:Object, obj2:Object):int
{
var value1:Number = (obj1[subObjectName][fieldName] == '' || obj1[subObjectName][fieldName] == null) ? null : new Number(obj1[subObjectName][fieldName]);
var value2:Number = (obj2[subObjectName][fieldName] == '' || obj2[subObjectName][fieldName] == null) ? null : new Number(obj2[subObjectName][fieldName]);
return ObjectUtil.numericCompare(value1, value2);
}
}
//sort adg column string
private function stringSortByField(subObjectName:String, fieldName:String):Function
{
return function(obj1:Object, obj2:Object):int
{
var value1:String = (obj1[subObjectName][fieldName] == '' || obj1[subObjectName][fieldName] == null) ? null : new String(obj1[subObjectName][fieldName]);
var value2:String = (obj2[subObjectName][fieldName] == '' || obj2[subObjectName][fieldName] == null) ? null : new String(obj2[subObjectName][fieldName]);
return ObjectUtil.stringCompare(value1, value2);
}
}
//sort adg date diff (takes date strings for example from a db)
private function dateSortByField(subObjectName:String, fieldName:String):Function
{
return function(obj1:Object, obj2:Object):int
{
var value1:String = (obj1[subObjectName][fieldName] == '' || obj1[subObjectName][fieldName] == null) ? null : new String(obj1[subObjectName][fieldName]);
var value2:String = (obj2[subObjectName][fieldName] == '' || obj2[subObjectName][fieldName] == null) ? null : new String(obj2[subObjectName][fieldName]);
var value1Date:Date = new Date();
var value1Time:int = value1Date.setTime(Date.parse(value1));
var value2Date:Date = new Date();
var value2Time:int = value2Date.setTime(Date.parse(value2));
return ObjectUtil.numericCompare(value1Time, value2Time);
}
}
In the mxml above, this is the changed line - notice the stringSortByField added:
<mx:AdvancedDataGridColumn headerText="first" dataField="clientObj.firstName" sortCompareFunction="{stringSortByField('clientObj','firstName')}" labelFunction="encounterGridLabelFunct"/>
If it were a numeric field use the numericSortByField. If it were a date string from a database, use the dateSortByField function instead.

You could use a custom compare function, thats how I do it (obviously your itemA
and itemB will be different objects, so cast them as such):
In your AdvancedDataGridColumn put in:
sortCompareFunction="string_sortCompareFunc"
and make the function:
private function string_sortCompareFunc(itemA:Object, itemB:Object):int
{
var a:String = itemA as String;
var b:String = itemB as String;
return ObjectUtil.stringCompare(a, b);
}

Related

Unable to check existing XML nodes in Adobe Flex 3

I am getting an XML data from server (please refer to xmlData value).
I need to:
Create another XML with non-duplicates Folders
Create another XML with final count on monthly basis.
I am unable to do this with below code and getting duplicate records.
private var xmlData:XML = new XML("<root><SUMMARY_RECORD><FOLDER>Folder1</FOLDER><COUNT>100</COUNT><MONTH>Feb</MONTH><QUARTER>Q1</QUARTER><YEAR>2014</YEAR></SUMMARY_RECORD><SUMMARY_RECORD><FOLDER>Folder1</FOLDER><COUNT>100</COUNT><MONTH>Feb</MONTH><QUARTER>Q1</QUARTER><YEAR>2014</YEAR></SUMMARY_RECORD></root>");
var folderDataXML:XML = new XML("<root></root>");
var folderDGDataXML:XML = new XML("<root></root>");
private function loaded():void{
var item:XML;
folderDGDataXML.appendChild(new XML("<FOLDER_NAME><Name>ALL</Name></FOLDER_NAME>"));
for each (item in xmlData.SUMMARY_RECORD){
if (folderDGDataXML.FOLDER_NAME.(Name==item.FOLDER).toString() == ""){
folderDGDataXML.appendChild(new XML("<FOLDER_NAME><Name>"+item.FOLDER+"</Name></FOLDER_NAME>"));
}
if (folderDataXML.SUMMARY_RECORD.(Name==item.MONTH).toXMLString() == ""){
folderDataXML.appendChild(new XML("<SUMMARY_RECORD><Name>"+item.MONTH+"</Name><COUNT>"+item.COUNT+"</COUNT></SUMMARY_RECORD>"));
}else{
var count:int = Number(folderDataXML.SUMMARY_RECORD.(Name==item.MONTH).COUNT) + Number(item.COUNT);
folderDataXML.SUMMARY_RECORD.(Name==item.MONTH).COUNT = count;
}
}
}
Final output, folderDGDataXML:
<root>
<FOLDER_NAME>
<Name>ALL</Name>
</FOLDER_NAME>
<FOLDER_NAME>
<Name>Folder1</Name>
</FOLDER_NAME>
<FOLDER_NAME>
<Name>Folder1</Name>
</FOLDER_NAME>
</root>
folderDataXML:
<root>
<SUMMARY_RECORD>
<Name>Feb</Name>
<COUNT>100</COUNT>
</SUMMARY_RECORD>
<SUMMARY_RECORD>
<Name>Feb</Name>
<COUNT>100</COUNT>
</SUMMARY_RECORD>
</root>
What am I doing wrong?
After getting correct XML, I need to populate datagrid & column chart.
Try this one
In XML Checking the elements present or not with hasOwnProperty or we can use in operator anyhow our case if it is based on value try like this way folderDGDataXML.descendants("FOLDER_NAME").(Name.text() == "Folder1"); //Return always XMLList. With the help of length() we can predict element with value occur or not.
Hope this will work for you.
var xmlData:XML = new XML("<root><SUMMARY_RECORD><FOLDER>Folder1</FOLDER><COUNT>100</COUNT><MONTH>Feb</MONTH><QUARTER>Q1</QUARTER><YEAR>2014</YEAR></SUMMARY_RECORD><SUMMARY_RECORD><FOLDER>Folder1</FOLDER><COUNT>100</COUNT><MONTH>Feb</MONTH><QUARTER>Q1</QUARTER><YEAR>2014</YEAR></SUMMARY_RECORD></root>");
var folderDataXML:XML = new XML("<root></root>");
var folderDGDataXML:XML = new XML("<root></root>");
var item:XML;
folderDGDataXML.appendChild(new XML("<FOLDER_NAME><Name>ALL</Name></FOLDER_NAME>"));
for each (item in xmlData.SUMMARY_RECORD)
{
var folderName:String = item.FOLDER.text();
var monthName:String = item.MONTH.text();
var existXMLList:XMLList = folderDGDataXML.descendants("FOLDER_NAME").(Name.text() == folderName);
if (existXMLList.length() == 0)
{
folderDGDataXML.appendChild(new XML("<FOLDER_NAME><Name>"+item.FOLDER+"</Name></FOLDER_NAME>"));
}
var monthXMLList:XMLList = folderDataXML.descendants("SUMMARY_RECORD").(Name.text() == monthName);
if (monthXMLList.length() == 0)
{
folderDataXML.appendChild(new XML("<SUMMARY_RECORD><Name>"+item.MONTH+"</Name><COUNT>"+item.COUNT+"</COUNT></SUMMARY_RECORD>"));
}
else
{
monthXMLList..COUNT = Number(monthXMLList..COUNT) + Number(item.COUNT);
//If more than one node it throws error. you need to use loop operation
}
}
trace("folderDGDataXML" + folderDGDataXML);
trace("folderDataXML" + folderDataXML);

How to sort an ArrayCollection by values

I have a list of items in an ArrayCollection that I'd like sorted by a certain value (not alphabetical). Is it possible to sort this way?
Here are the values I want to be ordered by:
Resolved
Closed
Open
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Addition to the provided answer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If your array collection is part of a DataGrid then you can set the sortCompareFunction on the DataGrid's GridColumn. Note that the syntax is different for this sort compare function as the grid colummn is passed in rather than the fields.
EXAMPLE CODE
used with a Spark DataGrid
private var desiredItemOrder:Array = ["In Progress", "Open", "Resolved", "Closed"];
private function sortCompareFunction(item:Object, anotherItem:Object, column:GridColumn = null):int
{
var itemIndex:Number = desiredItemOrder.indexOf(item.fields.status.name);
var anotherItemIndex:Number = desiredItemOrder.indexOf(anotherItem.fields.status.name);
if (itemIndex == -1 || anotherItemIndex == -1)
throw new Error("Invalid value for criticality ");
if (itemIndex == anotherItemIndex)
return 0;
if (itemIndex > anotherItemIndex)
return 1;
return -1;
}
<s:DataGrid dataProvider="{issuesCollection}">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="fields.status.name" headerText="Status" sortCompareFunction="sortCompareFunction"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
DOCUMENATION
Sort compareFunction
DataGridColumn sortCompareFunction
GridColumn sortCompareFunction
this may be of some help to you
Sorting an ArrayCollection in Flex
If you want to sort only 3 words - make this comparison in sort function like:
private static var valuesOrder : Array = ["Resolved", "Closed", "Open"];
private function sortFunction(a:Object, b:Object, array:Array = null) : int{
var indexA : int = valuesOrder.indexOf(a);
var indexB : int = valuesOrder.indexOf(b);
return indexA - indexB;//return positive if indexA > indexB
}
var sort : Sort = new Sort();
sort.compareFunction = sortFunction;
arrayCollection.sort = sort;
arrayCollection.refresh();
Note, if value not exists in valuesOrder array - index will be -1. Process this situation as you wish.

Flex DatagridColumn LabelFunction Additonal Parameters

I have a datagridcolumn where a labelFunction is defined:
private function myLabelFunction(item:Object, column:DataGridColumn):String
{
var returnVal:String;
var nm:NumericFormatter;
nm.decimalSeparatorTo = ".";
nm.precision = additionalParameter;
returnVal = nmTwoDecimals.format(item[column.dataField]);
if (returnVal == '0.00')
{
returnVal = '';
}
return returnVal;
}
Would it be possible to add an additional parameter so that I could pass the property values for the formatter which I intend to use?
Like for example:
private function myLabelFunction(item:Object, column:DataGridColumn, precisionParam:int):String
{
var returnVal:String;
var nm:NumericFormatter;
nm.decimalSeparatorTo = ".";
nm.precision = precisionParam;
returnVal = nmTwoDecimals.format(item[column.dataField]);
if (returnVal == '0.00')
{
returnVal = '';
}
return returnVal;
}
Thanks.
You would have to extend the DataGridColumn class. After creating your new class simply override the existing itemToLabel function:
public function itemToLabel(data:Object):String
{
if (!data)
return " ";
if (labelFunction != null)
return labelFunction(data, this);
if (owner.labelFunction != null)
return owner.labelFunction(data, this);
if (typeof(data) == "object" || typeof(data) == "xml")
{
try
{
if ( !hasComplexFieldName )
data = data[dataField];
else
data = deriveComplexColumnData( data );
}
catch(e:Error)
{
data = null;
}
}
if (data is String)
return String(data);
try
{
return data.toString();
}
catch(e:Error)
{
}
return " ";
}
The line 'return labelFunction(data, this);' is what calls the labelFunction (will also check the owner datagrid for a labelfunction). 'data' in 'itemToLabel' is your object. You could either include the precision value you want in the object or hard code it in the extended class (or inject, or singleton, class var, whatever you like).
At this point you can go ahead and pass it as a third parameter to your new labelFunction.
In your label function for the datagrid column, you can access the assigned data field by using the dataField property, see the following syntax below:
"supposing your label function is called formatNumbers_LabelFunction"
private function formatNumbers_LabelFunction(item:Object, column:DataGridColumn):String{
//Write any code logic you want to apply on your data field ;)
//In this example, I'm using a number formatter to edit numbers
return myCustomNumberFormatter.format(item[column.dataField]);
}
This way, you can use a generic label function to handle some unified operations on your displayed data
And besides that, you can also access to any data field that is in the data provider by just calling its name like this:
item.YourFieldName
where item is the firs parameter [of type Object] in your label function method
This would work:
<DataGridColumn labelFunction="{function(item:Object, column:DataGridColumn):String { return anotherLabelFunction(item,column,2) }}" />
// Elsewhere ...
function anotherLabelFunction(item:Object,column:DataGridColumn,precision:int):String
{
// Do your business
}

How do I dynamically instantiate a class, and set a property at runtime in Flex 3?

Using org.as3commons.reflect I can look-up the class name, and instantiate a class at runtime. I also have (non-working) code which invokes a method. However, I really want to set a property value. I'm not sure if properties are realized as methods internally in Flex.
I have a Metadata class which stores 3 pieces of information: name, value, and type (all are strings). I want to be able to loop through an Array of Metadata objects and set the corresponding properties on the instantiated class.
package com.acme.reporting.builders
{
import com.acme.reporting.model.Metadata;
import mx.core.UIComponent;
import org.as3commons.reflect.ClassUtils;
import org.as3commons.reflect.MethodInvoker;
public class UIComponentBuilder implements IUIComponentBuilder
{
public function build(metadata:Array):UIComponent
{
var typeClass:Class = ClassUtils.forName(getTypeName(metadata));
var result:* = ClassUtils.newInstance(typeClass);
for each (var m:Metadata in metadata)
{
if (m.name == "type")
continue;
// Attempting to invoke as method,
// would really like the property though
var methodInvoker:MethodInvoker = new MethodInvoker();
methodInvoker.target = result;
methodInvoker.method = m.name;
methodInvoker.arguments = [m.value];
var returnValue:* = methodInvoker.invoke(); // Fails!
}
return result;
}
private static function getTypeName(metadata:Array):String
{
if (metadata == null || metadata.length == 0)
throw new ArgumentError("metadata is null or empty");
var typeName:String;
// Type is usually the first entry
if (metadata.length > 1 && metadata[0] != null && metadata[0].name == "type")
{
typeName = metadata[0].value;
}
else
{
var typeMetadata:Array = metadata.filter(
function(element:*, index:int, arr:Array):Boolean
{
return element.name == "type";
}
);
if (typeMetadata == null || typeMetadata.length != 1)
throw new ArgumentError("type entry not found in metadata");
typeName = typeMetadata[0].value;
}
if (typeName == null || typeName.length == 0)
throw new Error("typeName is null or blank");
return typeName;
}
}
}
Here's some usage code:
var metadata:Array = new Array();
metadata[0] = new Metadata("type", "mx.controls.Text", null);
metadata[1] = new Metadata("text", "Hello World!", null);
metadata[2] = new Metadata("x", "77", null);
metadata[3] = new Metadata("y", "593", null);
this.addChild(new UIComponentBuilder().build(metadata));
I realize that I have to declare a dummy variable of the type I was to instantiate, or use the -inculde compiler directive. An unfortunate drawback of Flex.
Also, right now there's code to account for typecasting the value to it's specified type.
Dynamic execution in AS3 is much simpler than in other languages. This code:
var methodInvoker:MethodInvoker = new MethodInvoker();
methodInvoker.target = result;
methodInvoker.method = m.name;
methodInvoker.arguments = [m.value];
var returnValue:* = methodInvoker.invoke(); // Fails!
can be simplified to this:
var returnValue:* = result[method](m.value);
EDIT:
Since it's a property, it would be done like this:
result[method] = m.value;
and there is no return value (well, you can call the getter again but it should just return m.value unless the setter/getter do something funky.

Flex: Sort -- Writing a custom compareFunction?

OK, I am sorting an XMLListCollection in alphabetical order. I have one issue though. If the value is "ALL" I want it to be first in the list. In most cases this happens already but values that are numbers are being sorted before "ALL". I want "ALL" to always be the first selection in my dataProvider and then the rest alphabetical.
So I am trying to write my own sort function. Is there a way I can check if one of the values is all, and if not tell it to do the regular compare on the values?
Here is what I have:
function myCompare(a:Object, b:Object, fields:Array = null):int
{
if(String(a).toLowerCase() == 'all')
{
return -1;
}
else
if(String(b).toLowerCase() == 'all')
{
return 1;
}
// NEED to return default comparison results here?
}
//------------------------------
var sort:Sort = new Sort();
sort.compareFunction = myCompare;
Is there a solution for what I am trying to do?
The solution from John Isaacks is awesome, but he forgot about "fields" variable and his example doesn't work for more complicated objects (other than Strings)
Example:
// collection with custom objects. We want to sort them on "value" property
// var item:CustomObject = new CustomObject();
// item.name = 'Test';
// item.value = 'Simple Value';
var collection:ArrayCollection = new ArrayCollection();
var s:Sort = new Sort();
s.fields = [new SortField("value")];
s.compareFunction = myCompare;
collection.sort = s;
collection.refresh();
private function myCompare(a:Object, b:Object, fields:Array = null):int
{
if(String((a as CustomObject).value).toLowerCase() == 'all')
{
return -1;
}
else if(String((b as CustomObject).value).toLowerCase() == 'all')
{
return 1;
}
// NEED to return default comparison results here?
var s:Sort = new Sort();
s.fields = fields;
var f:Function = s.compareFunction;
return f.call(null,a,b,fields);
}
Well I tried something out, and I am really surprised it actually worked, but here is what I did.
The Sort class has a private function called internalCompare. Since it is private you cannot call it. BUT there is a getter function called compareFunction, and if no compare function is defined it returns a reference to the internalCompare function. So what I did was get this reference and then call it.
private function myCompare(a:Object, b:Object, fields:Array = null):int
{
if(String(a).toLowerCase() == 'all')
{
return -1;
}
else if(String(b).toLowerCase() == 'all')
{
return 1;
}
// NEED to return default comparison results here?
var s:Sort = new Sort();
var f:Function = s.compareFunction;
return f.call(null,a,b,fields);
}
Thanks guys, this helped a lot. In our case, we needed all empty rows (in a DataGrid) on the bottom. All non-empty rows should be sorted normally. Our row data is all dynamic Objects (converted from JSON) -- the call to ValidationHelper.hasData() simply checks if the row is empty. For some reason the fields sometimes contain the dataField String value instead of SortFields, hence the check before setting the 'fields' property:
private function compareEmptyAlwaysLast(a:Object, b:Object, fields:Array = null):int {
var result:int;
if (!ValidationHelper.hasData(a)) {
result = 1;
} else if (!ValidationHelper.hasData(b)) {
result = -1;
} else {
if (fields && fields.length > 0 && fields[0] is SortField) {
STATIC_SORT.fields = fields;
}
var f:Function = STATIC_SORT.compareFunction;
result = f.call(null,a,b,fields);
}
return result;
}
I didn't find these approaches to work for my situation, which was to alphabetize a list of Strings and then append a 'Create new...' item at the end of the list.
The way I handled things is a little inelegant, but reliable.
I sorted my ArrayCollection of Strings, called orgNameList, with an alpha sort, like so:
var alphaSort:Sort = new Sort();
alphaSort.fields = [new SortField(null, true)];
orgNameList.sort = alphaSort;
orgNameList.refresh();
Then I copied the elements of the sorted list into a new ArrayCollection, called customerDataList. The result being that the new ArrayCollection of elements are in alphabetical order, but are not under the influence of a Sort object. So, adding a new element will add it to the end of the ArrayCollection. Likewise, adding an item to a particular index in the ArrayCollection will also work as expected.
for each(var org:String in orgNameList)
{
customerDataList.addItem(org);
}
Then I just tacked on the 'Create new...' item, like this:
if(userIsAllowedToCreateNewCustomer)
{
customerDataList.addItem(CREATE_NEW);
customerDataList.refresh();
}

Resources