Flex: access dynamically added RicheEditableText in other function - apache-flex

When I click on a userlist, the function addTab is triggered:
private var counter:int = 0;
public function addTab():void {
var new vBox:VBox = new VBox();
var textBox:RichEditableText = new RichEditableText();
var nameEm:String = "dynamicTextBox" + counter;
textBox.id = nameEm;
counter++;
var textFlow:TextFlow = new TextFlow();
vbox.addChild(textFlow);
vbox.addChild(textBox);
tabNavigator.add(vBox);
}
In another function, I would like to add Rich Text to the newly created TextBox, but I can not access it.
I tried getChildByName(vbox) and vbox.getChildByName(textBox), but that doesn't seem to work.

To get childbyname assigned a name to richeditable text and if you want to get it by counter then give name to vbox also, as in the sample here:
private var counter:int = 0;
public function addTab():void {
var new vBox:VBox = new VBox();
var textBox:RichEditableText = new RichEditableText();
var nameEm:String = "dynamicTextBox" + counter;
textBox.id = nameEm;
vBox.name=nameEm;
textBox.name=nameEm;
counter++;
var textFlow:TextFlow = new TextFlow();
vbox.addChild(textFlow);
vbox.addChild(textBox);
tabNavigator.add(vBox);
}
If you know the index then
var vb:VBox = tabNavigator.getChildByName("dynamicTextBox"+index) as VBox;
var txt:RichEditableText=vb.getChildByName("dynamicTextBox"+index) as VBox;
So this will give you RichEditableText.
Or if you want to get access just after adding in to tab then return RichEditableText from the addtab function.

Elaborating on my comment, the idea is that you do something like this:
private var counter:int = 0;
public function addTab():void {
var new vBox:VBox = new VBox();
vBox.name = "dynVbox" + counter;
var textBox:RichEditableText = new RichEditableText();
textBox.name = "dynamicTextBox" + counter;
var textFlow:TextFlow = new TextFlow();
textFlow.name = "dynamicTextFlow" + counter;
vbox.addChild(textFlow);
vbox.addChild(textBox);
tabNavigator.add(vBox);
counter++;
}
Now, outside this function, you just need to know the counter number of the vBox you want. So for example:
var myBox = tabNavigator.getChildByName('dynVbox'+ 32).getChildByName('dynamicTextBox'+32)
Without seeing more of your code, I don't know if this is the best way to go about it, but if you want to mark your boxes with some dynamically generated name and look them up later, this will work
Example documentation

Related

Flex sort array collection by inner class

I want to sort an array collection in a way that I am not sure is possible.
Usually when you want to sort you have something like this.
var dataSortField1:SortField = new SortField();
dataSortField1.name = fieldOneToSortBy;
dataSortField1.numeric = fieldOneIsNumeric;
var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField1];
arrayCollection.sort = dataSort;
arrayCollection.refresh();
so if I had a class
public class ToSort {
public var int:a
}
I could type
var ts1:ToSort = new ToSort();
ts1.a = 10;
var ts2:ToSort = new ToSort();
ts2.a = 20;
var arrayCollection:ArrayCollection = new ArrayCollection([ts1, ts2])
var dataSortField1:SortField = new SortField();
dataSortField1.name = "a";
dataSortField1.numeric = true;
var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField1];
arrayCollection.sort = dataSort;
arrayCollection.refresh();
This works fine. My problem is I now have inherited a class that has another class inside it and I need to sort against this as well.
For example
public class ToSort2 {
public var int:a
public var ToSortInner: inner1
}
public class ToSortInner {
public var int:aa
public var int:bb
}
if a is the same in multiple classes then I want to sort on ToSortInner2.aa Is this possible. I have tried to pass in inner1.aa as the sort field name but this does not work.
Hope this is clear. If not I'll post some more code.
Thanks
You need to write a custom sort compareFunction. You can drill down into the objects properties inside the function.
Conceptually something like this:
public function aSort(a:Object, b:Object, fields:Array = null):int{
if(a.aa is b.aa){
return 0
} else if(a.aa > b.aa) {
return 1
} else{
return -1
}
}
When you create your sort object, you can specify the compare function:
var dataSort:Sort = new Sort();
dataSort.compareFunction = aSort;
arrayCollection.sort = dataSort;
arrayCollection.refresh();
Sort also has another property, compareFunction.

