Sunday, January 31, 2010

Setting the current row of a view object with custom key programmatically

I came across a use-case where I needed to set the key of a View Object manually through the backing bean. Usually setCurrentRowWithKey() or setCurrentRowWithKeyValue() can be used to set the current row of a view object. But What if you don't know the exact key but part of it and you want to create the key yourself and set the current Row programmtically.  Well you can use the following function on click of a command button or customize it happily to put to any specific use...

    public String setNewRowKey() {
        // Get the iterator displayed on the Page
         FacesContext ctx = FacesContext.getCurrentInstance();
         Application app = ctx.getApplication();
         ValueBinding bind = app.createValueBinding("#{bindings}");
         DCIteratorBinding iter = ((DCBindingContainer) bind.getValue(ctx)).findIteratorBinding("DepartmentsEmployeeVOIterator");
         if (iter == null) {
           throw new RuntimeException("Iterator not found");
         }
         
         // Create the key manually. It requires providing all primary keys for all 
         // the Entity Objects included in the View Object
         Object [] keyValues = new Object[2];
         keyValues[0] = null;  // Any Department
         keyValues[1] = "114"; // Employee ID
         
         // find all the rows matching the above criteria using the RowSetIterator. 
         // You can also use the same to find rows matching any key criteria.
         Row [] rows = iter.getRowSetIterator().findByKey(new Key(keyValues), -1);
        
         if (rows.length > 0)  {
             // get the first row and its key and set current row of iterator with this key string
             iter.setCurrentRowWithKey(rows[0].getKey().toStringFormat(true));
         }
         
        return "navigation-rule";
    }




No comments:

Post a Comment