TableView Sort

Hello,
I've the below code in my RENDER_CELL_START method and I do see the radio buttons properly on my tableview. The problem is that when I sort the tableview the radio selection is messed up totally. Sometimes more than 1 selection is changed and sometime it changes the selection by itself. I am doinf sort="server" and my tableview is binded to my model class (MVC).
Any help would be appreciated.
Thanks.
      WHEN 'DEFSEVERITY'.
        create object rad_gp.
        rbg = cl_htmlb_radiobuttongroup=>factory( id = p_cell_id columncount = '4' ).
        rad_gp->add( element = rbg level = 1 ).
        if c_item_row_ref2->defseverity = 'A'.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '1' key = 'A' text = 'A' checked = 'X' ).
        else.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '1' key = 'A' text = 'A' ).
        endif.
        rad_gp->add( element = rb level = 2 ).
        if c_item_row_ref2->defseverity = 'B'.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '2' key = 'B' text = 'B' checked = 'X' ).
        else.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '2' key = 'B' text = 'B' ).
        endif.
        rad_gp->add( element = rb level = 2 ).
        if c_item_row_ref2->defseverity = 'C'.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '3' key = 'C' text = 'C' checked = 'X' ).
        else.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '3' key = 'C' text = 'C' ).
        endif.
        rad_gp->add( element = rb level = 2 ).
        if c_item_row_ref2->defseverity = 'N'.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '4' key = 'N' text = 'None' checked = 'X' ).
        else.
           rb ?= cl_htmlb_radiobutton=>factory( id = p_cell_id id_postfix = '4' key = 'N' text = 'None' ).
        endif.
        rad_gp->add( element = rb level = 2 ).
        p_replacement_bee ?= rad_gp.
      ENDCASE.

Thanks Ravi,
I've seen the thread posted by Raja before. Since my tableview is binded (MVC) it is sorting correctly. Only problem is, after sort, the radio button selections are not showing up properly. For example, more than one button is checked in a group. It appears that the radiobutton group information is getting lost somewhere.
One question - Since render_cell_start fires at every server event - it should mark the selections properly after sorting, correct?
If I remove my radio button and display the data itself in the column (like A, B, C) it shows up fine and then there is no problem in sorting as well.
Do I need to create an OSS note for this one?
I really need this feature implemented.
Thanks,
Partho

