Display total sum of rows values in arraycollection - Adobe Flex - actionscript-3

I want to display total sum of rows values in an arraycollection. For example:
Definition Value
Product 1 20.00
Product 2 50.00
Product 3 30.00
Total 100.00
I have this code:
<mx:DataGrid id="srcgrid">
<mx:columns>
<mx:DataGridColumn dataField="Definition"/>
<mx:DataGridColumn dataField="Value"/>
</mx:columns>
</mx:DataGrid>
<s:Form>
<s:FormItem label="Total">
<s:Label text="{total()}"/>
</s:FormItem>
</s:Form>
And the script:
public function total():String {
var i:Number = 0;
for each(var obj:Object in ArrayCollection(DataGrid(srcgrid).dataProvider)){
i = i + obj.Value;
}
return i.toString();
}
Any idea?
Thanks in advance

The total() function was called before there was anything inside the dataProvider.
Also srcgrid.dataProvider can be looped as an Object
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="addInitData(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:DataGrid id="srcgrid">
<mx:columns>
<mx:DataGridColumn dataField="Definition"/>
<mx:DataGridColumn dataField="Value"/>
</mx:columns>
</mx:DataGrid>
<s:Form x="250">
<s:FormItem label="Total">
<s:Label id="total"/>
</s:FormItem>
</s:Form>
<fx:Script>
<![CDATA[
import flash.events.Event;
import mx.collections.ArrayList;
private function addInitData(e:Event = null):void{
var dataProvider:ArrayList = new ArrayList();
for (var i:int = 0; i < 12; i++){
dataProvider.addItem({Definition : 'item_' + i, Value : i});
}
srcgrid.dataProvider = dataProvider;
updTotal();
}
private function updTotal():void{
var sum:Number = 0;
for (var k:String in srcgrid.dataProvider){
sum += srcgrid.dataProvider[k]['Value'];
}
total.text = sum.toString();
}
]]>
</fx:Script>
</s:Application>

Related

How to get all the values of one column and calculate a total

I am making a program where people can create their own food schedule.
I also want to calculate the total amount of calories per food schedule.
So first off people can add items to a list which are saved in an arraycollection:
<s:List includeIn="State2" x="12" y="533" width="428" height="157" dataProvider="{acKoop}"
enabled="true" change="totalcal(event)">
<s:itemRenderer>
<fx:Component>
<mx:Label text="{data.Type} {data.Kcal}" />
</fx:Component>
</s:itemRenderer>
</s:List>
I want a function that retrieves all the values of data.Kcal and then makes a Sum of it.
public function totalcal(event:Event):void{
var price:Number=acKoop[event.columnIndex].Kcal;
total += price;
}
Here the code of link I was send, maybe will be useful:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
[Bindable]
private var acKoop:ArrayCollection = null;
public function init():void{
var arr:ArrayCollection = new ArrayCollection();
var obj:Object = new Object();
obj.Type = "TYPE1";
obj.Kcal = 10;
arr.addItem(obj);
obj = new Object();
obj.Type = "TYPE2";
obj.Kcal = 50;
arr.addItem(obj);
acKoop = arr;
}
public function totalcal(event:Event):void{
var i:Number = 0;
for each(var obj:Object in ArrayCollection(List(event.currentTarget).dataProvider)){
i = i + obj.Kcal;
}
Alert.show("Total of Kcal = " + i.toString());
}
]]>
</fx:Script>
<s:List dataProvider="{acKoop}"
enabled="true" change="totalcal(event)">
<s:itemRenderer>
<fx:Component>
<mx:Label text="{data.Type} {data.Kcal}" />
</fx:Component>
</s:itemRenderer>
</s:List>
</s:Application>
Basically, on the change event I take the dataprovider information from the event, and calculate the TOTAL with the for each loop. I hope this will be useful.

mx:TileList : Why drag doesn't works if allowMultipleSelection is activate

