free web page hit counter
Thursday Feb 02, 2006

Creator Tip: How to create single selectable row Table component

This tip shows how to create a single selectable row table component. A column of radiobutton components could be used to select a single table row. Dynamic row highlighting is set when ever the state of the radiobutton changes.

You can download the working project here .

Steps

  • Create a project called SingleSelectTable.
  • Add a table component.
  • From the Servers tab drag and drop Data Sources->Travel->Tables->Trip on to the table component.
  • Right Click on the Table Component and Select Table Layout.
    Click on the "New" button to add a new column.
    Using "Up" button move the newly added column to the top of the list.
    Remove the header text.
    Select Radio Button for component type and remove the text in Value Expression Field.
  • Go to JSP page and remove other Java Scripts added to the table component except the following. Make sure the generated code is similar to the following
<script>
  function initAllRows() {
   var table = document.getElementById("form1:table1");
   table.initAllRows();
  }
</script>

You need to write some logic to hold information about the selected radio button in the Page1.java. So add the follwoing code to the Page1.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 Radio Button (from outline) and set the properties
    selected="#{Page1.selected}"
    selectedValue="#{Page1.selectedValue}"
    name="radioButton1" (for browser compatibility)
  • select the corresponding table column and set the properties
    onClick="setTimeout('initAllRows()', 0)"
    selectId="radioButton1"
  • Select the rowgroup and set the property
    selected=#{Page1.selectedState}

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

  • Add a Button (may change the text to "display row no.")
  • 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 the radio buttons. Only one row should be selected and highlighted at a time as shown below.


Click on the button and you should see message of the row number being selected as below.


Comments:

j

Posted by 151.46.140.168 on December 26, 2006 at 06:40 AM PST #

Hello Winston, great stuff in your blog! Thanks a lot for that. Just a question regarding this posting. Why if I do not specify a value for the Name field for the RadioButton I am allowed to select more than one row?

Posted by Luca on January 21, 2007 at 06:45 AM PST #

Hello Winston! This is a nice blog! But one question: How can I realize that there is only one radiobutton selected or how can I deselect the other radiobuttons, what I have selected before?

Posted by Roland Prinz on January 24, 2007 at 02:21 AM PST #

Hello Winston! This is a nice blog! But one question: How can I realize that there is only one radiobutton selected or how can I deselect the other radiobuttons, what I have selected before?

Posted by Roland Prinz on January 24, 2007 at 02:22 AM PST #

Hello, how can i deselect a selected row?

Posted by Sascha on January 24, 2007 at 07:35 AM PST #

