Netbeans VWP Tip: How to create Muli-Row selectable Table component

This tip shows how to create a multiple row selection capable Table component. A column of Checkbox components is used to select multiple rows in the Table Component. Dynamic row highlighting is set to indicate the selected state of the rows. This tip is very similar to the tip I wrote for Single Selection Table Component.

You can download the working project here .

Steps

  • Create a Java EE 5 project called MultipleSelectionTable.
  • Add a table component from the Palette on to the Webform designer.
  • From the Runtime tab expand the Databases node and drag and drop a table on to the Table Component.
    • Right Click on the Table Component and Select Table Layout.
    • In the "Columns" tab click on the "New" button to add a new column.
    • Using "Up" button move the newly added column to the top of the list.
    • Replace the header text as "Select".
    • Select Checkbox for component type and remove the text in Value Expression Field.
  • Dismiss the Table Layout after clicking OK and refresh the designer using the refresh button in the designer's toolbar
  • Go to JSP page and add the following Java Script to the head section
<webuijsf:head binding="#{Page1.head1}" id="head1">
     <script>
       function initAllRows() {
            var table = document.getElementById("form1:table1");
            table.initAllRows();
         }
     </script>
     <webuijsf:link binding="#{Page1.link1}" id="link1" url="/resources/stylesheet.css"/>
</webuijsf:head>

You need to write some logic to hold information about the selected rows. Add the following code to the Sessionbean1.java

    private TableSelectPhaseListener tablePhaseListener = new TableSelectPhaseListener();
    
    public void setSelected(Object object) {
        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
        if (rowKey != null) {
            tablePhaseListener.setSelected(rowKey, object);
        }
    }
    
    public Object getSelected(){
        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
        return tablePhaseListener.getSelected(rowKey);
        
    }
    
    public Object getSelectedValue() {
        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
        return (rowKey != null) ? rowKey.getRowId() : null;
        
    }
    
    public boolean getSelectedState() {
        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
        return tablePhaseListener.isSelected(rowKey);
    }

Press Alt-Shift-F to fix the imports.

Now do the following to tell the Table Component to keep track of selection.

  • Select the CheckBox (from outline Table -> TableGroup-> TableCoulmn -> CheckBox) and set the properties
    selected="#{Sessionbean1.selected}"
    selectedValue="#{Sessionbean1.selectedValue}"
  • Select the corresponding table column and set the properties
    onClick="setTimeout('initAllRows()', 0)"
    selectId="checkbox1"
  • Select the TableRowGroup and set the property
    selected=#{Sessionbean1.selectedState}

Let us add a button, which on click would display the line number of the rows being selected.

  • Add a Button 
  • Add a Message Group to display the message after clicking the button.
  • Double click on the button and add the following code.
 
  public String button1_action() {
        int selectedRows = getTableRowGroup1().getSelectedRowsCount();
        RowKey[] selectedRowKeys = getTableRowGroup1().getSelectedRowKeys();
        for(int i=0; i< selectedRowKeys.length; i++){
            int rowId = Integer.parseInt(selectedRowKeys[i].getRowId()) + 1;
            info("Row " + rowId  + " is selected");
        }
        return null;
    }    

Deploy the application and in the displayed table component select one or two Checkboxess. The selected rows will be highlighted at  shown below. Click on the button and you should see message (at right) about line number of the rows being selected as below.

Comments:

Excelent example, but when you use a CachedRowSet with a table and use your code, the selected property is never called. I have spent the last 4 days trying to make an example work for a simple multiple selection and delete action. Can you help me please?

Posted by Luis Alberto Iñiguez Sánchez on December 19, 2006 at 08:58 AM PST #

great example, but what should i do, when i have 2 tables (1 with checkBox-column, 2 with radioButton-column) on the same jsp page??

Posted by Szymon on January 06, 2007 at 07:39 PM PST #

I like this example. I need to do the following. I need to have a list of clients in a table. Then next to the clients I need a textbox to enter an amount of employees. This list can be long so I enable pagination. Now... I've added the textbox next to each client name, but when I enter a value in the textbox and go to the next page, when I get back that value is missing. How do I keep the value there? Thanks!

Posted by Marthinus on February 07, 2007 at 03:25 PM PST #

Any answer to Luis Q? I got the same problem.

Posted by Eric Jexén on February 27, 2007 at 06:17 AM PST #

Download the Java Studio creator field guide at http://developers.sun.com/prodtech/javatools/jscreator/learning/bookshelf/index.jsp and then look in Chapter 9 for deleting multiple rows :) Worked for me. Be blessed.

Posted by Marthinus on February 27, 2007 at 02:01 PM PST #