Similar Messages

  • TableView : sort = "SERVER" ...does not work for "TIME"

    Hi,
    TableView sort = "Server" works automatically for "Date" Fields and "Text" Fields.
    But it does not work for "Time" field with data element "CDUZEIT". It shows the below error message:
    Note
    The following error text was processed in the system IFD : Invalid sort field type in "SORT ... AS TEXT".
    The error occurred on the application server ifdmain_IFD_01 and in the work process 0 .
    The termination type was: RABAX_STATE
    The ABAP call stack was:
    Form: IF_HTMLB_ELEMENT_DELEGATED~DO_AT_END of program CL_HTMLB_TABLEVIEW============CP
    Form: DELEGATED_END of program CL_HTMLB_ELEMENT==============CP
    Form: IF_BSP_ELEMENT~DO_AT_END of program CL_HTMLB_TABLEVIEW============CP
    Form: ONLAYOUT of program CLO27OLHO7EA9KVWPONPDC2NLTDFHCP
    Form: %_ONLAYOUT of program CL_O27OLHO7EA9KVWPONPDC2NLTDFHCP
    Form: DO_REQUEST of program CL_BSP_PAGE===================CP
    Form: CALL_VIEW of program CL_BSP_PAGE_BASE==============CP
    Form: CALL_VIEW of program CL_BSP_CONTROLLER=============CP
    Form: DO_REQUEST of program ZCL_ZPR_C_ACTION_LOG==========CP
    Form: DO_REQUEST of program CL_BSP_CTRL_ADAPTER===========CP
    Thanks and Regards,
    Bindiya

    Welcome to SDN.
    This problem and solution to it is exaplined in the following oss note number.
    <a href="https://service.sap.com/~form/handler?_APP=01100107900000000342&_EVENT=REDIR&_NNUM=893210&_NLANG=E">893210</a>
    Regards
    Raja

  • TableView: sort="server" with iterator-generated cell content

    I have an htmlb:tableView that uses an iterator and sort ="SERVER".
    In one of the columns, I change the text that is displayed a little bit in RENDER_CELL_START of the iterator.
      DATA lr_text  TYPE REF TO cl_htmlb_textview.
      FIELD-SYMBOLS <fs_row>  LIKE LINE OF me->t_bla.
      ASSIGN p_row_data_ref->* TO <fs_row>.
      CASE p_column_key.
        WHEN 'MY_FIELDNAME'.
          CREATE OBJECT lr_text.
          lr_text->id     = p_cell_id.
          lr_text->text   = me->get_name( <fs_row>-id ).
          p_replacement_bee = lr_text.
    Now, if I click on the sort icon of the column, the table is sorted by the field 'MY_FIELDNAME', but not by the actual content of the column.
    How would I achieve that?

    this sounds almost possible.
    I cannot write the new value into the original field of the table though, because I cannot be sure that the datatypes fit to each other and because I stil need the original values.
    But I could of course add some more fields to the table structure (which I would not like so much), loop at the table before I use it in the tableView and write the new values into these fields.
    Then, I wouldn't even need RENDER_CELL_START at all.

  • JSP TableView Sorting Problem

    I have been trying to get a tableview to be sortable by clicking on the header of columns.  I have been reviewing existing threads on the forum in particular the one below.
    https://forums.sdn.sap.com/thread.jspa?threadID=16417
    I seem to understand the concept but for some reason my table does not sort, it just does nothing.  Could someone take a look and see if you can find any problems - I can't wait to give points.
    Here is all my code.
    Here is the Java....
    package MSSPackage;
    import MSSBeanPackage.PositionOverviewBean;
    import MSSPackage.SortTableModel;
    import com.sapportals.htmlb.page.DynPage;
    import com.sapportals.htmlb.page.PageException;
    import com.sapportals.portal.htmlb.page.JSPDynPage;
    import com.sapportals.portal.htmlb.page.PageProcessorComponent;
    import com.sapportals.portal.prt.component.IPortalComponentContext;
    import com.sapportals.portal.prt.component.IPortalComponentProfile;
    import com.sapportals.portal.prt.component.IPortalComponentRequest;
    import com.sapportals.portal.prt.component.IPortalComponentSession;
    import com.sapportals.htmlb.event.*;
    import com.sapportals.htmlb.*;
    import com.sapportals.htmlb.table.*;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    import javax.servlet.http.*;
    // SAP RFC Imports
    import com.sap.mw.jco.IFunctionTemplate;
    import com.sap.mw.jco.JCO;
    import com.sapportals.portal.prt.service.jco.IJCOClientPoolEntry;
    import com.sapportals.portal.prt.service.jco.IJCOClientService;
    import com.sapportals.portal.prt.runtime.PortalRuntime;
    import java.util.*;
    public class PositionOverview extends PageProcessorComponent {
      public DynPage getPage(){
         return new PositionOverviewDynPage();
      public static class PositionOverviewDynPage extends JSPDynPage{
         JCO.Repository mRepository;
         public JCO.Table tblRelations;
         public JCO.Table tblPositions;     
         public SortTableModel tableModel;
         public int visibleRow = 1;     
         private boolean OrgUnitSelected = false;
         public void doInitialization(){
              IPortalComponentSession oSession = ((IPortalComponentRequest)getRequest()).getComponentSession();
              PositionOverviewBean oBean = new PositionOverviewBean();
              // Table Start row
              oBean.setvisibleRow(new Integer(this.visibleRow).toString());          
              oSession.putValue("myBean", oBean);
              // Define request, context and profile containers         
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
              IPortalComponentContext myContext = request.getComponentContext();
              IPortalComponentProfile myProfile = myContext.getProfile();
              // Define bean reference to bean
              PositionOverviewBean myBean = new PositionOverviewBean();
              // Table Start row
              myBean.setvisibleRow(new Integer(this.visibleRow).toString());
              // Place bean in user profile.          
              myProfile.putValue("myBean", myBean);
         public void doProcessAfterInput() throws PageException {
         public void doProcessBeforeOutput() throws PageException {
              String NavType = "RCORGUNIT";
              String OType = "O";
              //String OBjid = "10004399";
              String OBjid = "";
              String sapSystem = "SAP_R3_HumanResources";          
              IPortalComponentSession oSession = ((IPortalComponentRequest)getRequest()).getComponentSession();
              PositionOverviewBean myBean = (PositionOverviewBean) oSession.getValue("myBean");
              // Define request, context and profile containers         
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
    /*          IPortalComponentContext myContext = request.getComponentContext();
              IPortalComponentProfile myProfile = myContext.getProfile();
              //HttpSession session = request.getServletRequest().getSession();          //dmm
              //Get Bean from Profile
              PositionOverviewBean myBean = (PositionOverviewBean) myProfile.getValue("myBean");
              //PositionOverviewBean myDataBean = (PositionOverviewBean) session.getValue("POviewBean");               //dmm
              String ddlbSelection = "";
              String ddlbValue = "";
              DropdownListBox ddlbOrgUnits = (DropdownListBox) getComponentByName("ddlbOrgUnits");
              if (ddlbOrgUnits != null)
                   ddlbSelection = ddlbOrgUnits.getSelection();
                   ddlbValue = ddlbOrgUnits.getValueAsDataType().getValueAsString();
                   OBjid = ddlbValue;
                   myBean.setObjId(OBjid);
              else
                   OBjid = "";
                   myBean.setObjId(OBjid);                 
              IJCOClientService clientService;
              IJCOClientPoolEntry poolEntry;          
              JCO.Client client;          
              try
                   clientService = (IJCOClientService) PortalRuntime.getRuntimeResources().getService(IJCOClientService.KEY);
                   poolEntry = clientService.getJCOClientPoolEntry(sapSystem, request);
                   client = poolEntry.getJCOClient();
                // connect to SAP system, logon
                   client.connect();
                // Create Jco Repository Object
                   mRepository = new JCO.Repository("R3USERMENU", client);
                // Reset function object
                   JCO.Function function = null;
                // Run RFC Module on SAP system
                   function = this.createFunction("HRWPC_GET_NAV_OBJECTS");
                   JCO.ParameterList input = function.getImportParameterList();
                   input.setValue("RCORGUNIT", "NAVTYPE");               
                   client.execute(function);
                   tblRelations = function.getTableParameterList().getTable("RESULT_OBJEC");
                   myBean.setRowcnt(tblRelations.getNumRows());
                   if (tblRelations.getNumRows() != 0)               
                        myBean.setOrgUnits(tblRelations);
                        if (ddlbOrgUnits == null)
                             // check to see if there is not a position id already assigned
                             tblRelations.setRow(0);
                             OBjid = tblRelations.getString("OBJID");
                             myBean.setObjId(OBjid);
                             //myBean.sTemp = OBjid;                         
                   // GET THE POSITION DETAILS
                   function = null;
                   input = null;
                   function = this.createFunction("Z_GET_POSITION_OVERVIEW");
                   input = function.getImportParameterList();               
                   input.setValue(NavType, "NAVTYPE");               
                   input.setValue(OType, "OTYPE");
                   input.setValue(OBjid, "OBJID");               
                   client.execute(function);
                   tblPositions = function.getTableParameterList().getTable("RESULT_OBJEC");
                   myBean.setRowcnt(tblPositions.getNumRows());
                   tableViewFormat();
                   tableModel.setTesting("Startxxxx");
                   myBean.settableModel(tableModel);
                   //tableModel.setTesting("SSSS");               
                   //myDataBean.settableModel(tableModel);                                             //dmm               
                   //session.setAttribute("POviewBean", myDataBean);                                //dmm
                   oSession.putValue("myBean", myBean);
              //Release pool entry
              poolEntry.release();                           
           catch(Exception ex)
                //name = ex.getMessage();                         
           //String sTest = "this is a test";      
           //request.getComponentSession().putValue("Test", sTest);
           //myProfile.putValue("Testx", sTest);
           this.setJspName("PositionOverviewJSP.jsp");
         public void getPositions()
              String NavType;
              String Root_Ot;
              String Root_ObjId;
         public void tableViewFormat()
              // Define the vectors used to build tableView
              Vector tempRec = new Vector();
              Vector dataRec = new Vector();
              String sDate = "";
              String sPosLink = "";
              String sPosVal = "";
              String sENameLink = "";
              String sENameVal = "";
              String sStatus = "";
              // Loop at company code list and add to vectors
              for (int i = 0; i < tblPositions.getNumRows(); i++)
                   tblPositions.setRow(i);
                   tempRec = new Vector();
                   sStatus = (String) tblPositions.getString("STATUS");
                   if (sStatus != null)
                        if (sStatus.equals("0"))                    
                             sDate = tblPositions.getString("ZHR_VACANT_BEGDA");
                             sDate = sDate.substring(5, 7) + "/" + sDate.substring(8, 10) + "/" +  sDate.substring(0, 4);                         
                        else
                             sDate = "";                    
                   sPosVal = tblPositions.getString("STEXT");
                   sENameVal = tblPositions.getString("ENAME");
                   if (sPosVal.equals(""))
                        sPosLink = sPosVal;
                   else
                        sPosLink = "<a HREF="myLink" onclick="return EPCM.doNavigate('ROLES://portal_content/com.sap.portal.migrated/ep_5.0/pages/com.sap.pct.hcm.positionprofile?CKey=000000" + tblPositions.getString("OBJID") + "', 1)">" + tblPositions.getString("STEXT") + "</a>";
                   if (sENameVal.equals(""))
                        sENameLink = sENameVal;
                   else
                        sENameLink = "<a HREF="myLink" onclick="return EPCM.doNavigate('ROLES://portal_content/com.phi/com.phi.mgt/com.phi.mss/com.phi.hr/com.phi.pages/com.phi.mgt.mss.hr.pages.positionholder?CKey=000000" + tblPositions.getString("OBJID") + "', 1)">" + tblPositions.getString("ENAME") + "</a>";
                   tempRec.addElement(sStatus);
                   tempRec.addElement(tblPositions.getString("OBJID"));
                   tempRec.addElement(sPosLink);
                   tempRec.addElement(sENameLink);
                   tempRec.addElement(sDate);               
                   dataRec.addElement(tempRec);
              // Then define the technical column names
              Vector colNames = new Vector();
              colNames.addElement("STATUS");
              colNames.addElement("OBJID");
              colNames.addElement("STEXT");     
              colNames.addElement("ENAME");
              colNames.addElement("ZHR_VACANT_BEGDA");
              // Now we build the actual tableView
              //tableModel = new DefaultTableViewModel(dataRec, colNames);
              tableModel = new SortTableModel(dataRec, colNames, 5);     
              // Define tableView parameters
              tableModel.setKeyColumn(2);
              TableColumn column = tableModel.getColumn("STATUS");
              column.setEncode(false);
              column.setType(com.sapportals.htmlb.enum.TableColumnType.USER);
              column.setTitle("Vacant");
              column = tableModel.getColumn("OBJID");
              column.setTitle("Position Number");
              column = tableModel.getColumn("STEXT");
              column.setTitle("Position");
              column = tableModel.getColumn("ENAME");
              column.setTitle("Holder of Position");          
              column = tableModel.getColumn("ZHR_VACANT_BEGDA");
              column.setTitle("Vacant as of");
         //     * Navigation Button Clicked
         public void myOnNavigate(Event event)
              TableNavigationEvent tne = (TableNavigationEvent) event;
              visibleRow = tne.getFirstVisibleRowAfter();
              // Define request, context and profile containers         
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
              IPortalComponentContext myContext = request.getComponentContext();
              IPortalComponentProfile myProfile = myContext.getProfile();
              // Get Bean from profile
              PositionOverviewBean myBean = (PositionOverviewBean) myProfile.getValue("myBean");
              // Table Start row
              myBean.setvisibleRow(new Integer(this.visibleRow).toString());
         public void onHeaderClick(Event event)
              IPortalComponentSession oSession = ((IPortalComponentRequest)getRequest()).getComponentSession();
              PositionOverviewBean myBean = (PositionOverviewBean) oSession.getValue("myBean");
              TableHeaderClickEvent tne = (TableHeaderClickEvent) event; // get the event
              SortTableModel tblModel = myBean.gettableModel();
              //tblModel.sort();
              int col = 3;
              tblModel.sortByColumn(col);
              myBean.settableModel(tblModel);
              oSession.putValue("myBean", myBean);
         // Create Function object for RFC Calls
         public JCO.Function createFunction(String name) throws Exception
              try
                   IFunctionTemplate ft = mRepository.getFunctionTemplate(name.toUpperCase());
                   if (ft == null)
                        return null;
                   return ft.getFunction();
              catch (Exception ex)
                   ex.printStackTrace();
                   throw new Exception("Problem retrieving JCO.Function object");
         public void onSelectddlbOrgUnits(Event event) throws PageException
              OrgUnitSelected = true;          
    Here is the JSP
    <%@ page import="com.sap.mw.jco.*" %>
    <%@ page import="com.sapportals.htmlb.enum.*" %>
    <%@ page import="MSSPackage.TableViewCellRenderer" %>
    <%@ page import="com.sapportals.portal.prt.component.IPortalComponentRequest" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page import="com.sapportals.portal.prt.component.IPortalComponentContext" %>
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <hbj:content id="myContext" >
         <hbj:page title="PageTitle">
              <hbj:form id="myFormId" >  
              <jsp:useBean id="myBean" scope="session" class="MSSBeanPackage.PositionOverviewBean" />     
                   <hbj:gridLayout rowSize="1" columnSize="1" cellSpacing="1">
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="1">
                             <hbj:textView id="ddlbLable" text="Select organizational unit to display positions" design="STANDARD" />
                        </hbj:gridLayoutCell>                         
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="2">
                             <hbj:dropdownListBox id="ddlbOrgUnits" onSelect="onSelectddlbOrgUnits" selection="<%=myBean.getObjId()%>">                                                       
                                  <%                         
                                       JCO.Table org_units = null;                                                       
                                       org_units = myBean.getOrgUnits();
                                       for (int i = 0; i < org_units.getNumRows(); i++)
                                            org_units.setRow(i);
                                            String sUnit = org_units.getString("STEXT");
                                            String Unit_Id = org_units.getString("OBJID");
                                  %>
                                  <hbj:listBoxItem key="<%=Unit_Id%>" value="<%=sUnit%>" />
                                  <%
                                  %>
                             </hbj:dropdownListBox>                                                                                                   
                        </hbj:gridLayoutCell>
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="3">
                             <hbj:textView id="listLable" text="To designate a vacant position, click the icon in the 'Create Form' column" design="STANDARD" />                    
                        </hbj:gridLayoutCell>                    
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="4">     
                             <hbj:tableView
                                  id="myTableView"
                                  headerVisible="true"
                                  footerVisible="true"
                                  fillUpEmptyRows="true"
                                  selectionMode="NONE"                              
                                  navigationMode="BYPAGE"
                                  onNavigate="myOnNavigate"                                        
                                  visibleFirstRow="<%= myBean.getvisibleRow() %>"                                                  
                                  visibleRowCount="5" >                                                            
                                  <%
                                  myTableView.setOnHeaderClick("onHeaderClick");
                                  myTableView.setUserTypeCellRenderer(new TableViewCellRenderer());                                                             
                                  myTableView.setModel(myBean.gettableModel());
                                  myTableView.setColumnType(TableColumnType.LINK, 3);
                                  myTableView.setColumnType(TableColumnType.LINK, 4);                              
                                  %>
                             </hbj:tableView>
                        </hbj:gridLayoutCell>                                        
                   </hbj:gridLayout>   
              </hbj:form>
         </hbj:page>
    </hbj:content>
    Here is the BEAN
    package MSSBeanPackage;
    //import com.sapportals.htmlb.enum.TableColumnType;
    import MSSPackage.SortTableModel;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    //import com.sapportals.htmlb.table.TableColumn;
    //import com.sapportals.htmlb.table.TableView;
    //import com.sapportals.htmlb.table.TableViewModel;
    import com.sap.mw.jco.JCO;
    import com.sap.mw.jco.JCO.Table;
    public class PositionOverviewBean {
    //     public DefaultTableViewModel tableModel;
         public SortTableModel tableModel;
         public JCO.Table OrgUnits;
         public String ObjId;
         public String visibleRow;
         public int rowcnt;
         public String sTemp;
         // Get and Set methods for table model
    //     public DefaultTableViewModel gettableModel() { return tableModel; }
    //     public void settableModel(DefaultTableViewModel tableModel)     { this.tableModel = tableModel;     }
         public SortTableModel gettableModel() { return tableModel; }
         public void settableModel(SortTableModel IntableModel)     { this.tableModel = IntableModel;     }     
         public JCO.Table getOrgUnits()     { return OrgUnits; }
         public void setOrgUnits(JCO.Table value) { this.OrgUnits = value; }
         // Get and Set methods for visiblerow
         public String getvisibleRow() {     return visibleRow; }
         public void setvisibleRow(String visibleRow) { this.visibleRow = visibleRow; }     
         public int getRowcnt() { return this.rowcnt; }
         public void setRowcnt(int rowcnt) { this.rowcnt = rowcnt; }
         public String getObjId() { return this.ObjId; }
         public void setObjId(String value) { this.ObjId = value; }     
    Here is the sorting class
    package MSSPackage;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Vector;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    public class SortTableModel extends DefaultTableViewModel implements Comparator {
         //protected int currCol;
         public int currCol;
         protected Vector ascendCol; // this vector stores the state (ascending or descending) of each column
         protected Integer one = new Integer(1);
         protected Integer minusOne = new Integer(-1);
         public String testing;
         public SortTableModel()
              super();
              ascendCol = new Vector();
         public SortTableModel(Vector vec)
              super(vec);
              ascendCol = new Vector();
         public SortTableModel(Vector vec, Vector vec2, int numberOfColumns)
              super(vec, vec2);
              ascendCol = new Vector();
              setSortOrder(numberOfColumns);
         public int compare (Object v1, Object v2)
              // the comparison is between 2 vectors, each representing a row
              // the comparison is done between 2 objects from the different rows that are in the column that is being sorted
              int ascending = ((Integer)ascendCol.get(currCol)).intValue();
              if (v1 == null && v2 == null)
                   return 0;
              else if (v2 == null)
              { // Define null less than everything.
                   return 1 * ascending;
              else if (v1 == null)
                   return -1 * ascending;
              Object o1 = ((Vector)v1).get(currCol);
              Object o2 = ((Vector)v2).get(currCol);
              // If both values are null, return 0.
              if (o1 == null && o2 == null)
                   return 0;
              else if (o2 == null)
              { // Define null less than everything.
                   return 1 * ascending;
              else if (o1 == null)
                   return -1 * ascending;
              if (o1 instanceof Number && o2 instanceof Number)
                   Number n1 = (Number)o1;
                   double d1 = n1.doubleValue();
                   Number n2 = (Number)o2;
                   double d2 = n2.doubleValue();
                   if (d1 == d2)
                        return 0;
                   else if (d1 > d2)
                        return 1 * ascending;
                   else {
                        return -1 * ascending;
              else if (o1 instanceof Boolean && o2 instanceof Boolean)
                   Boolean bool1 = (Boolean)o1;
                   boolean b1 = bool1.booleanValue();
                   Boolean bool2 = (Boolean)o2;
                   boolean b2 = bool2.booleanValue();
                   if (b1 == b2)
                        return 0;
                   else if (b1)
                        return 1 * ascending;
                   else
                        return -1 * ascending;
              else
                   // default case
                   if (o1 instanceof Comparable && o2 instanceof Comparable)
                        Comparable c1 = (Comparable)o1;
                        Comparable c2 = (Comparable)o2; // superflous cast, no need for it!
                        try
                             return c1.compareTo(c2) * ascending;
                        catch (ClassCastException cce)
                        // forget it... we'll deal with them like 2 normal objects below.
                   String s1 = o1.toString();
                   String s2 = o2.toString();
                   return s1.compareTo(s2) * ascending;
         * This method sorts the rows using Java's Collections class.
         * After sorting, it changes the state of the column -
         * if the column was ascending, its new state is descending, and vice versa.
         public void sort()
              Collections.sort(dataVector, this);          
              //Collections.sort(dataVector);
              Integer val = (Integer)ascendCol.get(currCol);
              ascendCol.remove(currCol);
              if (val.equals(one)) // change the state of the column
                   ascendCol.add(currCol, minusOne);
              else
                   ascendCol.add(currCol, one);
         public void sortByColumn(int column)
              this.currCol = column;
              sort();
         public void setSortOrder(int numberOfColumns)
              for (int i = 0; i < numberOfColumns; i++)
                   ascendCol.add(one);
         public void setTesting(String inStr)
              testing = inStr;
    Any help would be greatly apprciated and rewarded...

    Hi Don,
    be aware that after the method onHeaderClick(Event event) is executed the method doProcessBeforeOutput() is executed as well.
    I look over your code and found the following:
    1) In method onHeaderClick you sort the table model and store the table model in the bean
    2) In method doProcessBeforeOutput() you create a new table model from scratch (in helper method tableViewFormat())and store it in the bean. Thus you overwrite the sorted model.
    I suggest that you move the initial creation of the table model in method doInitialization(). Do not forget to store the created table in the bean. In method doProcessBeforeOutput() you retrieve the table model from the bean instead of creating a new one for every request.
    Best regards,
    Martin

  • Bug or feature: TableView sorts the underlying list?

    that's at least highly unexpected - all variants of table sorting I know, support some kind of sortedView on top of the user model (either by a framework outside of the table, as GlazedList, or internal as core swing).
    Is it a not-yet-done feature or yet another variant of leaving the hard stuff to the user dev?
    CU
    Jeanette

    JonathanGiles wrote:
    This is by-design. We consider the items list in the TableView to be the view model - clicking on a column results in the view model being sorted.
    There are ways around this. If you provide a TransformationList (e.g. SortedList) wrapped around an ObservableList, the TableView will sort the SortedList, leaving the underlying ObservableList unsorted and still available via SortedList.getDirectSource() or getBottomMostSource() (depending on how many layers of wrapping you have).that's exactly what I keep complaining about:
    - framework handles the trivial stuff: it simply pushes a comparator into a sortable list is or lets collections.sort do the work
    - developers are left with the harder parts like index mapping
    Actually, the framework is hit by those missing harder parts as well:
    - SortedList freaks out on mutable elements, basically because the internal index mapping is not optimal (http://javafx-jira.kenai.com/browse/RT-14965)
    - Selection synch is broken when sorting/filtering (and TableView taking the extreme easy way out in clearing ... tseee), don't have a report handy, but know that you are aware of the issue : - )
    - no way to "unsort" a TableColumn (http://javafx-jira.kenai.com/browse/RT-15166) in the general case. Even for a SortedList, that would involve to restore the original comparator (instead of leaving the TableColumnComparator in place)
    Cheers
    Jeanette

  • TableView Sorting issues

    Hi,
    Just a short question about sorting.  In one of our tables, there are entries for a column that have names starting With and without capital letters.  Now, is there a way to force the sort to not care whether or not the first word is Capitalized or not?
    Thanks and best regards,
    Kevin

    Hi Kevin,
    follow for example more or less the code given in this thread: Functionality to dynamically sort tableview columns and implement a <i>compare</i> method corresponding to your needs (for example using <i>compareToIgnoreCase</i> method of <i>String</i>).
    Hope it helps
    Detlev

  • HTMLB TableView Sort .

    Hello,
    Can some one tell me how I can sort a Tableview and how the code should be implemented.
    Appreciate all the help.
    Thanks & Regards,
    Emmanuel.

    Hi,
    I am implementing the code but I am facing an exceptio:
    Caused by: java.lang.NoClassDefFoundError: com/sapportals/htmlb/table/DefaultTableViewModel
    Loader Info -
    ClassLoader name: [com.sapportals.portal.prt.util.ApplicationClassLoader@24b0c5]
    Parent loader name: [com.sapportals.portal.prt.util.ApplicationClassLoader@bc0da8]
    References:
       not registered!
    Can some one suggest why ?

  • TableView Sorting

    Hi,
    When I get data from R/3 backend. Does the TableView have any methods to sort this data.
    Has anyone sorted data after retrieving data from backend based on a column.
    Any advice will be appreciated.
    NAC

    Thank you for your answer and sorry if the question was not clear. Let me clarify it through an example. Let's say I have a table with 4 rows, containing data in the first 3 rows, and the 4th row is a total row, that sums up whatever is in the first 3 rows. I want to be able to sort the rows but keep the 4th row where it is.
    Example:
    Table before sorting:
    Header: [Category,Value]
    Row 1: [Cat1,5]
    Row 2: [Cat2,15]
    Row 3: [Cat3,10]
    Row 4: [Total,30]
    Table after sorting column "Value" in ascending order:
    Header: [Category,Value]
    Row 1: [Cat1,5]
    Row 2: [Cat3,10]
    Row 3: [Cat2,15]
    Row 4: [Total,30]
    Table after sorting column "Value" in descending order:
    Header: [Category,Value]
    Row 3: [Cat2,15]
    Row 2: [Cat3,10]
    Row 1: [Cat1,5]
    Row 4: [Total,30]
    Note how the last row (Total) has NOT been affected by the sorting operation.

  • Tableview sorting from database

    Hi guys,
    I created a TableView that reads data through Hibernate from Mysql. I'd like to order the data in the table (by clicking the column's name) with the order by clause in the db and not programatically with Comapable of String or something similar.
    How I can manage this situation?
    Thanks very much

    Hi guys,
    anyone has some suggestion?
    Thanks

  • Sort a tableview column containing a date

    This is my second request to find more info on handling dates javafx2, no replies to the first so am trying again.
    I am a relative "newby" to java, FX2 has so many compelling features I really want to use it.
    Displaying and sorting on dates seems like such a fundamental requirement that I am surprised that I can't find any examples anywhere on handing dates in a tableview.
    This would be so easy to do in Cocoa with the "date formatter" so apologies if I am missing something obvious.
    If I use a formatted date the column sorts on the text not on the actual date.
    eg. starting with
    06/01/2012
    08/01/2011
    07/01/2012
    sorting ascending gives
    06/01/2012
    07/01/2012
    08/01/2011
    and descending
    08/01/2011
    07/01/2012
    06/01/2012
    both wrong!
    Same issue if I use a calendar in the cells.
    Hope the answer is not to have a separate column for day, month and year.

    Hi wornish,
    TableView sort can be customized as per our needs. A sample example of Date is given here:
    Currently Let's suppose that you are displaying data of "Date" in String form using SimpleDateFormat class.
    TableView<Date> view = new TableView<Date>();
    TableColumn<Date,String> col = new TableColumn<Date,String>("Date");
    col.setComparator(new Comparator<String>(){
         @Override
         public int compare(String t, String t1) {
            try{
              SimpleDateFormat format =new SimpleDateFormat("MM-dd-YYYY");
              Date d1 =format.parse(t);               
              Date d2 = format.parse(t1);
              return Long.compare(d1.getTime(),d2.getTime());
            }catch(ParseException p){
                 p.printStackTrace();
            return -1;
    col.setCellValueFactory(new Callback<CellDataFeatures<Date, String>, ObservableValue<String>>() {
         @Override
         public ObservableValue<String> call(CellDataFeatures<Date, String> param) {
              SimpleDateFormat format = new SimpleDateFormat("MM-dd-YYYY");
              return new SimpleObjectProperty(format.format(param.getValue()));
            Thanks
    Narayan

  • Table View: How to modify the sort in DO_REQUEST or DO_HANDLE_DATA or ..EVE

    Hi ,
    In my DO_REQUEST i tried to modify the tableview sort...but its not getting triggered....
                    UPDATE SORTING
      DATA: lv_id                            TYPE string.
      DATA: lr_table_view                    TYPE REF TO cl_htmlb_tableview.
      DATA: lr_tbl_view_event                TYPE REF TO cl_htmlb_event_tableview.
      lv_id = me->get_element_id( 'tp' ).
      lr_table_view ?= cl_htmlb_manager=>get_data( request = request
                                                   name    = 'tableview'
                                                   id      = lv_id ).
      IF lr_table_view IS BOUND.
        lr_tbl_view_event                ?= lr_table_view->data.
        lr_tbl_view_event->column_key     = mr_model_assign_sb_list->mv_column_key.
        lr_tbl_view_event->sortcolumntype = mr_model_assign_sb_list->mv_sortcolumntype.
      ENDIF.
    Thanks and Regards,
    Bindiya

    Hi,
    The easiest way to modify the screens in the Std transactions using ITS is to modify the ITS templates corresponding to that transaction.
    E.g In you case,there will be a ITS service corresponding to the ESS transaction.This ITS service will have  number of HTML templates which will actually correspond to the diffrent screens in the Trascn.What you need to do is find out the HTML template in the ITS service which corresponds to the screen(which you want to modify) in the STd transacn.To do this ,the easiest way is to right click on that Web page and say VIEW SOURCE.It will show you a HTML code with the ITS service name and the template which is being used for that particular screen.
    So after you find out the correct HTML template to be modified,you can simply hide the fields by putting the HTML code lines in between the symbols
      <!   and  -->
    BR,
    Disha.
    <b>Pls reward points for useful answers.</b>

  • TableView: Filter as Dropdown

    Hi @all
    Has someone experiences with rendering the filter-row in an TableView? I get the access to the "data-rows" and i am able to render them, but how to get access to the filter row and create a "dropdown-Filter".
    I want to create a functionality which is know from Excel: Autofilter!
    Thank you for helping on this
    Thorsten

    As promised, here is my example (using MVC):
    In DO_REQUEST, I call a model method to create my filter table, because the content in my table is changing all the time, I need my filter to be up to date as well.
    Example: LASTNAME as column name for the filter
    data: lt_filter      type tableviewfiltertab,
          lv_last_insert type string,
    * here go your table and table structure definitions
    * lt_tvdata type ...
    * ls_tvdata type ...
    field-symbols: <filter> like line of lt_filter,
                   <wa>     type ihttpnvp2.
      append initial line to lt_filter assigning <filter>.
      <filter>-columnname = 'LASTNAME'.
    * define a pre-selection
      <filter>-selection  = '*'.
    * append filter lines:
    * first a joker character
      append initial line to <filter>-dropdownlistbox_table assigning <wa>.
      <wa>-name  = '*'.
      <wa>-value = '*'.
    * ... and now the tableview table entries
    * lt_tvdata is a copy of the table for the tableview
    * sort table
      sort lt_tvdata ascending by 'LASTNAME'.
    * now do the loop ...
      clear lv_last_insert.
      loop at lt_tvdata into ls_tvdata.
    *   if not in filter already ...
        if lv_last_insert is initial or lv_last_insert ne ls_tvdata-lastname.
    *     then append the value
          append initial line to <filter>-dropdownlistbox_table assigning <wa>.
          <wa>-value  = ls_tvdata-lastname.
          <wa>-name   = ls_tvdata-lastname.
    *     set last insert
          lv_last_insert = ls_tvdata-lastname.
        endif.
      endloop.
      sort <filter>-dropdownlistbox_table by value.
    This should do for a quick example, all left to do is use the filter in your tableview:
    <htmlb:tableview
      id = ".....
      columnFilters = "<%= model->filter %>" />
    * filter table as model attribute in this case
    Well, I should turn this topic into a weblog, as I got another (slightly different) dropdown in my filter ...
    Hope you get your part going with this example for a start.
    Max

  • Property performance issues cpu 40%

    All
    We are using a tableView with maybe 10+ SimpleIntegerProperty or SimpleStringProperty fields on our object to update values on the table. When we push data into the table we are seeing the CPU at 40%. When profiling the application all of the issues seem to point to the Simple*Property objects. Is there a way to update the TableView without using these property objects so we can compare performance?

    I haven't ever come across performance problems like you describe with so few items. There are some issues with really large tables, which I think have been addressed in the latest version (ea b96) of JavaFX 8 (or perhaps in the next snapshot release): see JavaFx tableview sort is really slow how to improve sort speed as in java swing - Stack Overflow for example. (In a nutshell, the PropertyValueFactory is really inefficient if you only provide a getXXX() method and no xXXProperty() method in your data representation.)
    Can you post a simple example that reproduces the issue?

  • TableView - How to update a running balance column after any other column in the view is re-sorted

    To keep this simple and to illustrate a problem that I am trying to solve let's say we have
    a domain class that contains an income per day.
    This class has two persistent properties - populated from a database table - date and income.
    And there is one transient property - running balance - that shows the accumulated income
    starting from the first record. This property is not persisted and it is used only to show
    the running/accumulated income in a table view.
    This domain object is shown in a table view with three columns:
         - date
         - income
         - running balance
    The first two columns - date and income - are sortable. When the user clicks on the column
    heading these can will be sorted in ascending or descending order. The running balance
    column needs to reflect this change and be correctly updated.
    So the question is : how would you implement the running balance update after the data in
    the table has been updated by the user?
    Take 1)
    =============
    The obvious approach is to use "setOnSort" method to consume the SortEvent event and re-sort the
    data but the sort-event does not contain any useful information that would tell from which column
    the sort event originated.
    Take 2)
    =============
    Found a possible solution:
         - TableView.getSortOrder() returns a list that defines the order in which TableColumn instances are sorted after the user clicked one or more column headings.
         - TableColumn.getSortType() returns the sort type - ascending/descending.
         - This info can be used in the TableView.setOnSort() event handler to re-sort the data and update the balance at the same time.
    Take 3)
    =============
    When the TableView.setOnSort() event handler is called the data is already sorted therefore the only thing that needs to be done is to update the running balance.

    I  think I understand what you're trying to do. If I've missed it, apologies, but I think this will provide you with something you can work from anyway.
    I would listen to the data instead of watching specifically for sorting. This will be much more robust if you add new functionality later (such as adding and removing rows, editing the data that's there, etc).
    Specifically, for the runningBalance column, create a cellValueFactory that provides a DoubleBinding; this binding should listen for changes to the data and compute the value by running through the table's items up to the point of the item for which it's displaying the value. (Hope you can untangle that sentence.)
    Example. The important part is the cellValueFactory for the cumulativeAmountCol. I guess I should mention that you shouldn't try this exact approach with very large tables as the performance might be pretty bad (computations of the order of n x m on changing data, where n is the number of rows in the table and m is the number of visible rows in the table).
    import java.text.DateFormat;
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random;
    import javafx.application.Application;
    import javafx.beans.Observable;
    import javafx.beans.binding.DoubleBinding;
    import javafx.beans.property.DoubleProperty;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleDoubleProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.scene.Scene;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class CumulativeTableColumnExample extends Application {
      private final static int NUM_ITEMS = 20 ;
    @Override
      public void start(Stage primaryStage) {
      final TableView<LineItem> table = new TableView<>();
      // using the extractor here makes sure the table item list fires a list changed event if any amounts change
      // this enables the cumulative amount column to keep up to date when the amount in a different row changes.
      table.setItems(FXCollections.observableList(createRandomData(), new Callback<LineItem, Observable[]>() {
          @Override
          public Observable[] call(LineItem item) {
            return new Observable[] {item.amountProperty()};
      final TableColumn<LineItem, Date> dateCol = new TableColumn<>("Date");
      final TableColumn<LineItem, Number> amountCol = new TableColumn<>("Amount");
      final TableColumn<LineItem, Number> cumulativeAmountCol = new TableColumn<>("Cumulative Amount");
      table.getColumns().addAll(Arrays.asList(dateCol, amountCol, cumulativeAmountCol));
      dateCol.setCellValueFactory(new PropertyValueFactory<LineItem, Date>("date"));
        amountCol.setCellValueFactory(new PropertyValueFactory<LineItem, Number>("amount"));
        cumulativeAmountCol.setCellValueFactory(new PropertyValueFactory<LineItem, Number>("amount"));
        cumulativeAmountCol.setSortable(false); // otherwise bad things might happen
      final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
      dateCol.setCellFactory(new Callback<TableColumn<LineItem, Date>, TableCell<LineItem, Date>>() {
          @Override
          public TableCell<LineItem, Date> call(TableColumn<LineItem, Date> col) {
            return new TableCell<LineItem, Date>() {
              @Override
              public void updateItem(Date date, boolean empty) {
                super.updateItem(date, empty);
                if (empty) {
                  setText(null);
                } else {
                  setText(dateFormat.format(date));
      cumulativeAmountCol.setCellValueFactory(new Callback<CellDataFeatures<LineItem, Number>, ObservableValue<Number>> () {
          @Override
          public ObservableValue<Number> call(CellDataFeatures<LineItem, Number> cellData) {
            final LineItem currentItem = cellData.getValue() ;
            DoubleBinding value = new DoubleBinding() {
                super.bind(table.getItems());
              @Override
              protected double computeValue() {
                double total = 0 ;
                LineItem item = null ;
                for (Iterator<LineItem> iterator = table.getItems().iterator(); iterator.hasNext() && item != currentItem; ) {
                  item = iterator.next() ;
                  total = total + item.getAmount() ;
                return total ;
            return value;
        final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
      // generics hell.. can't wait for lambdas...
      final Callback<TableColumn<LineItem, Number>, TableCell<LineItem, Number>> currencyCellFactory = new Callback<TableColumn<LineItem, Number>, TableCell<LineItem, Number>>() {
          @Override
          public TableCell<LineItem, Number> call(TableColumn<LineItem, Number> column) {
            return new TableCell<LineItem, Number>() {
              @Override
              public void updateItem(Number amount, boolean empty) {
                if (empty) {
                  setText(null) ;
                } else {
                  setText(currencyFormat.format(amount));
        amountCol.setCellFactory(currencyCellFactory);
        cumulativeAmountCol.setCellFactory(currencyCellFactory);
        BorderPane root = new BorderPane();
      root.setCenter(table);
      primaryStage.setScene(new Scene(root, 600, 400));
      primaryStage.show();
      public List<LineItem> createRandomData() {
        Random rng = new Random();
        List<LineItem> items = new ArrayList<>();
        for (int i=0; i<NUM_ITEMS; i++) {
          Calendar cal = Calendar.getInstance();
          cal.add(Calendar.DAY_OF_YEAR, rng.nextInt(365)-365);
          double amount = (rng.nextInt(90000)+10000)/100.0 ;
          items.add(new LineItem(cal.getTime(), amount));
        return items ;
      public static void main(String[] args) {
      launch(args);
    public static class LineItem {
        private final ObjectProperty<Date> date ;
        private final DoubleProperty amount ;
        public LineItem(Date date, double amount) {
          this.date = new SimpleObjectProperty<>(this, "date", date);
          this.amount = new SimpleDoubleProperty(this, "amount", amount);
        public final ObjectProperty<Date> dateProperty() {
          return date;
        public final Date getDate() {
          return date.get();
        public final void setDate(Date date) {
          this.date.set(date);
        public final DoubleProperty amountProperty() {
          return amount ;
        public final double getAmount() {
          return amount.get();
        public final void setAmount(double amount) {
          this.amount.set(amount);

  • How to enforce always sorting on a column in a TableView?

    Hello,
    I have a requirement to always sort on a column in a TableView.
    So basically, I need a TableColumn's SortType go from Ascending to Descending and back to Ascedning when user clicks on a column header repeatedly.
    I guess that means making sure a TableView's SortOrder list is not empty. Am I right?
    I tried to listen to SortOrder list changes like below:
    tableView.getSortOrder().addListener(new ListChangeListener<TableColumn<String, ?>>() {
         @Override
         public void onChanged(final javafx.collections.ListChangeListener.Change<? extends TableColumn<String, ?>> arg0) {
    if (tableView.getSortOrder().size() > 0) {
                   // fine. nothing to do
              else {
    // add the removed column back
    Is this the right approach?
    I'm not sure how to use arg0 and add the removed column back.
    Can people with experience in this area provide some sample code?
    Thanks.

    The solution I came up with was to save the last column added to the SortOrder list to a map.
    Whenever the SortOrder list becomes empty, I add the last saved column back to the SortOrder list.
    That seems work.
    Edited by: 925616 on Aug 3, 2012 3:33 PM
    Edited by: 925616 on Aug 3, 2012 3:33 PM

Maybe you are looking for

  • Trying to Salvage Crashed HD Files...am I on the right track?

    Alright. To make a long story short, my hard disk went kerput (not the physical structure, but the file structure or whatever corrupted). I haven't had to do anything like this since I was using OS9 so my OSX skills are crappy. Anyways. Here is what

  • What the hell has happened to my form???

    I was just compiling my form (Program > Compile > All) And then my hand slipped I clicked something and now all the items on my form have been resized and moved arround. Some items are now really tiny. And some are bigger. What the hell did I do and

  • Can I connect my iPad to my volvo?

    If so, how do I do that?

  • Can't get Facebook App to work on Bold 9700

    I have used the Facebook app on my Bold 9700 the past couple of years.  Recently, after an upgrade of the Facebook app, I can no longer get Facebook to work on my phone.  I have installed and uninstalled the app numerous times.  I have done many hard

  • I lost the 3D functionality in PhotoShop CS6 with the last update.

    error message: "The 3D features require that 'Use Graphics Processor' is enabled in the Performance preferences. [It is]. Your video card must meet the minimum requirements and you may need to check that your driver is working correctly." I was worki