List Templates in webOS

List widget has many properties, among which there are
listTemplate [optional]
itemTemplate [required]
emptyTemplate [optional]

listTemplate
In listTemplate file (optional; defines HTML template for list’s container; if omitted, list items are added to scene with no container):

<div style="background-color: #1e1e1e;color:#FFFFFF;height:55px;">
MyList
</div>
<div>
	#{listElements}
</div>

If ListTemplate is been defined, then you need to mention where those items should be populated. where #{listElements} refers to the list items. if #{listElements} not mentioned, then it wont populate the items.

itemTemplate
defines HTML template for list items

<div class="palm-row">
<div id="storyText" class="listText truncating-text">#{data}</div>
</div>

in ListExample-assistant.js

ListExampleAssistant.prototype.setup = function() {
	this.controller.setupWidget("listId",
	  this.attributes = {
	      itemTemplate: "ListExample/myRowTemplate",
	      listTemplate: "ListExample/myListTemplate",
	      swipeToDelete: true,
	  },
	  this.model = {
	      listTitle: "List Title",
	      items : [
	          {data: "Item 1"},
	          {data: "Item 2"},
	          {data: "Item 3"},
	          {data: "Item 4"},
	          {data: "Item 5"},
	      ]
	  }
	);
};
listTemplate 

<div style="background-color: #1e1e1e;color:#FFFFFF;height:55px;">
MyList 
</div>
<div>
#{listElements} 
</div>

itemTemplate

<div class="palm-row" x-mojo-tap-highlight="momentary"> 
<div style="float:left">#{data}</div>
</div> 
listTemplate 

</div> <div class="palm-group">
<div class="palm-group-title">
My List 
</div>
<div class="palm-list">
#{-listElements} 
</div>
</div>

Where palm-group / palm-group-title and palm-list are inbuilt classes

 itemTemplate

<div class="palm-row" x-mojo-tap-highlight="momentary"> 
<div style="float:left">#{data}</div>
</div> 
in scene assistant: 
if listTemplate not mentioned, then the listeitems will be populated
directly into the scene.

		ListExampleAssistant.prototype.setup = function() {
	this.controller.setupWidget("listId",
	  this.attributes = {
	      itemTemplate: "ListExample/myRowTemplate",
	      swipeToDelete: true,
	  },
	  this.model = {
	      listTitle: "List Title",
	      items : [
	          {data: "Item 1"},
	          {data: "Item 2"},
	          {data: "Item 3"},
	          {data: "Item 4"},
	          {data: "Item 5"},
	      ]
	  }
	); 	
};

		

itemTemplate

<div class="palm-row" x-mojo-tap-highlight="momentary"> 
<div style="float:left">#{data}</div>
</div>	

Database to list in WebOS

This tutorial shows how to insert record into SQL Storage(HTML5) and Populate the rows in List widget.

Refer to List Widget

Step1 : Create Basic Scene “DatabaseList”

in DatabaseList-Scene.html

<div>Database Tutorial</div>

<div id="textField"></div>
<div id="button-1"></div>
<div id="listId" class="listClass"></div>

Step2 : Create one html file for List Widget
in myRowTemplate.html

<div class="palm-row">
<div style="float: left;">#{data}</div>
&nbsp;

</div>

Step 3: DatabaseList-assistant.js Creating a new table named”ofive_table” with two columns ID – Autoincrement Column Title – Text column

DatabaseListAssistant.prototype.setup = function() {
var name = "MainDB";  // required
var version = "1";  // required

var db = openDatabase(name, version);

if (!db) {
  Mojo.Log.error("Could not open database");
} else {

  db.transaction(
  	function (transaction)
  	{
	    transaction.executeSql("CREATE TABLE IF NOT EXISTS Ofive_Table(id integer primary key autoincrement, Title TEXT)",[],
    		function(transaction, results)
    	       {Mojo.Log.info("Successfully created table")},
               function(transaction, error)
               {Mojo.Log.error("Could not create table: ")});
  });
}
this.controller.setupWidget('button-1',{},{buttonLabel: 'Insert'});
this.controller.setupWidget('textField',{},{original : 'initial value'});
Mojo.Event.listen(this.controller.get('button-1'),Mojo.Event.tap, this.InsertRow)
var attributes = {
             itemTemplate: 'DatabaseList/myRowTemplate',
             swipeToDelete: true,
         }
this.controller.setupWidget('listId', attributes);  
};