I work with TileList to display image like a gallery.
At start, I activate only drag option.
<mx:TileList xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
columnWidth="120"
rowHeight="150"
paddingLeft="2"
paddingRight="2"
paddingTop="2"
paddingBottom="2"
itemRenderer="fr.ui.display._43Imagerie.TileUnit2"
doubleClickEnabled="true"
dragEnabled="true"
dropEnabled="true"
dragMoveEnabled="true"
verticalScrollPolicy="on"
>
Now I try to add multiple selection possibility.
ItemRenderer is :
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
verticalScrollPolicy="off"
horizontalScrollPolicy="off"
width="120"
height="150"
borderVisible="false"
xmlns:s="library://ns.adobe.com/flex/spark"
creationComplete="onEvent()"
>
<mx:Script>
<![CDATA[
import fr.util.imageTransform;
import mx.controls.Image;
import mx.core.UIComponent;
import mx.events.DragEvent;
import mx.managers.DragManager;
import org.osmf.utils.URL;
import spark.effects.Rotate;
[Bindable]
[Embed(source="icon/imagerie/rotate.png")]
private var rotationArrowClass:Class;
private var _file:File;
private var _selected:Boolean;
private var _sauvBMD:BitmapData;
public var wasScaled:Boolean = false;
public var deleted:Boolean = false;
private var bgCenterX:Number;
private var bgCenterY:Number;
private var _dragDownPt:Point;
[Bindable]
public var angle:int = 0;
private var dragBitmapData : BitmapData;
private function onEvent():void
{
// iconCanvas.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick);
// double click gere ds wPlanchePhoto3
}
private function rotationImage(e:MouseEvent):void
{
var rot:Rotate = new Rotate();
rot.angleBy = 90;
rot.duration = 1000;
rot.autoCenterTransform = true;
rot.target = iconCanvas;
rot.play();
}
private function radiansToDegrees(radians:Number):Number {
var degrees:Number = radians * (180 / Math.PI);
return degrees;
}
private function degreesToRadians(degrees:Number):Number {
var radians:Number = degrees * (Math.PI / 180);
return radians;
}
public function set image(im:BitmapData):void
{
this._sauvBMD=im;
}
public function get image() :BitmapData
{
return this._sauvBMD;
}
protected function iconCanvas_mouseDownHandler(event:MouseEvent):void
{
// on enregistre la point de départ
_dragDownPt = new Point(mouseX,mouseY);
// puis on écoute l'éventuel déplacement de la souris
this.addEventListener(MouseEvent.MOUSE_MOVE,_onMouseMoveDuringDrag);
}
private function _onMouseMoveDuringDrag(evt:MouseEvent):void {
// astuce pour s'assurer que la souris a vraiment bougee volontairement
if(Math.abs(_dragDownPt.x - mouseX) <= 2 && Math.abs(_dragDownPt.y - mouseY) <= 2)
return;
else{
dragBitmapData = new BitmapData(iconCanvas.width, iconCanvas.height,true, 1);
dragBitmapData.draw(iconCanvas);
var transfert:Clipboard = new Clipboard();
transfert.setData(ClipboardFormats.BITMAP_FORMAT,Bitmap(iconCanvas.content).bitmapData);
// only allow the file to be copied
var dragOptions:NativeDragOptions = new NativeDragOptions();
dragOptions.allowMove=false;
dragOptions.allowCopy = true;
dragOptions.allowLink = false;
// begin the drag
NativeDragManager.doDrag(this, transfert, dragBitmapData, null, dragOptions);
}
// dispatch de l'event depuis le parent pour pouvoir écouter cet event dans l'application
}
]]>
</mx:Script>
<s:BorderContainer
id="bcImage"
width="120"
height="99%"
borderVisible="true"
borderColor="#FFFFFF"
borderWeight="1"
cornerRadius="6"
backgroundAlpha=".4"
backgroundColor="#5f5f5f"
>
<mx:Canvas id="cvsImage" width="100%">
<mx:SWFLoader id="rotationArrow" source="{rotationArrowClass}" height="18" width="18" x="3" y="3" visible="true" click="rotationImage(event);" alpha=".5"/>
<s:Label x="23" y="3" width="82" fontSize="11" fontWeight="normal" text="{data.imDate}"
textAlign="right" color="#000000"/>
<mx:Image id="iconCanvas" x="10" y="20" width="99" height="99" horizontalAlign="center"
maintainAspectRatio="true" scaleContent="true"
source="{data.imURL}"
verticalAlign="middle" mouseDown="iconCanvas_mouseDownHandler(event)"
>
</mx:Image>
</mx:Canvas>
<s:VGroup width="100%" y="124" height="25" bottom="1" left="3" right="3" paddingBottom="0" paddingTop="4" gap="0">
<s:Label text="{data.imType}" height="50%" fontSize="10" paddingBottom="1"
fontWeight="normal" width="99%" textAlign="center" color="#000000"/>
<s:Label text="{data.imStade}" fontSize="10" textAlign="center" paddingTop="1"
fontWeight="normal" width="99%" color="#000000"/>
</s:VGroup>
</s:BorderContainer>
If this option is true (allowMultipleSelection), drag stop to work, do you know why?
Thanks for helping.
Adding allowMultipleSelection="true" worked just fine for me. I am running on a Mac with latest version of Flash Player. It seemed a bit flaky at first but after refreshing the page it worked just fine. Only thing I didn't have in my project was your data provider and item renderer. I really doubt your item renderer would cause an issue unless you are doing something crazy in there. Check to see if you have the latest Flash Player.