Flex 3: Setting one arrayCollection to another is stalling the application

I'll just go ahead and C/P the entire function to ensure you guys see everything going on:
public function directorsPrepsToShow():void
{
var tempDPrepsAC:ArrayCollection = new ArrayCollection;
var dprepSD:Date = new Date;
var dprepED:Date = new Date;
var viewSD:Date = rightDate(startViewDate.getMonth(), startViewDate.getDate(), startViewDate.getFullYear());
var viewED:Date = rightDate(viewSD.getMonth(), viewSD.getDate() + 14, viewSD.getFullYear());
var newACIDs:String = new String;
var useACIDs:String = new String;
for each (var item:Object in dPrepAC)
{
dprepSD = textToDate(item[2]);
dprepED = rightDate(dprepSD.getMonth(), Number(dprepSD.getDate() + (item[3] - 1)), dprepSD.getFullYear());
if (dateCollider(dprepSD, dprepED, viewSD, viewED))
tempDPrepsAC.addItem(item as Array);
}
if (tempDPrepsAC.length != usePrepAC.length)
{
usePrepAC = new ArrayCollection();
usePrepAC = tempDPrepsAC;
Alert.show("HI");
}
}
This function is in a separate file, that's called from the main mxml via the following:
<mx:Script source="functions/dprep.as" />
The line that's causing the app to stall is "usePrepAC = tempDPrepAC;". usePrepAC is declared in the main mxml like this:
[Bindable] public var usePrepAC:ArrayCollection = new ArrayCollection;
Dose anybody see why this one line would cause the application to stall? If I comment out that line, the application loads fine (loads everything except for the information that this AC should contain). I've been looking at this now for about an hour, trying different ways to get the contents of tempDPrepsAC into usePrepAC - but nothing is working. I tried googling it, but found nothing :(
Thanks,
Brds
EDIT
dprep AC is declared in the main mxml like this:
[Bindable] public var dPrepAC:ArrayCollection = new ArrayCollection;
And the function that populates it is as follows:
public function createDirectorsPrepCollection(e:ResultEvent):void
{
var xmlList:XMLList = XML(e.result).directorsprep;
var dupString:String = "|";
var tempArray:Array = new Array;
for (var i:int = 0; i < xmlList.length(); i++)
{
if (dupString.indexOf(String("|" + xmlList[i].name.#id) + "|") == -1)
{
tempArray = new Array;
tempArray[0] = xmlList[i].prepDBID;
tempArray[1] = xmlList[i].projectDBID;
tempArray[2] = xmlList[i].startdate;
tempArray[3] = xmlList[i].numdays;
tempArray[4] = xmlList[i].positions;
dPrepAC.addItem(tempArray);
dupString += "|" + xmlList[i].prepDBID + "|";
}
}
directorsPrepsToShow();
}
This function is called by this:
<mx:HTTPService id="dprepHttp" url="{dprepXML}" resultFormat="e4x" makeObjectsBindable="true" result="createDirectorsPrepCollection(event)" />
dPrepAC is populating fine btw... I check it in a for each loop.
Try using following code:
usePrepAC.source = tempDPrepsAC.source;

load symbol of flash in flex at runtime

Hey people, I've this huge problem loading a symbol from a swf file in the application at runtime. I want to load it and pass it as a argument to another class where it could be used further. The symbol name is passed on from the array collection from the "o" object. Can anybody please tell me what's the right way to go about it.. Thanks in advance..!!
Following is the code for reference..
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var item:WeatherItem;
var items:ArrayCollection;
var widgetCount:Number;
var headlineFontSize:int;
var conditionsIconThemeLoader:Loader;
this.m_weatherWidgetContainer = new HBox();
super.Show(o);
_this = this;
_super = super;
(undefined == o["HeadlineFontSize"]) ? headlineFontSize = 20 : headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
items = ArrayCollection(o.LargeUrl.Forecast);
else
items = new ArrayCollection([o.LargeUrl.Forecast]);
widgetCount = this.m_computeWidgetSpace(items.length);
conditionsIconThemeLoader = new Loader();
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void
{
for(var i:uint = 0; i < widgetCount; i++)
{
var symbolClass:Class = e.currentTarget.loader.contentLoaderInfo.applicationDomain.currentDomain.getDefinition(int(items[i].condition)) as Class;
var symbolInstance:Sprite = new symbolClass();
item = new WeatherItem();
item.Show(items[i], headlineFontSize, symbolInstance, widgetCount);
_this.m_weatherWidgetContainer.addChild(item);
}
});
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void
{
Alert.show("Failure loading " + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf");
});
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"));
super.media.addChild(this.m_weatherWidgetContainer);
}
Heres the answer
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var conditionsIconThemeLoader:Loader;
var loaderContext:LoaderContext;
this.m_weatherWidgetContainer = new HBox();
this.m_weatherWidgetContainer.percentHeight = 100;
this.m_weatherWidgetContainer.percentWidth = 100;
super.Show(o);
_this = this;
(undefined == o["HeadlineFontSize"]) ? this.m_headlineFontSize = 20 : this.m_headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
this.m_items = o.LargeUrl.Forecast;
else
this.m_items = new ArrayCollection([o.LargeUrl.Forecast]);
conditionsIconThemeLoader = new Loader();
loaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.m_loaderSuccess);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.m_loaderFail);
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"), loaderContext);
this.m_weatherWidgetContainer.addEventListener(FlexEvent.CREATION_COMPLETE, this.m_drawHorizontalLine);
super.media.addChild(this.m_weatherWidgetContainer);
}