Step 4: Include the following function which performs

Reference for Queries
– Inserting a new record into the Table (ofive_Table)
– Retrieve all records from the table and Populate into the List widget

DatabaseListAssistant.prototype.InsertRow=function(event){
var db = openDatabase("MainDB", "1"); // this is all that is required to open an existing DB

db.transaction( function (transaction) {
  transaction.executeSql("INSERT INTO Ofive_Table(Title) VALUES (?)",  [$('textField').innerText],
      function(transaction, results) {    // success handler
      Mojo.Log.info("Successfully inserted record");
      },
      function(transaction, error) {      // error handler
       Mojo.Log.error("Could not insert record: " + error.message);
      }
  );
  transaction.executeSql("SELECT * FROM Ofive_Table",  [],
                         function(transaction, results) {    // success handler
			  var Ar1=[]
                          for(i=0;i<results.rows.length;i++)
			  {
			  Ar1.push({data: results.rows.item(i).Title})
			  }
			 $("listId").mojo.noticeUpdatedItems(0, Ar1);
                         },
                         function(transaction, error) {      // error handler
                           Mojo.Log.error("Could not insert record: " + error.message);
                         }
  );
})	

}

Output

Storage Database in webOS

HTML5 storage Database is generally referred as SQLlite. It is to handle minimal database and Query.

Please refer Basic App Creation in PALM

Step1 :Create Basic Scene “Database”

in Database-Scene.html

<div>Database Tutorial</div>

<div id="textField"></div> <!-- Open field for user to enter values -->
<div id="button-1"></div> <!-- Insert Button, to tigger insert query -->
<div id="button-2"></div> <!-- Retrieve Records from the table -->
<div id="Records"></div> <!-- Display Records -->

Step2 : In Database-Assistant.js

DatabaseAssistant.prototype.setup = function() {
var name = "MainDB";  // required
var version = "1";  // required

var db = openDatabase(name, version); // Open Database
if (!db) {
  Mojo.Log.error("Could not open database"); // If Database is not available , it throws an error message
} else {
  var sql = "CREATE TABLE IF NOT EXISTS 'Table1' (Title TEXT)";
  db.transaction(
  	function (transaction)
  	{
    transaction.executeSql(sql,[], function(transaction, results)
    							   {Mojo.Log.info("Successfully created table")},
    							   function(transaction, error)
    							   {Mojo.Log.error("Could not create table: ")});
  });
}
this.controller.setupWidget('button-1',{},{buttonLabel: 'Insert'}); //Giving the button label as Insert
this.controller.setupWidget('button-2',{},{buttonLabel: 'Retrieve Data'}); // To give the button label as Retrieve
this.controller.setupWidget('textField');
Mojo.Event.listen(this.controller.get('button-1'),Mojo.Event.tap, this.InsertRow) //One Tab of Insert Button, function InsertRow will be called
Mojo.Event.listen(this.controller.get('button-2'),Mojo.Event.tap, this.RetrieveRows) // on Tab of Retrieve Button, function Retrieve Rows will be called
};

Step 3: Include functions below
1. To Insert Row into Table

DatabaseAssistant.prototype.InsertRow = function(event) {
var test = $('textField').innerText;

var db = openDatabase("MainDB", "1"); // this is all that is required to open an existing DB
var sql = "INSERT INTO 'Table1' (Title) VALUES (?)";

db.transaction( function (transaction) {
  transaction.executeSql(sql,  [test],
                         function(transaction, results) {    // success handler
                           Mojo.Log.info("Successfully inserted record");
                         },
                         function(transaction, error) {      // error handler
                           Mojo.Log.error("Could not insert record: " + error.message);
                         }
  );
})
};

2. To Retrieve Rows from table