Show snapshots from camera Flex

I created a flex application that snapshot a picture of the webcam. Im trying now to save every snapshop and display it directly when the image has been capture. But I cant seems to understand how to.
I want the images to be display in the Thumbnail box.
Any help ? or any sites I can found some help on ?
This is what I have for the moment
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="top"
horizontalAlign="center" paddingTop="0" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.core.UIComponent;
private function videoDisplay_creationComplete() : void
{
var camera:Camera = Camera.getCamera();
if (camera)
{
videoDisplay.attachCamera(camera);
}
else
{
Alert.show("Oops, we can't find your camera.");
}
}
private function capture_click() : void
{
var snap:BitmapData = new BitmapData(320, 240, true);
var snapBmp:Bitmap = new Bitmap(snap);
snapBmp.width = 320;
snapBmp.height = 240;
if(snapshotHolder.numChildren > 0)
snapshotHolder.removeChildAt(0);
snapshotHolder.addChild(snapBmp);
snap.draw(videoDisplay);
}
]]>
</mx:Script>
<mx:HBox>
<mx:Panel title="Video">
<mx:VideoDisplay id="videoDisplay" creationComplete="videoDisplay_creationComplete();" width="320" height="240" />
</mx:Panel>
<mx:Panel title="Snapshot">
<mx:UIComponent id="snapshotHolder" width="320" height="240" />
</mx:Panel>
</mx:HBox>
<mx:HBox>
<mx:Button label="reload camera" click="videoDisplay_creationComplete();"/>
<mx:Button label="capture" click="capture_click();"/>
</mx:HBox>
<mx:HBox>
<mx:Panel title="Thumbnails">
<mx:UIComponent id="snapshotHolderTN" width="128" height="96" />
</mx:Panel>
</mx:HBox>
</mx:Application>
Pls try with this when u click for image snaps.
var bmp:BitmapData = new BitmapData(videodisplay.width,videodisplay.height);
bmp.draw(drawArea);
var jpgEncode:JPEGEncoder = new JPEGEncoder(50);
var imageByte:ByteArray = jpgEncode.encode(bmp);
var fileRef:FileReference = new FileReference;
fileRef.save(imageByte);

Flex 3: inquiry about printing