Flex, Problem when jpegencoding two bitmaps in sequence

I am creating this "drawing application", where the user can click "preview" and it will take what they made, draw a bitmap, and then I want to split that bitmap into left and right images. I create the first bitmap, encode it as a jpeg, and then use that to cut the left and right out using copypixels. I then reform the images together with a space inbetween in one canvas, and draw that canvas. Everything works fine up there.
When I go to encode the new bitmap, and then offer it to save out, the saved image is blank. I have tested everything up to that point and it all works fine. I see the images on screen, I can save out the first bitmap fine.. but the second one is always blank. Here is some sample code, possibly someone can help me out.
_mainBmd = new BitmapData(_jacketWidth, _jacketHeight);
_mainBmd.draw(_imageHolder);
startEncode(_mainBmd);
private function startEncode(imageBitmapData:BitmapData):void
{
var encoder:JPEGAsyncEncoder = new JPEGAsyncEncoder(100);
encoder.PixelsPerIteration = 150;
encoder.addEventListener(JPEGAsyncCompleteEvent.JPEGASYNC_COMPLETE, encodeDone);
encoder.encode(imageBitmapData);
}
private function encodeDone(event:JPEGAsyncCompleteEvent):void
{
_leftBmd = new BitmapData(sideWidth, sideHeight);
var lRect:Rectangle = new Rectangle(0,0, sideWidth, sideHeight);
var lPoint:Point = new Point(0,0);
_leftBmd.copyPixels(_mainBmd, lRect, lPoint);
_rightBmd = new BitmapData(sideWidth, sideHeight);
var bWidth:Number = 200;
var sWidth:Number = 111;
var rRectWidth:Number = (bWidth/2 + sWidth) * Constants.print_dpi;
var rRect:Rectangle = new Rectangle(rRectWidth, 0, sideWidth, sideHeight);
var rPoint:Point = new Point(0, 0);
_rightBmd.copyPixels(_mainBmd, rRect, rPoint);
var lbm:Bitmap = new Bitmap(_leftBmd);
var rbm:Bitmap = new Bitmap(_rightBmd);
//now combine the two images into one holder with a space in the middle
//left Image
var l_Image:Image = new Image();
l_Image.source = lbm;
//right image
var r_Image:Image = new Image();
r_Image.source = rbm;
var newRender:Canvas = new Canvas();
newRender.clipContent = false;
newRender.minHeight = 0;
newRender.minWidth = 0;
newRender.addChild(l_Image);
r_Image.x = 500;
newRender.addChild(r_Image);
fcBMD = new BitmapData(renderW, renderH);
fcBMD.draw(newRender);
startEncode2(fcBMD);
}
private function startEncode2(imageBitmapData:BitmapData):void
{
var encoder:JPEGAsyncEncoder = new JPEGAsyncEncoder(100);
encoder.PixelsPerIteration = 150;
encoder.addEventListener(JPEGAsyncCompleteEvent.JPEGASYNC_COMPLETE, encode2Done);
encoder.encode(imageBitmapData);
}
private function encode2Done(event:JPEGAsyncCompleteEvent):void
{
_data = event.ImageData;
}
private function onSaveRenderClick(e:MouseEvent):void //save button listener
{
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(Event.SELECT, onSaveComplete);
fileRef.save(_data, 'testImage.jpg');
}
Is there a special reason why you go trough all the loops of creating a Canvas holder and adding Images?
Why not use copyPixels directly on the final BitmapData that you want to encode:
var backgroundColor:uint = 0xffffff;
fcBMD = new BitmapData(renderW, renderH, false, backgroundColor);
var lPoint:Point = new Point(0,0);
var lRect:Rectangle = new Rectangle(0,0, sideWidth, sideHeight);
fcBMD.copyPixels(_mainBmd, lRect, lPoint);
var rRect:Rectangle = new Rectangle(rRectWidth, 0, sideWidth, sideHeight);
var rPoint:Point = new Point(renderW - sideWidth, 0);
fcBMD.copyPixels(_mainBmd, rRect, rPoint);
startEncode2(fcBMD);