Hello, you can try with public String button1_action() { // TODO: Process the button click action. Return value is a navigation // case name where null will return to the same page. tablePhaseListener.clear(); return null; } It works for my application. Luca

Posted by Luca on January 27, 2007 at 01:45 AM PST #

Hello, how can i select only one selected row?

Posted by Roland on February 19, 2007 at 02:37 AM PST #

Roland: You have to set the "name" property to something. Winston uses: name="radioButton1". You've probably skipped this step, because the "id" property is set to "RadioButton1".

Posted by Martin Varga on March 01, 2007 at 08:51 AM PST #

If the table consists of multiple pages and I want to select rows from different pages then click on display row no. button. For this the result will be only the rows that are selected in the last page. The question how can we keep track of the selected rows when we move from table page to another.

Posted by Wassim on March 12, 2007 at 12:39 PM PDT #

ok, thanks for this tip. Useful for me. Keep it up.

Posted by Jordan on March 17, 2007 at 01:38 PM PDT #

[Trackback] The UI presentation layer doesn’t hold state about which rows were selected. Winston Prakash outlines how selecting a single row in Netbeans JSF table can be done, but it was a little roundabout. Here’s a simpler take on it: Bind a Tabl...

Posted by Chui's counterpoint on March 24, 2007 at 04:20 AM PDT #

Gracias!! Este ejemplo me fue de utilidad.

Posted by SERGIO ORDOÑEZ on March 29, 2007 at 10:52 PM PDT #

Hello, how can i set the first row selected by default ?

Posted by QBert on March 31, 2007 at 01:50 AM PDT #

Hi Winston, First of all congratulations for these invaluable posts. I am trying to enhance your table example to allow single row editing in jsf table. I have adopted the tableRowgroup getchildren approach until I get to the components in each cell of the selected row and change that components readonly property to false. However the change I do in the component of that row is reflected in all the rows. How can one just modify a single row's components using the TableRowgroup component without effecting the other rows?

Posted by Mario Ciappara on April 04, 2007 at 01:49 AM PDT #

Hi Mario, I am trying to achieve the same editable row effect in the table, Had anybody get any solution for this problem. Any help would be highly appreciated

Posted by Gerson on May 03, 2007 at 08:31 AM PDT #

Hi Gerson, unfortunately no one gave me a solution on this problem and I did not manage myself to go round it. To tell you the truth I quite doubt it can be achieved since the getChildren method gets the default component used to render each row - hence it changes all rows for you. I have gone round this problem by creating an editable panel and fill the editable fields from the selected row each time I need to edit a row.

Posted by Mario Ciappara on May 03, 2007 at 08:46 AM PDT #

Mario is correct. I explained in my new blog how to use a panel to add & update records
http://blogs.sun.com/winston/entry/jpa_add_update_delete

Posted by Winston Prakash on May 03, 2007 at 08:52 AM PDT #

Thanks a lot for your answers Mario and Winston. I like your solution Winston, a nice workaround.

Posted by Gerson on May 05, 2007 at 06:18 PM PDT #

I would like that someone help me find out how to put a number/text at the Footer of column. I used the example of calculating calories and it was useful but I could not figure out how to place text/numbers at the Footer of a column. Thanks in advance Petraq

Posted by Petraq on May 17, 2007 at 10:15 AM PDT #

Hi!! First, congratulations for this fantastic weblog!! (excuse me my english...) Winston!! I do your steps for to get a single selectable row Table Component, but it happens this: I select the seventh row. I click on button and I get right data. And now, I select the first row, I click on button and I get wrong data!! I get data from the previous selection!! If you select previous rows, you get wrong data, but if you select next rows, you get right data. Why does it happen? And, how I get deselect previous selections???

Posted by Santiago on May 18, 2007 at 02:33 AM PDT #

Hi!!!! I'm fool... Deselection is made by a button that implements the Netbeans Visual Web Pack. Go to table component properties and select "Deselect Single Button". All right!!! That wonderful life is that "Deselection button" exists!!!

Posted by Santiago on May 18, 2007 at 02:49 AM PDT #

Petraq To make components appear in the footer of each column you need to define inside the column element a <f:facet name="footer"> componen, and put inside it the corresponding component, in this case I imagine you will need an outputText component made binding to the totals you want to show.

Posted by Gerson on May 18, 2007 at 06:51 PM PDT #

I am using CachedRowSetDataProvider in my project. I am getting all the required values from the database to CachedRowSet and then binding the provider to the table. Help me in retreving the Selected Row value in this case. My project will not deal with defaultTableProviders at all.

Posted by ParSar on May 30, 2007 at 03:44 AM PDT #

Hi there! I am glad to have such helpful information about the visual web. i m working on the JSF table component and i want to add a radio button group component to it. Ur (single selectable row Table component) example was good. But i need help for the same example using radio button group. Looking for a response ............ Thanx!

Posted by Waqas Raja on June 13, 2007 at 09:24 PM PDT #

I previously asked a question about the radio button group component, actually i want to get the value of the selected RBGroup from the table data. Hope u Understand!!

Posted by Waqas Raja on June 13, 2007 at 10:12 PM PDT #

Hi, What do we need to do to make this work for Netbeans 5.5? Thanks

Posted by Arijit Kundu on July 06, 2007 at 10:53 AM PDT #

LOS ANGELES, July 5 Pomegranate juice may help counter erectile dysfunction, according to findings by the University of Southern California. Dr. Harin Padma-Nathan, of the Keck School of Medicine at the University of Southern California, conducted a randomized, placebo-controlled, double-blind, crossover pilot study to examine the efficacy of pomegranate juice versus placebo in improving erections in 61 male subjects.

Posted by Dysfunction erectile pills on July 07, 2007 at 05:56 PM PDT #

Hello Winston. Can you help me? All my time i developed in C# but now i have interest to Java. So could you help me do this selectable row Table under NetBeans 5.5.1 + VWP 5.5.1 Please help. :) Best Regards F.

Posted by Foli on July 13, 2007 at 03:38 AM PDT #

Hi, maybe i'm the first member from indonesia and just wanna to say hi to all.

Posted by Sexual Stimulant on July 18, 2007 at 07:00 PM PDT #

Hi, how to programmatically bind the table component with external database (mysql)... without using JNDI reference... If anyone know plz share the knowledge. Thanx

Posted by Waseem Kayani on July 25, 2007 at 09:11 AM PDT #

Hi, how to programmatically bind the table component with external database (mysql)... without using JNDI reference... If anyone know plz share the knowledge. Thanx

Posted by Waseem Kayani on July 25, 2007 at 09:16 AM PDT #

Hello. How can I select row programatically and set corresponding radiobutton? ??????

Posted by Michael on July 30, 2007 at 08:13 AM PDT #

To deselect all radio buttons you must write: tablePhaseListener.clear(); To keep only one selection you must go to the radio buttons properties and in the name property write something like radioButtonGroup. In this way all radio buttons work together and only one can be selected at a time. If you can`t select the radio button you can go to the outline window and find it inside table -> tableRowGroup1 -> tableColumn1 for example.

Posted by Juan on August 01, 2007 at 07:39 AM PDT #

It is not necesary to remove the javascript code of the page or to write Winston`s javascript code: <script> function initAllRows() { var table = document.getElementById("form1:table1"); table.initAllRows(); } </script> to make this work

Posted by Juan on August 01, 2007 at 07:42 AM PDT #

yeah

Posted by 212.210.147.101 on August 02, 2007 at 12:24 AM PDT #

Thanks for the post on this. It helped me a lot. How would you go about setting a default selection when a person came back to this page. Specifically, lets say that you wanted tripID 202 selected automatically this first time the page loads, or in my case I need to set the selected row to what the customer chose before. I store their selected values in the database, and pull them back out, I just can't figure out how to get the radioButton checked. Thanks Steve Michael

Posted by Steve Michael on August 06, 2007 at 07:50 AM PDT #

I've worked out my issue with trying to get this working. If I reload my ObjectListDataProvider in the prerender() method (NB5.5.1/VWP), the selection state is lost (i.e. none of the above works). If I shift the reload of the OLDP to preprocess(), things work and the row selection is maintained and highlighted (I didn't need to add the Javascript function). Only thing I can guess at is that something is using object equality (==) to test the row selection. Which if I'm right isn't great.