I have created a scheduling application that spans upwards of 16 weeks. I would like to be able to print the schedule using Flex. I've created a test application that lists incrementing dates. These dates obviously stretch longer than the width of my computer. I would like for my print function to print the entire width of dates across several pages... currently, it prints just what appears on my screen. Is there a way to accomplish this?
Below is the app i've created. There are some calls to custom functions, but they in no way relate to the issue at hand:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init();">
<mx:Script source="functions/dateFunctions.as" />
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.collections.ArrayCollection;
[Bindable] public var date:Date = new Date;
public var numDays:Number = 50;
[Bindable] public var datesAC:ArrayCollection = new ArrayCollection;
public function init():void
{
var tempDate:String = new String;
for (var i:int = 0; i < numDays; i++)
{
tempDate = dateToNumText(rightDate(date.getMonth(), date.getDate() + i, date.getFullYear()));
datesAC.addItem(tempDate);
}
}
private function printMe() :void
{
var pj:PrintJob = new PrintJob();
pj.start();
// setTimeout(function() :void { finishPrinting(pj);}, 1);
finishPrinting(pj);
}
private function finishPrinting(pj:PrintJob): void {
pj.addPage(this);
pj.send();
}
]]>
</mx:Script>
<mx:VBox width="100%" height="100%">
<mx:Button id="print" label="Start Print" click="printMe()" />
<mx:HorizontalList id="dateList" dataProvider="{datesAC}" width="100%" height="100%" useRollOver="false">
<mx:itemRenderer>
<mx:Component>
<mx:Canvas borderColor="#000000" borderSides="right" borderStyle="solid">
<mx:Text text="{data}" textAlign="center" color="#000000" width="100" />
</mx:Canvas>
</mx:Component>
</mx:itemRenderer>
</mx:HorizontalList>
</mx:VBox>
</mx:Application>
You would have to break up/paginate content on your own. You can send each such logically broken up page to PrintJob.appPage() API so it becomes a printed paper. At present, what is happening would be that content would be getting clipped.
I guess you should use PrintJob.addPage() to add your dates to print job.

Scroll the datagrid down or up to selected index row flex

I am performing a find operation in a datagrid on one of the columns. After I find the row containing the item, I make that as the selected index row, which highlights it. But now I also want to scroll the datagrid down or up (if the item is out of screen scope) to show that selected item automatically on this find operation.
Thanks.
Have you tried the scrolltoindex() method? Take a look at Anuj Gakhar's article on using scrolltoindex() with a datagrid.
Here's the example from the article:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="doInit();" creationComplete="setSelectedItem()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
// this holds the grid data
[Bindable]
private var myData:ArrayCollection = new ArrayCollection();
// change this name here to change the selected item on load
[Bindable]
private var initialFName:String = "Joe9";
private function doInit():void
{
myData.addItem({fname:"Joe",lname:"Bloggs"});
myData.addItem({fname:"Joe1",lname:"Bloggs"});
myData.addItem({fname:"Joe2",lname:"Bloggs"});
myData.addItem({fname:"Joe3",lname:"Bloggs"});
myData.addItem({fname:"Joe4",lname:"Bloggs"});
myData.addItem({fname:"Joe5",lname:"Bloggs"});
myData.addItem({fname:"Joe6",lname:"Bloggs"});
myData.addItem({fname:"Joe7",lname:"Bloggs"});
myData.addItem({fname:"Joe8",lname:"Bloggs"});
myData.addItem({fname:"Joe9",lname:"Bloggs"});
}
private function setSelectedItem():void
{
var gData:Object = dGrid.dataProvider;
for(var i:Number=0; i < gData.length; i++)
{
var thisObj:Object = gData.getItemAt(i);
if(thisObj.fname == initialFName)
{
dGrid.selectedIndex = i;
//sometimes scrollToIndex doesnt work if validateNow() not done
dGrid.validateNow();
dGrid.scrollToIndex(i);
}
}
}
]]>
</mx:Script>
<mx:DataGrid id="dGrid" dataProvider="{myData}" visible="true">
<mx:columns>
<mx:DataGridColumn dataField="fname" headerText="FirstName" />
<mx:DataGridColumn dataField="lname" headerText="LastName" />
</mx:columns>
</mx:DataGrid>
</mx:Application>