DatabaseAssistant.prototype.RetrieveRows = function(event) {
var db = openDatabase("MainDB", "1");
var sql = "SELECT * FROM 'Table1'";

db.transaction(function(transaction) {
  transaction.executeSql(sql, [],
                         function(transaction, results) {
                           // results.rows holds the rows returned by the query
                           $("Records").innerHTML=""
                           for(i=0;i<results.rows.length;i++)
                           $("Records").innerHTML += results.rows.item(i).Title +"
"
                         },
                         function(transaction, error) {
                           Mojo.Log.error("Could not read: " + error.message);
                         });
});
};

Important Notes

db.transaction(
function(transaction) {
  transaction.executeSql(sql, [],
                         function(transaction, results) {
                          // this function is a success handler, if the query executed properly, this function will be called
                         },
                         function(transaction, error) {
                         // This function is a failure handler, if any error executing the query.
                         });
});

We can have multiple transaction of queries like below

db.transaction(InsertQuery,[values],SuccessHandler(transaction,results), FailureHandler(transaction,error))
db.transaction(SelectQuery,[],SuccessHandler(transaction,results), FailureHandler(transaction,error))

Output

Dynamic List in webOS

Refer Palm App :Basic App for Creating a basic App

The list is the most common component. In Webos, list objects are rendered into
the provided HTML templates.

Two HTML templates are necessary to render the list objects. listTemplate and
itemTemplate

List has many attributes to define among which

1. listTemplate – declaration to refer listTemplate

2. itemTemplate – declaration to refer itemTemplate

3. emptyTemplate – declaration to refer is values are empty

Step1 : Create a basic scene “List”

List-Scene.html

List Declaration

<div x-mojo-element=”List” id=”listId” name=”listName”></div>

Step 2: Defining the List itemTemplate, create a new HTML file in the same folder
of List named “myRowTemplate”. This template name to be referenced in “itemTemplate”
attribute property.

myRowTemplate.html

<div class=”palm-row” x-mojo-tap-highlight=”momentary”>
//x-mojo-tab-highlight to highlight the list item when the user taps,
palm-row is an inbuilt class.#{data} // is the Object Name from the declaration</div>


Create a folder named “Data” and paste test.xml

Test.XML

<l>
  <citem>
    <id>1</id>
    <userId>UserID1</userId>
    <pwd>adsdasdasd</pwd>
  </citem>
  <citem>
    <id>2</id>
    <userId>UserID2</userId>
    <pwd>adsdasdasd</pwd>
  </citem>
  <citem>
    <id>3</id>
    <userId>UserID3</userId>
    <pwd>adsdasdasd</pwd>
  </citem>
  <citem>
    <id>4</id>
    <userId>UserID4</userId>
    <pwd>adsdasdasd</pwd>
  </citem>
  <citem>
    <id>6</id>
    <userId>UserID5</userId>
    <pwd>adsdasdasd</pwd>
  </citem>
  <citem>
    <id>7</id>
    <userId>UserID6</userId>
    <pwd/>
  </citem>
  <citem>
    <id>8</id>
    <userId>UserID7</userId>
    <pwd></pwd>
  </citem>
</l>

List Widget Declaration
There are two ways to set the List Widget Properties, here i am not assigning any data items to list as we are going to populate dynamically from XML file.

one Way

ListAssistant.prototype.setup = function() {

this.controller.setupWidget(“listId”,

this.attributes = {

itemTemplate: ‘List/myRowTemplate’,

swipeToDelete: true,

});

};

 

Alternate Way

ListAssistant.prototype.setup = function() {

var attributes = {
             itemTemplate: 'List/myRowTemplate',
             swipeToDelete: true,
         }
this.controller.setupWidget('listId', attributes);
};

 

Final code will look like below with loading XML.
Step 3: In scene assistant

 

ListAssistant.prototype.setup = function() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=handler
xmlhttp.open("GET","Data/test.xml");
xmlhttp.send();

var attributes = {
             itemTemplate: 'List/myRowTemplate',
             swipeToDelete: true,
         }
this.controller.setupWidget('listId', attributes);
};

 

Step 4: Add below function

