Search code examples
jsfdatatable

JSF commandbutton id inside datatable


How can I add in commandbutton inside datatable?

<hx:dataTableEx value="#{searchData.searchFriends}" var="s">
   <hx:columnEx>
    <f:facet name="header">
     <h:outputText value="First Name" />
    </f:facet>
    <hx:requestLink action="#{pc_Search.doAddFriendAction}">
     <h:outputText value="Add as Friend" />
     <f:param name="friendId" value="#{s.memberId}" />
    </hx:requestLink>
   </hx:columnEx>
  </hx:dataTableEx>

To get the data at backend

String friendId = (String)getRequestParam().get("friendId");

But once I change the requestlink to command button the friedId = null? any idea how can i pass value using command button


Solution

  • Wrap the datatable value in a DataModel. Then you can obtain the selected row by DataModel#getRowData().

    public class Bean {
        private List<Friend> friends;
        private DataModel friendsModel;
    
        public Bean () {
            friends = getItSomehow();
            friendsModel = new ListDataModel(friends);
        }
    
        public void addAsFriend() {
            Friend selectedFriend = (Friend) friendsModel.getRowData();
            // ...
        }
    }
    

    with

    <h:dataTable value="#{bean.friendsModel}" var="friend">
        <h:column>
            <h:commandButton value="Add as friend" action="#{bean.addAsFriend}" />
        </h:column>
    </h:dataTable>
    

    Should work as good with IBM Faces Client Framework (those hx: components).