Posted by Joe on August 14, 2007 at 06:53 PM PDT #

Hi, thanks for this blog, i'm reading a lot of jsf books and something, all is here :-).
I have a problem, i have got the row number when select, but, if i want to get the table field value? ( as name, age, ....) without use the jpa ( i see the other blog and the personal website :-) ) #{currentRow.tableRow} returns always 'null' and if change #{currentRow.value['ID'] the same.
Thanks

Posted by Deivit on August 17, 2007 at 03:09 AM PDT #

Hi Deivit

Usually you put an object model (a List<Person> for instance) encapsulated inside an ObjectListDataProvider, then you can get the selected value of type Person and access to the Person object. Remember that you put the DataProvider in a TableRowGroup. Try this:

// Please check the right syntax
public String edit(){
RowKey rowkey = tableRowGroup.getRowKey();
// Domain object
Person person = dataProvider.getValue(rowKey);
getSessionBean().setPerson(person);
}

After this you can access to the property in the JSP view like this

<f:outputText value="#{sessionBean.person.name}"

If you work with a working domain model it results easier, right?. Good Luck.

Posted by Gerson on August 17, 2007 at 10:52 AM PDT #

Hi!
How to set a default selection, so that some row would be selected after the page rendering? I tried to do this in Invoke Application phase and in Render Response phase but it didn't work. I used setSelectedRows(RowKeySet r) method from UIXTable. I don't use NB. Can anyone help?

Posted by Piotr Pikusa on September 10, 2007 at 07:05 AM PDT #

Hi. i don't know how can i do (in this example) if i select a row (radio Button) automatically generate a event that identifies the row.(is like this example but without push the button)

thanks for all.

Posted by Deivit on September 12, 2007 at 09:14 AM PDT #

Why do you remove the other Java Scripts added to the table component?

Posted by c on September 19, 2007 at 01:15 PM PDT #