function handler()
{	
	if(this.readyState == 4 && (this.status == 200 || this.status == 304))
    {
		  if(this.responseXML != null)
		  {
		  xmlDoc=this.responseXML.getElementsByTagName("userId")
		  var Ar1=[]
		  for(i=0;i<xmlDoc.length;i++)
		  {
		  Ar1.push({data: xmlDoc[i].firstChild.nodeValue})
		  }
		  $("listId").mojo.noticeUpdatedItems(0, Ar1); 
		  }
	} 
	else if(this.readyState == 4)
	{
	alert("Error Reading List")
	}
};


listWidget.mojo.noticeUpdatedItems(offset, items)
, where:

Argument Type Description
offset Integer Index in the list of the first object in ‘items’; usually the same as ‘offset’ passed to the itemsCallback
items Array An array of the list item model objects that have been loaded for the list

Notes

$("listId").mojo.noticeUpdatedItems(0, Ar1);  //$ is quite equivalent 
to document.getElementById in Ajax way. noticeUpdatedItems is the property of 
list to populate list with an array.


OutPut

List Widget in webOS

Refer Palm App :Basic App for Creating a basic App

The list is the most common component. In Webos, list objects are rendered into
the provided HTML templates.

Two HTML templates are necessary to render the list objects. listTemplate and
itemTemplate

List has many attributes to define among which

1. listTemplate – declaration to refer listTemplate

2. itemTemplate – declaration to refer itemTemplate

3. emptyTemplate – declaration to refer is values are empty

Step1 : Create a basic scene “List”

List-Scene.html

List Declaration

<div x-mojo-element=”List” id=”listId” class=”listClass” name=”listName”></div>

Step 2: Defining the List itemTemplate, create a new HTML file in the same folder
of List named “myRowTemplate”. This template name to be referenced in “itemTemplate”
attribute property.

myRowTemplate.html

<div class=”palm-row” x-mojo-tap-highlight=”momentary”>
//x-mojo-tab-highlight to highlight the list item when the user taps,
palm-row is an inbuilt class.#{data} // is the Object Name from the declaration

</div>

Step 3: In scene assistant:

ListAssistant.prototype.setup = function() {

this.controller.setupWidget(“listId”,

this.attributes = {

itemTemplate: ‘List/myRowTemplate’,

swipeToDelete: true,

},

this.model = {

listTitle: ‘Servers’,

items : [

{data:”Value1″},

{data:”Value2″},

]

});

};

OutPut

Modifying myRowTemplate a little bit

<div class=”palm-row” x-mojo-tap-highlight=”momentary”>
<div style=”float:left”><img src=”images/RightArrow.png” /></div><div
style=”float:left”>#{data}</div>
</div>

Output 2

 

 

Load XML in webOS

Read XML in webOS

Refer Palm App :Basic App for Creating a basic App

Step1 : Create a folder named “Data” and paste test.xml

Test.XML

<l>
<citem>
<id>1</id>
<userId>rrrtttt1111117779999999999999</userId>
<pwd>adsdasdasd</pwd>
</citem>
<citem>
<id>2</id>
<userId>111111aaa</userId>
<pwd>adsdasdasd</pwd>
</citem>
<citem>
<id>3</id>
<userId>333333333</userId>
<pwd>adsdasdasd</pwd>
</citem>
<citem>
<id>4</id>
<userId>33333333311111111</userId>
<pwd>adsdasdasd</pwd>
</citem>
<citem>
<id>5</id>
<userId>Laaaaa222222</userId>
<pwd>adsdasdasd</pwd>
</citem>
<citem>
<id>6</id>
<userId>11111111qqqqq333333333</userId>
<pwd>adsdasdasd</pwd>
</citem>
<citem>
<id>7</id>
<userId>456</userId>
<pwd/>
</citem>
<citem>
<id>8</id>
<userId>tyrrr</userId>
<pwd></pwd>
</citem>
</l>

Step 2: In Scene1-scene.html , Include another <div> tag to load the XML data

<div id=”XMLData”></div>

Entire Code of Scene1-scene.html will look like below

<div id=”main” class=”palm-hasheader”>

<div class=”palm-header”>Header</div>

<div id=”count” class=”palm-body-text”>Hello World</div>

<div id=”XMLData”></div>

</div>

Step 3: Scene1-scene.html corresponding javascript file is
Scene1.assistant.js. Whatever javascript related to this scene can go in to this
javascript

Each javascript file has four events (Setup / Activate /cleanUp /deactivate)
related to the scene

1. Scene1-assistant.js

2. Edit the setup function to contain the following:

Scene1Assistant.prototype.setup = function() {

xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=handler

xmlhttp.open(“GET”,”Data/test.xml”);

xmlhttp.send();

};

3. Add the following funtion

function handler()
{
if(this.readyState == 4 && (this.status == 200 || this.status == 304))
{
if(this.responseXML != null)
{
xmlDoc=this.responseXML
document.getElementById(“XMLData”).innerText=this.responseText  //It loads the XML content and writes into the DIV tag with ID XMLData}
}
}

Output

Chart out of SharePoint data without Stacked

Step 1: Create a sharepoint list with the following data in it.

Step 2: Below code creates the bar chart

<?xml version=”1.0″ encoding=”utf-8″?><mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”absolute” creationComplete=”onCreate(event)”><mx:Script><![CDATA[

import mx.charts.series.*;
import mx.controls.Alert;
import mx.collections.ArrayCollection;
import mx.binding.utils.BindingUtils;
import mx.charts.*;
import mx.core.UIComponent;

private var MainXMLList:XMLList;
private var Project:Array =new Array();
private var Status:Array =new Array();
private var BU:Array =new Array();
private var MainXML:URLLoader;

[Bindable]
public var HoldStatus:ArrayCollection=new ArrayCollection();

private function onCreate(e:Event):void
{
MainXML=new URLLoader(new URLRequest(“http://teams4.sharepoint.hp.com/teams/ProjSpace/_vti_bin/owssvr.dll?Cmd=Display&List={56FD41DB-4D68-43EF-AF9F-3A76CBC0A8CC}&XMLDATA=TRUE”))
MainXML.addEventListener(Event.COMPLETE,MainXMLL)
}

private function MainXMLL(e:Event):void
{
var myXML:XML = XML(e.target.data);
var XMLL:XMLList=new XMLList(e.target.data)
var rsNS:Namespace = XMLL.namespace(“rs”);
var zNS:Namespace = XMLL.namespace(“z”);
var sNS:Namespace = XMLL.namespace(“s”);
MainXMLList=new XMLList(XMLL.rsNS::data.zNS::row)
HoldStatus.source=[]
for(var i:int=0;i<MainXMLList.length();i++)
{
BU.push(MainXMLList[i].attribute(“ows_Project_x0020_BU”))
Status.push(MainXMLList[i].attribute(“ows_Status”))
}
BU=removeDuplicates(BU)
Status=removeDuplicates(Status)
for(var b:int=0;b<BU.length;b++)
{
HoldStatus.source.push({Dummy:”April”})  // Just pushing dummy value to create an empty index
HoldStatus[b][“Title”]=BU[b]  // Creating a Title Idenfier in Arraycollection which stores BU1 and BU2
for(var s:int=0;s<Status.length;s++)
HoldStatus[b][Status[s]]=MainXMLList.(attribute(“ows_Project_x0020_BU”)== BU[b] && attribute(“ows_Status”) == Status[s] ).length()  //If Project BU =”BU1″ and Status =”Pipleline” Takes the count.
}

var myChart:BarChart = new BarChart(); // Create barchart dynamically
myChart.dataProvider = HoldStatus; //Assigning the HoldStatus (Arraycollection as a dataprovider for BarChart

// Setting up the Vertical Axis
var vAxis:CategoryAxis = new CategoryAxis();
vAxis.categoryField = “Title”;
myChart.verticalAxis = vAxis;
var hh:LinearAxis=new LinearAxis()
hh.interval=1
myChart.horizontalAxis=hh

 //Creating barseries (Pipeline, Closed, Complete) where Status array

holds “Pipeline, Closed and Complete”
for(var c:int=0;c<Status.length;c++)
{
var BS:BarSeries = new BarSeries();
BS.xField = Status[c];
BS.displayName = Status[c];
myChart.series.push(BS) //Pushes all bar series into Chart
}

myChart.percentWidth=95;
myChart.percentHeight=80;
var l:Legend = new Legend();
l.dataProvider = myChart;
l.direction=”horizontal”
l.percentWidth=95;
l.percentHeight=20;

myPanel.addChild(myChart);
myPanel.addChild(l);
}
private function removeDuplicates(arr:Array):Array  // This function retrieves the unique values from the Array
{
var currentValue:String = “”;
var tempArray:Array = new Array();
arr.sort(Array.CASEINSENSITIVE);
arr.forEach(
function(item:*, index:uint, array:Array):void {
if (currentValue != item) {
tempArray.push(item);
currentValue= item;
}
}
);

return tempArray;

}

]]>

</mx:Script>

<mx:Panel id=”myPanel” width=”300″ height=”300″>

</mx:Panel>

</mx:Application>

 

 

This will collect all BU Values and Status
for(var i:int=0;i<MainXMLList.length();i++)
{
BU.push(MainXMLList[i].attribute(“ows_Project_x0020_BU”))
Status.push(MainXMLList[i].attribute(“ows_Status”))
}Below code retrieves unique values and stores back into the same
array variable
BU=removeDuplicates(BU)Status=removeDuplicates(Status)Below code construct a loop for BUs and inner loop for status to
get the count of projects

for(var b:int=0;b<BU.length;b++)
{
HoldStatus.source.push({Dummy:”April”})
HoldStatus[b][“Title”]=BU[b]
for(var s:int=0;s<Status.length;s++)
HoldStatus[b][Status[s]]=MainXMLList.(attribute(“ows_Project_x0020_BU”)== BU[b] && attribute(“ows_Status”) == Status[s] ).length()
}

This will create an array collection like below 

{Title :BU1 , Pipeline: 2, Closed: 2}
{Title :BU2 , Pipeline: 1, Closed: 2}

Output

Chart out of SharePoint data

Step 1: Create a sharepoint list with the following data in it.

Step 2: Below code creates the bar chart

<?xml version=”1.0″ encoding=”utf-8″?><mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”absolute” creationComplete=”onCreate(event)”>

<mx:Script>

<![CDATA[

import mx.charts.series.*;
import mx.controls.Alert;
import mx.collections.ArrayCollection;
import mx.binding.utils.BindingUtils;
import mx.charts.*;
import mx.core.UIComponent;

private var MainXMLList:XMLList;
private var Project:Array =new Array();
private var Status:Array =new Array();
private var BU:Array =new Array();
private var MainXML:URLLoader;

[Bindable]
public var HoldStatus:ArrayCollection=new ArrayCollection();

private function onCreate(e:Event):void
{
MainXML=new URLLoader(new URLRequest(“http://teams4.sharepoint.hp.com/teams/ProjSpace/_vti_bin/owssvr.dll?Cmd=Display&List={56FD41DB-4D68-43EF-AF9F-3A76CBC0A8CC}&XMLDATA=TRUE”))
MainXML.addEventListener(Event.COMPLETE,MainXMLL)
}

private function MainXMLL(e:Event):void
{
var myXML:XML = XML(e.target.data);
var XMLL:XMLList=new XMLList(e.target.data)
var rsNS:Namespace = XMLL.namespace(“rs”);
var zNS:Namespace = XMLL.namespace(“z”);
var sNS:Namespace = XMLL.namespace(“s”);
MainXMLList=new XMLList(XMLL.rsNS::data.zNS::row)
HoldStatus.source=[]
for(var i:int=0;i<MainXMLList.length();i++)
{
BU.push(MainXMLList[i].attribute(“ows_Project_x0020_BU”))
Status.push(MainXMLList[i].attribute(“ows_Status”))
}
BU=removeDuplicates(BU)
Status=removeDuplicates(Status)
for(var b:int=0;b<BU.length;b++)
{
HoldStatus.source.push({Dummy:”April”})  // Just pushing dummy value to create an empty index
HoldStatus[b][“Title”]=BU[b]  // Creating a Title Idenfier in Arraycollection which stores BU1 and BU2
for(var s:int=0;s<Status.length;s++)
HoldStatus[b][Status[s]]=MainXMLList.(attribute(“ows_Project_x0020_BU”)== BU[b] && attribute(“ows_Status”) == Status[s] ).length()  //If Project BU =”BU1″ and Status =”Pipleline” Takes the count.
}

var myChart:BarChart = new BarChart(); // Create barchart dynamically
myChart.dataProvider = HoldStatus; //Assigning the HoldStatus (Arraycollection as a dataprovider for BarChart

// Setting up the Vertical Axis
var vAxis:CategoryAxis = new CategoryAxis();
vAxis.categoryField = “Title”;
myChart.verticalAxis = vAxis;
var hh:LinearAxis=new LinearAxis()
hh.interval=1
myChart.horizontalAxis=hh

 // Setting up the chart type as stacked bar
var innerSet:BarSet = new BarSet();
innerSet.type = “stacked”;

 //Creating barseries (Pipeline, Closed, Complete) where Status array
holds “Pipeline, Closed and Complete”
for(var c:int=0;c<Status.length;c++)
{
var BS:BarSeries = new BarSeries();
BS.xField = Status[c];
BS.displayName = Status[c];
innerSet.series.push(BS) // innerSet is the barSet where all Bar Series
into the InnerSet, It groups the series into stacked show
}

myChart.series=[innerSet] // Assigning the Barset to the chart
myChart.percentWidth=95;
myChart.percentHeight=80;
var l:Legend = new Legend();
l.dataProvider = myChart;
l.direction=”horizontal”
l.percentWidth=95;
l.percentHeight=20;

myPanel.addChild(myChart);
myPanel.addChild(l);
}
private function removeDuplicates(arr:Array):Array  // This function retrieves the unique values from the Array
{
var currentValue:String = “”;
var tempArray:Array = new Array();
arr.sort(Array.CASEINSENSITIVE);
arr.forEach(
function(item:*, index:uint, array:Array):void {
if (currentValue != item) {
tempArray.push(item);
currentValue= item;
}
}
);

return tempArray;

}

]]>

</mx:Script>

<mx:Panel id=”myPanel” width=”300″ height=”300″>

</mx:Panel>

</mx:Application>

This will collect all BU Values and Status
for(var i:int=0;i<MainXMLList.length();i++)
{
BU.push(MainXMLList[i].attribute(“ows_Project_x0020_BU”))
Status.push(MainXMLList[i].attribute(“ows_Status”))
}Below code retrieves unique values and stores back into the same
array variable
BU=removeDuplicates(BU)

Status=removeDuplicates(Status)

Below code construct a loop for BUs and inner loop for status to
get the count of projects

for(var b:int=0;b<BU.length;b++)
{
HoldStatus.source.push({Dummy:”April”})
HoldStatus[b][“Title”]=BU[b]
for(var s:int=0;s<Status.length;s++)
HoldStatus[b][Status[s]]=MainXMLList.(attribute(“ows_Project_x0020_BU”)== BU[b] && attribute(“ows_Status”) == Status[s] ).length()
}

This will create an array collection like below 

{Title :BU1 , Pipeline: 2, Closed: 2}
{Title :BU2 , Pipeline: 1, Closed: 2}

 

Output

Advanced Datagrid from SharePoint data

Step 1: Create a sharepoint list with the following data in it.

Step 2: Retrieving custom list data as XML in flex. In order to create the
advanced datagrid with grouping (Column grouping lets you collect multiple
columns under a single column heading)

<?xml version=”1.0″ encoding=”utf-8″?><mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”absolute” initialize=”initializeHandler();” ><mx:Script>
<![CDATA[
import mx.controls.Alert
import mx.controls.dataGridClasses.DataGridColumn
import mx.collections.*;
private var FinalXML:XMLList
[Bindable]
private var dpFlat:ArrayCollection=new ArrayCollection();
private function initializeHandler():void
{
var XMLLoader:URLLoader=
new URLLoader(new URLRequest(“<sharepointLini>/_vti_bin/owssvr.dll?Cmd=Display&List=%7BA6FFA525%2D0AC1%2D411E%2DA1F4%2D687402312595%7D&XMLDATA=TRUE”))
XMLLoader.addEventListener(Event.COMPLETE,openXMLValues)
function openXMLValues(e:Event):void
{
var XMLL:XML=new XML(e.target.data)
var rsNS:Namespace = XMLL.namespace(“rs”);
var zNS:Namespace = XMLL.namespace(“z”);
var sNS:Namespace = XMLL.namespace(“s”);
FinalXML=new XMLList(XMLL.rsNS::data.zNS::row)
var Obj:Object
for(var i:int=0;i<FinalXML.length();i++)
{
var attNames:XMLList = FinalXML[0].attributes();
Obj=new Object();
for (var i:int=0; i<attNames.length(); i++)
{
Obj[attNames[i].name().toString()]=attNames[i]
}
dpFlat.addItem(Obj)
}
}

}

]]>
</mx:Script>

<mx:Panel title=”AdvancedDataGrid Control Example”
height=”300″ width=”400″ layout=”horizontal”
paddingTop=”10″ paddingBottom=”10″ paddingLeft=”10″ paddingRight=”10″>

<mx:AdvancedDataGrid id=”myADG”>

<mx:dataProvider>
<mx:GroupingCollection2 id=”gc” source=”{dpFlat}”>
<mx:grouping>
<mx:Grouping>
<mx:GroupingField name=”ows_LinkTitle”/>
<mx:GroupingField name=”ows_Category2″/>
</mx:Grouping>
</mx:grouping>
</mx:GroupingCollection2>
</mx:dataProvider>

<mx:columns>
<mx:AdvancedDataGridColumn dataField=”ows_LinkTitle” headerText=”Category1″/>
<mx:AdvancedDataGridColumn dataField=”ows_Category2″ headerText=”Category2″/>
<mx:AdvancedDataGridColumn dataField=”ows_Value” headerText=”Value”/>
</mx:columns>
</mx:AdvancedDataGrid>
</mx:Panel>
</mx:Application>

Notes: XMLList values should be converted to ArrayCollection. ArrayCollection
will hold Objects. Grouping in advanced datagrid cannot be XMLList without
having a hierarchial data.

If XML value is like Below
<item value=”server”>
<citem value=”Integrity” >
<sitem value=”580i” />
<sitem value=”670i” />
</citem>
</item>

It can be treated as Hierarchical data and can be set as datasource to advanced
Datagrid. In this case, Group is very simple.

But Sharepoint gives the XML structure as

<z:row ows_Attachments=”0″ ows_LinkTitle=”Server” ows_Category2=”ProLiant”ows_Value=”580i” />
<z:row ows_Attachments=”0″ ows_LinkTitle=”Server” ows_Category2=”ProLiant”ows_Value=”670i”/>
<z:row ows_Attachments=”0″ ows_LinkTitle=”Server” ows_Category2=”Integrity”ows_Value=”580i”/>
<z:row ows_Attachments=”0″ ows_LinkTitle=”Server” ows_Category2=”Integrity”ows_Value=”780i2″/>
 
So this needs to be converted to either hierarchical XML structure or Array Collection like below dynamically

DP:   var ArrayCollection=new ArrayCollection(
{ows_Attachments:”0″, ows_LinkTitle:”Server”,ows_Category2:”ProLiant”, ows_Value:”580i”}
{ows_Attachments:”0″, ows_LinkTitle:”Server”,ows_Category2:”ProLiant”, ows_Value:”670i”}
{ows_Attachments:”0″, ows_LinkTitle:”Server”,ows_Category2:”Integrity”, ows_Value:”580i”}
{ows_Attachments:”0″, ows_LinkTitle:”Server”,ows_Category2:”Integrity”, ows_Value:”780i”}
)
for(var i:int=0;i<FinalXML.length();i++)
{
var attNames:XMLList = FinalXML[0].attributes(); // It retrieves all attributes from the xml node
Obj=new Object();
for (var i:int=0; i<attNames.length(); i++)  // Loop through attributes and create object with identifier name as attribute
{
Obj[attNames[i].name().toString()]=attNames[i]  // Creating identifier in object and assign the attribute values from xml.
}
dpFlat.addItem(Obj)  // add Object into the ArrayCollection (sample ows_Attachments:”0″, ows_LinkTitle:”Server”, ows_Category2:”ProLiant”, ows_Value:”580i” )

Output