Great example. I wonder if you could help me. I've got two problems and maybe this component is part of the solution. First I need to have two buttons in the end of each row, I meant the table will have two other columns and for each row there are two buttons: a delete and a update button. If I click the delete button then the respective row will be deleted and if a click the update button the page will be changed to another one where I can update each attribute. The second is when a user selects a checkbox, below the selected row will appear other details about the row, I meant, it will appear a blank space between the selected row and the row below it with more details. That's all. Best regards. Thanks in advance. Any help is worth it.

Posted by Jaindson on March 17, 2007 at 02:55 PM PDT #

Hi Jaindson, It is easy to do the delete and update button. Look at Table tutorials which explains this. But showing the details between two rows may not be supported by the table component. It may be possible to display the detail data at the end of the table though.

Posted by guest on March 19, 2007 at 12:36 AM PDT #

Good example. <copy file="${libs.jsf12-support.classpath.libfile.3}" todir="${build.web.dir.real}/WEB-INF/lib"/> I had an error building due to not being able to find file referenced above. Do you know what it is?

Posted by Becky Peltz on April 20, 2007 at 07:42 AM PDT #

Hi Winston, I ran into a stange behavior. I was using ObjectArrayDataProvider with above example. The selected property simply would not trigger until I switched from setting myDataProvider using it's array property to calling myDataProvider.setArray(myArray) from java code. Now it works like a charm. Any ideas?

Posted by Edward Yang on May 28, 2007 at 05:09 PM PDT #

bvc

Posted by guest on June 27, 2007 at 07:55 PM PDT #

Hello Winston. I have a problem. Suppose i need to select multiple rows and then i want to change query parameters so after submit my results will be different and may or may not include some of previously selected results. I want to have previously selected results to be selected and highlighted. Could you advise me something?

Posted by Alexander Yastrebov on July 15, 2007 at 07:01 PM PDT #

hi all i m trying to delete a row after i clicj on delete button.i m not using check box.But i shoould delete that perticular row beside which i click delete button.Please help me

Posted by ajit das on July 16, 2007 at 04:20 PM PDT #

I don't know about anyone else but I've just tried these instructions, and the Divas one on the Sun site. Like most of my other experience with VWP and NetBeans, its been a nightmare and implementing something so trivial is just wasting my time (I don't know if the instructions should differ for NB/VWP, but this doesn't work). Any readers coming along, I'd save yourself a huge amount of headache and avoid VWP/JSC or other other variant that mutates from the same codebase, like the alpha, flakey, exception generating plague it is. Yes, I've had a horrible day with this rubbish, coders behind this need to be reminded when software should be allowed to go beta.

Posted by QaDepartmentNeedsTheSack on August 13, 2007 at 06:38 PM PDT #

[Trackback] I migrated the sample tutorial project that I created for the Sun Java Studio Creator IDE into a NetBeans IDE 6.0 web application that uses the Visual Web Java Server Faces framework. You can download this NetBeans IDE project from here . Note th...

Posted by Insider Scoop From the Tutorial Divas on September 06, 2007 at 11:11 AM PDT #

It is not necesary to place the TablePhaseListener in the SessionBean. It can be placed in the page bean as in the Single Selectable Row Example.

Posted by Juan on September 21, 2007 at 04:20 AM PDT #

I mean all this code can be placed in the Page Bean
private TableSelectPhaseListener tablePhaseListener = new TableSelectPhaseListener();

public void setSelected(Object object) {
RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
if (rowKey != null) {
tablePhaseListener.setSelected(rowKey, object);
}
}

public Object getSelected(){
RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
return tablePhaseListener.getSelected(rowKey);

}

public Object getSelectedValue() {
RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
return (rowKey != null) ? rowKey.getRowId() : null;

}

public boolean getSelectedState() {
RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
return tablePhaseListener.isSelected(rowKey);
}

Posted by Juan on September 21, 2007 at 04:21 AM PDT #

The javascript code in the head section is not necesary for this example to work.

Posted by Juan on September 21, 2007 at 04:23 AM PDT #

Hello,

the sample works fine for me. But when i reload the page, the selection is gone! Why? I used the SessionBean for binding.

greetings
sascha

Posted by Sascha on November 12, 2007 at 12:16 AM PST #

Hi,

I am using Netbeans6.0 and i am working with DataTable component(WOOD STOCK TABLE ).

My Requirement is setting the data to the DropDown in the Table column. and get the selected DropDown value in current Row.

I am able to set the data.
i am able to get the selected rowkey. \* i am unable to get the selected value in dropdown value.\*

can any body help me.

Posted by Archana on November 27, 2007 at 08:45 PM PST #

Hi, with the current version of NB6.0 VWP, if you select the table property 'selectMultipleButton' and edit the table layout, you will have a tableRowGroup1SelectionColumn containing a tableRowGroup1SelectionChild checkbox. No needs to create it any more.
So, you can skip the step 'click on the "New" button to add a new column...'. Moreover, it generates also the JavaScript function so you can skip the steps to create the function and to call the function.

To summarize, check selectMultipleButton, go to table layout and click ok, it will create the check box. Add the code to the SessionBean1. Bind the values
\* tableRowGroup1SelectionChild: selected="#{Sessionbean1.selected}" and selectedValue="#{Sessionbean1.selectedValue}"
\* tableRowGroup1: selected=#{Sessionbean1.selectedState}

Posted by psecheresse on December 12, 2007 at 08:57 AM PST #

Hi!
I've a strange problem with the onClick="setTimeout('initAllRows()', 0)" property.
In the JSP view the code is highlighted in red and a red square indicates "Unexpected character." I'm using NetBeans IDE 6.0 (Build 200711261600). Any idea?

jet

Posted by jettero on January 13, 2008 at 02:46 AM PST #

how can I set some of the ceckboxes preselected programmatically based on some condition? would you please help me?

Posted by Muhammad Ijaz on January 14, 2008 at 03:52 PM PST #

Hi I am new to VJSF i am trying to get the selected value of a drop down in java script using netbeans 6 i dont know how could i can do this.
thanks in advance

Posted by Abdul Mannan on January 16, 2008 at 06:11 PM PST #

Hi Winston Prakash
Thanks for your example,it worked perfectly for me, infact I was able to implement the concept in my program, like in my own case I have a buttons(submit button), when I checked a single or a multiple checkbox and click on submit button it will iterate through the records selected and submit the records into the database and take the records off the table automatically but the issues now is after taken of the records it does not uncheck the checkboxes it will automatically check the next set of rows that are next to the onces that were previously checked.How can I uncheck the checkboxes on a click of the submit button after it has finish iterating through the selected record and iserting the record into the database

Posted by Muyiwa Osunronbi on January 29, 2008 at 07:38 PM PST #

hii i am new to jsp ..as i want to create jsp page that fetch data from database and show in jsp page having each row a checkbox ...as i select checkbox it can delete selected rows .. i am putiing my first page that makes it ..but how will get data to delete in next jsp page

<%@page contentType="text/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.\*" %>
<%
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
%>

<html>
<body>
<form method=post name=check action="deletecombo.jsp">
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost/books?user= & password= ");
statement = connection.createStatement();
rs = statement.executeQuery("SELECT \* FROM employee2");
%>

<table width="369" border="1">
<tr>
<td width="100"><span class="style5"><input type="checkbox" name="mainCheck" value="ON" /></span></td>
<td width="159"><span class="style5">Username</span></td>
<td width="194"><span class="style5">Password</span></td>
</tr>

<%

while (rs.next())
{
int i=0;
%>
<tr>
<td><input type="checkbox" name="check" value="<%= i%>"/>
<td><input name="USERNAME" value="<% out.println(rs.getString("username"))%>"></td>
<td><% out.println(rs.getString("password")); %></td>
</tr>
<%
i++;
}
%>
<form name="Form3" action="deletecombo.jsp"><table >
<tr><td><input type="submit" value="delete" /></td></tr></table></form>

Posted by vikram on February 12, 2008 at 03:38 PM PST #

Hello Winston, you have a great blog. Thanks for spreading out your work. I tried the above example and it worked great. I have one question though. When dealing with queries, if I need to make a selection based on more than one criteria, then I choose the 'IN?' and not '=?' right. How do I use the setObject function to send more than one selection? I tried an Object array but it doesn't like it ...ex: setObject(1, array). any advise is much appreciated.

Posted by varun on February 13, 2008 at 08:55 PM PST #

Hi, Varun. Winston forwarded me your comment. I looked around, and I think this article at http://developers.sun.com/jscreator/reference/techart/2/queryeditor.html is a good match for what you're asking.

Posted by David Van Couvering on February 14, 2008 at 03:48 AM PST #

Just want to say thanks.. ! This helped a lot! :)

Posted by Stephan on February 23, 2008 at 04:42 PM PST #

Hi,
Thank You Winston it is worked properly for first captured data in Table(First page).But Select some Check Boxes and click "Go To Back Page" after clicking "Go To Next Page" Then You can see previous selection cleared .How I work with keeping the also previous selected Check Boxes after clicking "Go To Next Page".

Posted by Suresh on February 28, 2008 at 12:59 PM PST #

zxdfg

Posted by guest on March 25, 2008 at 05:05 PM PDT #

same problem as suresh posted on february 28 2008

Posted by Mayank on April 01, 2008 at 09:40 PM PDT #

Hi Winston Prakash
here is Amjed i am working in VWP using netbeans 5.5 i have the following problem