is it obligatory to set the radio button to autosubmit to highlight the row on selection?

Posted by c on September 20, 2007 at 05:35 AM PDT #

Well good article,,, but this works on Netbeans5.5.1 using the standard Visual Web Aplication...?

And another thing why my table get clear when I submit any chances (I put my ObjectListaDa.. on Page1.jav)?

using this:

RowKey rowkey = tableRowGroup.getRowKey();
My rowkey is null (ever time)... I just follow the article... what it could be?

See:
My page is show
my table is only one select row
my table is populate too
but the way to get back value of selection doesn't work...

Posted by Leandro on September 28, 2007 at 08:08 AM PDT #

Hi,

Did anybody compile this project with Netbeans 6 beta 2 ?

Posted by Valentin on October 29, 2007 at 07:04 AM PDT #

If we import this project in Visual Web Pack of Netbeans 5.5.1 then it does not work. Also if we want to make single row selectable using Winston given steps then it does allow to select but it keeps selecting each clicked row so sounds like initAllRows() javascript function does not work well.

Suggestion will be appreciated.

Thanks,
Vijay

Posted by Vijay on November 09, 2007 at 07:41 AM PST #

Hi,
I am using sun creator. I want to have an automatic selection of first row in a table when page appears.
I did it like this:
RowKey[] rowKeys = getMyDataProvider().getAllRows();
myID = (Integer) getMyDataProvider().getValue("myID", rowKeys[0]);
tablePhaseListener.setSelected(rowKeys[0], new Boolean(true));

By doing this, the first row is higlighted, but corresponding radio button is not selected. Can anyone help in this regard?

Thanx,
Faisal

Posted by Faisal on December 02, 2007 at 01:12 AM PST #

How do you have two database tables on the same page? Which table is getValue("#{currentRow.tableRow}") refering to? Thnks.

Posted by Wai Wu on January 17, 2008 at 12:40 PM PST #

I did this excersise but the row where i click radio button didnt highlight only after when i click button1, please help me.

Posted by Roberto on February 18, 2008 at 10:40 PM PST #

Does any one have code to display a table row as selected when the page render?

Thanks
- Lakshmi

Posted by lakshmi on February 28, 2008 at 11:13 AM PST #

does it work for NetBeans 6.0?

Posted by 129.6.72.13 on April 23, 2008 at 02:55 PM PDT #

Hi winston, although its working fine, but i have a different scenario, i just want to user click on any row in the table and i need the row id for that clicked row in the table, i dont want to use a radio button or check box , i will permit the user to click on any row.

Posted by Abdul Mannan on May 29, 2008 at 03:02 AM PDT #

q

Posted by 122.160.68.248 on September 30, 2008 at 02:27 AM PDT #

You are a genius! Fantastic, look for this a lot of time! You saved the life! ;)

Posted by veronk on October 15, 2008 at 08:03 AM PDT #

http://www.batteryfast.co.uk/hp/nc8000.htm hp nc8000 battery,
http://www.batteryfast.co.uk/hp/v1000.htm hp v1000 battery,
http://www.batteryfast.co.uk/hp/nx4300.htm hp nx4300 battery,

Posted by laptop batteries on October 24, 2008 at 12:26 AM PDT #

We have developed a DELL laptop battery finder tool that will guide you in choosing the correct battery and ac adapter for your laptop. Your first step is to choose your DELL model from the list below.
http://www.inbattery.com/HP-laptop-batteries/HP.html
http://www.tool-battery.com/
http://www.inbattery.com/
http://www.toolbattery8.com/

Posted by laptop battery on November 13, 2008 at 08:03 PM PST #

Hi..
I have done everything whatever is there in this blog but still its giving nullpointerexception.. Can you pls help me as soon as possible.

Posted by yashaswini.v on February 26, 2009 at 11:24 PM PST #

how do u do this in netbeans 6.5 without the use of radio buttons? is it possible?

Posted by denim on March 16, 2009 at 05:13 PM PDT #

It works great. Be careful on JavaScript table path. Load page, take a look on its html source to see where exactly the table is.
At my side the code looks like :

function initAllRows()
{
var table = document.getElementById('form1:tabSet1:tab1:layoutPanel1:table1');
table.initAllRows();
}

Posted by Ionut Neicu on May 31, 2009 at 09:35 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed