Thursday, June 3, 2010

Flex Actionscript Goodness : Finding and Removing a Object from ArrayCollection(IViewCursor and Sort)

There is always a need to find a particular object or remove it from the ArrayCollection class based on a various member variable conditions.

IViewCursor and Sort classes of mx.collections are a perfect fit for it

Goal: Find employee by empId and remove it

Step1 : Lets Create a ArrayCollection of two Employees

   1: public class EmployeeVo{
   2:     var empNo:String
   3:     var firstName:String
   4:     var lastName:String
   5: }
   6:  
   7: var empVo1:EmployeeVo = new EmployeeVo()
   8: empVo1.empNo=1
   9: empVo1.firstName="john"
  10: empVo1.lastName="tyson"
  11:  
  12: var empVo2:EmployeeVo = new EmployeeVo()
  13: empVo2.empNo=2
  14: empVo2.firstName="ram"
  15: empVo2.lastName="balram"
  16:  
  17: var empCol:ArrayCollection = new ArrayCollection()
  18: empCol.addItem(empVo1)
  19: empCol.addItem(empVo2)
  20:  
  21:  
  22:  
  23:  

Step2 : Sort the employee Vo Class by empId And Find it / Remove it

Note: Sort it needed first in order to use the IViewCursor


   1: import mx.collections.IViewCursor
   2: import mx.collections.Sort
   3: pubic function findAndDeleteEmp(empId:String):void{    
   4:    addSort()
   5:    var cursor:IViewCursor = empCol.createCursor()
   6:    var searchEmpVo:EmployeeVo = new EmployeeVo()
   7:    searchEmpVo.empId = empId
   8:    var isExisting:Boolean = cursor.findAny(searchEmpVo)
   9:    if(isExisting){
  10:        //to get the found object
  11:        var foundEmpVo:EmployeeVo = cursor.currentItem as EmployeeVo
  12:        //to remove the found object
  13:        var deletedObj:EmployeeVo =cursor.remove() as EmployeeVo
  14:    }
  15: }
  16:  
  17: public function addSort():void{
  18:    //Add Sorting to Array Collection
  19:     var fieldName:String = "empId"
  20:     var sortField:SortField = new SortField(fieldName, true,descending);
  21:     var sort:Sort = new Sort();
  22:     sort.fields = new Array(sortField)    
  23:     empCol.sort = sort
  24:     empCol.refresh()
  25: }

Step3: Done!! Hurray!!!

No comments:

Post a Comment