i am using checkbox in table for selection
i trying to make checked the spsific rows in checkbox column.
i am using the follwing code in prerender to set selected
------------------->
boolean hasNext = getTbts_resource_actionsDP().cursorFirst();
getTbts_resource_actionsDataProvider().cursorFirst();
RowKey rowKey = null;
while(hasNext){
rowKey = getTbts_resource_actionsDataProvider().getCursorRow();
debug("rowKey = " + rowKey);
if(getTbts_resource_actionsDP().getValue("selected").toString().equalsIgnoreCase("1")){
session.setSelectedObject(true, rowKey);
session.setSelectedValue(rowKey);
}
String selected = "" + getTbts_resource_actionsDP().getValue("selected");
String actionId = "" + getTbts_resource_actionsDP().getValue("tbts_resource_actions.actionId");
debug(" actionId = " + actionId + " selected = " + selected);
hasNext = getTbts_resource_actionsDP().cursorNext();
getTbts_resource_actionsDataProvider().cursorNext();
}

<------------------

on execution the table's spesific rows bg color change as per selection but
checkbox not actually made checked.

2nd problem is that i cannot become successful to unselect and uncheck the rows each and
evry time "selected" property remain true for the even unchecked rows

Posted by Amjed on May 29, 2008 at 09:36 PM PDT #

vikram,
I m facing similar problem as yours.I want to display table data in jsp page.User will select the rows he wants using checkbox and I have to delete those rows from database.Can somebody guide me in this.I m not using EJB or struts.I m using plain jsp.

Posted by Avinash on June 24, 2008 at 10:03 PM PDT #

Hi, Nice example but the Table works well for first page.But if we have paginated set True for table and wants to select another row at next page in pagination the selection is cleared and rather than showing 2 rows selected it shows only 1 wherelse 2 rows in total have been selected 1 at page 1 and 1 at 2. How does it maintain the selection.

Posted by Khalid on July 29, 2008 at 09:28 PM PDT #

I too am interested in the response to Khalid's question as I am considering paginating my table. The record set I would need to support will soon have 7000+ records! At present, I have them categorized into several dozen groups and I have the groups listed in a combobox. When the user selects a different group, the contents of the table change completely.

The instructions given above work like a charm (using NetBeans 6.1, (SDK6, J2EE5)) for the first time the page is displayed, but when the user changes the group from the combobox, the http status is 500, with the message "The server encountered an internal error () that prevented it from fulfilling this request."

In the Tomcat 6.0.16 output, I see the following:
31-Jul-2008 11:27:44 AM com.sun.faces.lifecycle.LifecycleImpl phase
WARNING: executePhase(PROCESS_VALIDATIONS 3,com.sun.faces.context.FacesContextImpl@1f06804) threw exception
javax.faces.FacesException: /DailyETFreport.jsp(40,154) '#{Sessionbean1.selected}' Target Unreachable, identifier 'Sessionbean1' resolved to null

But I do not see anything in the logs or output related to the session bean not being created or available. In fact, after this error message is produced, I can go back (in the same session) and continue to use the session bean on other pages. My hunch is that the error is due to the contents of the table having been changed. I suspect this is, in some way, related to Khalid's question, but that the way to deal with it may be a bit different. I suspect that in my case, the session bean must somehow be notified that the contents of the table have been changed, the relevant data about selected items then needs to be stored, and the properties added above reset to appropriate null values.

There are then two questions.

1) How do you make the example code behave properly when the contents of the table change? (Bearing in mind that I MAY have to resort to a combination of combobox selection and pagination in order to handle 7000+ items well!)
2) Can both my issue and Khalid's issue be handled using the same code?

Posted by Ted on July 31, 2008 at 01:56 AM PDT #

How do you extract the values of a dropdown list within a wood stock table. I managed to get the selected items however I need to find a way to iterate through the table to extract the selected drop down list values.

Posted by Bjorn on October 14, 2008 at 11:11 PM PDT #

Hi, I also have been able to implement this tip but suffer the same problem of losing the selected choices after paginatiion is enabled and the user moves to a different page.

Would anybody be able to offer some insight on how to solve this?

tia..

Posted by Daren on October 15, 2008 at 11:51 PM PDT #

I've tried this and its worked, thanx to you. the problem is its worked only on one page and the other pages with same implementation not worked. i places the code on page bean. how can i make it work on any page?
thanx :)

Posted by amin on November 20, 2008 at 02:28 PM PST #

its very easy

Posted by guest on December 10, 2008 at 01:25 PM PST #

sir i m new to visual jsf i used this example but i dont know how to retrive values from the table component on to the java class if anyone can help please its urgent

Posted by vinay on March 23, 2009 at 12:00 AM PDT #

pls its urgent i only want to know how i get values of the row feilds which i checked in this example pls help
i m working on a project in my mca course pls help its really urgent
plssssssssssssss

Posted by vinay on March 23, 2009 at 12:03 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today