How to read the Dynamic form Child data in Flex?

i created a form dynamically by adding each component in action script,
now i want to get back the text/data entered in to that each component dynamically?
private function loadAllComponents():void
{
var formItemArray:Array = new Array();
for(var i:int=0; i< Application.application.designList.length; i++)//which had the colonName, colComponet to be dispalyed,
{
var fm:FormItem = new FormItem();
fm.label = Application.application.designList.getItemAt(i).colName;
var comp:String = Application.application.designList.getItemAt(i).component;
switch(comp)
{
case "TextBox":
var ti:TextInput = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
fm.addChild(ti);
break;
case "TextArea":
var ta:TextArea = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
fm.addChild(ta);
break;
case "ComboBox":
var mycb:myComboBox = new myComboBox();
mycb.getAllMasterCBData(Application.application.selectedgridItem, Application.application.designList.getItemAt(i).colName);
fm.addChild(mycb);
break;
case "DateField":
var df:DateField = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
fm.addChild(df);
break;
}
myform.addChild(fm);
}
}
private function saveToDb():void // Here i wan to read all the formdata
{
var formItems:Array = myform.getChildren();
for each (var item:UIComponent in formItems)
{
if (item is TextInput)
{
var text:String = Object(item).text;
Alert.show("came here");
}
else if (item is DateField)
{
var date:Date = DateField(item).selectedDate;
}
}
}
]]>
</mx:Script>
<mx:Form id="myform" cornerRadius="5" borderColor="#B7BABC" borderStyle="solid" width="100%" height="100%" />
<mx:HBox width="100%" height="100%" >
<mx:Spacer width="120"/>
<mx:Button label=" Save " id="saveBtn" click="saveToDb()" />
</mx:HBox>
You're creating the input components in ActionScript, but based on this code you are not creating them dynamically; you're just hard coding them. With your given sample, you'll know the components you are creating at compile time.
You'll need to store a reference to the form items you create; make them public variables instead of 'var' local variables. Kind of like this:
protected var ti:TextInput ;
protected var ta:TextArea ;
protected var df:DateField;
Then in your creation method, do something like this:
ti = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
fm.addChild(ti);
ta = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
fm.addChild(ta);
df = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
fm.addChild(df);
myform.addChild(fm);
Then when you need to access them, just do something like this:
private function getMyformData()
{
ti.text;
ta.text;
}
If you're generating the form components at run time based on data, then store then form elements in an array of some sort.
You could also work something out by looping over all children of your container, although that wouldn't be my first approach.
Since poster posted more complete code; here are some additions. I added the protected array of all form items and in each 'switch' block; the new input element is pushed onto the array.
<mx:Script>
protected var itemsArray : Array = new Array();
private function loadAllComponents():void
{
var formItemArray:Array = new Array();
for(var i:int=0; i< Application.application.designList.length; i++)//which had the colonName, colComponet to be dispalyed,
{
var fm:FormItem = new FormItem();
fm.label = Application.application.designList.getItemAt(i).colName;
var comp:String = Application.application.designList.getItemAt(i).component;
switch(comp)
{
case "TextBox":
var ti:TextInput = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
fm.addChild(ti);
itemsArray.push(ti)
break;
case "TextArea":
var ta:TextArea = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
fm.addChild(ta);
itemsArray.push(ta)
break;
case "ComboBox":
var mycb:myComboBox = new myComboBox();
mycb.getAllMasterCBData(Application.application.selectedgridItem, Application.application.designList.getItemAt(i).colName);
fm.addChild(mycb);
itemsArray.push(mycb)
break;
case "DateField":
var df:DateField = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
fm.addChild(df);
itemsArray.push(df)
break;
}
myform.addChild(fm);
}
}
The sateToDb method will change to be something like this:
private function saveToDb():void // Here i wan to read all the formdata
{
var formItems:Array = myform.getChildren();
for each (var item:UIComponent in itemsArray )
{
if (item is TextInput)
{
var text:String = Object(item).text;
Alert.show("came here");
}
else if (item is DateField)
{
var date:Date = DateField(item).selectedDate;
}
}
}
]]>
</mx:Script>
Edited Response:
OK, I think I see the issue.
You're adding your data controls to FormItems and adding those to the Form. But then you're iterating over the Form's children and as if they were the data controls and not FormItems.
Without commenting on the rest of the code, have a look at what this updated function is doing to retrieve the data controls:
private function saveToDb():void
{
var formItems:Array = myform.getChildren();
for each (var item:FormItem in formItems)
{
var itemChildren:Array = item.getChildren();
for each (var control:UIComponent in itemChildren)
{
if (control is TextInput)
{
var text:String = Object(item).text;
Alert.show("TextInput");
}
else if (control is DateField)
{
var date:Date = DateField(item).selectedDate;
Alert.show("Date");
}
}
}
You can delete the formItemArray variable too, it's not needed since we're getting the list of children from the Form and FormItems.
Original response:
If you keep a reference to each of the dynamic form items in an Array you can iterate over each of them in your getMyFormData() function.
e.g.
protected var formItems:Array = new Array();
// Other class stuff here...
var ti:TextInput = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
formItems.push(ti); // Add item to array.
fm.addChild(ti);
var ta:TextArea = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
formItems.push(ta); // Add item to array.
fm.addChild(ta);
var df:DateField = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
formItems.push(df); // Add item to array.
fm.addChild(df);
myform.addChild(fm);
<mx:button click="getMyformData()"/>
private function getMyformData()
{
//How to get the myform Data dynamically here after validations... ? &
for each (var item:UIComponent in formItems)
{
if (item is TextInput || item is TextArea)
{
// Cast to Object to access the 'text' property without the compiler complaining.
var text:String = Object(item).text;
// Do something with the text...
}
else if (item is DateField)
{
var date:Date = DateField(item).selectedDate;
// Do something with the date...
}
// Insert additional type checks as needed.
}
}
You'll have to work out what to do with the data on your own though :)
If you are using a separate list make sure you clear out the formItems array when you're done with it so you don't have references to the items keeping them in memory unnecessarily.
Instead of keeping a separate array of form items you could also iterate over the children in the fm container. You might have to make some assumptions about the children you'd be accessing but it looks like you have control over all of the children being added so that's no problem.
I hope that helps...
:)

Resources