Set selected row from backing bean in primefaces datatable - jsf-2

I am using primefaces datatable with clickable rows and I need to find way how to set selected row from backing bean.
There is my datatable definition:
<p:dataTable id="cablePathTable" var="cablePath" value="#{commonTableBean.cableLazyModel}" rows="100"
selectionMode="single" selection="#{commonTableBean.selectedCablePathTblRow}"
rowIndexVar="rowIndex" widgetVar="datatableVar"
emptyMessage="---">
<p:ajax event="rowSelect" process="#this" update=":form:portFieldset" />
<p:column headerText="No">
<h:outputText value="#{cablePath.column1}" />
</p:column>
<p:column headerText="Port A">
<h:outputText value="#{cablePath.column4}" />
</p:column>
<p:column headerText="Port B">
<h:outputText value="#{cablePath.column5}" />
</p:column>
I have tried following approach, but with no success.
In backing bean I have added method:
public void test(){
DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form:cablePathTable");
dataTable.setRowIndex(2);
}
And I have added test butoon to the XHTML page:
<p:commandButton process="#this" update=":form:cablePathTable" value="set2row" action="commonTableBean.test"/>
But nothig is changed on the datatable, selection didn't change...
Please any ideas how to solve this problem?

Just set the value behind selection="#{commonTableBean.selectedCablePathTblRow}".
public void test(){
selectedCablePathTblRow = cablepath;
}

Related

ModalPanel using RichFaces

I'm trying to create a ModalPanel from a dataTable (RichFaces 4.5.1, MyFaces 2.2.6, Spring 3.1.1, Tomcat 7.0.27) but I can't.
The modalPanel has values ​​to be displayed based on the selected row in the table. When I click in a commandLink, trigger a actionListener should feed these values (localidadeMB.carregarColecoes()), but it does't work, because the reference to attributes of bean is null (has not been set by the f:setPropertyActionListener located in commandLink).
What was missing?
*page.xhtml
(...)
<f:view>
<h:form id="formConsulta">
<rich:dataTable id="tabela"
value="#{localidadeMB.getLocalidadesPorPalavra()}" var="loc"
rowKeyVar="row" rows="20" width="800px" render="scroller">
<rich:column>
(...)
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<a4j:commandLink id="editlink" ajaxSingle="true"
oncomplete="#rich:component('modalEditarLocalidade')}.show()"
actionListener="#{localidadeMB.carregarColecoes}"
render="modalEditarLocalidade">
<h:graphicImage value="/img/edit.png"/>
<f:setPropertyActionListener value="#{loc}" target="#{localidadeMB.localidade}" />
</a4j:commandLink>
</rich:column>
</rich:dataTable>
</h:form>
<ui:include src="modalPanel.xhtml" />
*modalPanel.xhtml
<ui:composition>
<rich:popupPanel id="modalEditarLocalidade" autosized="true"
modal="false" resizable="false">
<f:facet name="header">
<h:outputText value="Alterar localidade" />
</f:facet>
<f:facet name="controls">
<h:graphicImage id="modalClosePNG2" value="/img/close1.png"
style="cursor:default;"
onclick="Richfaces.hideModalPanel('modalEditarLocalidade')" />
</f:facet>
<h:form>
<h:outputLabel value="Nome da localidade:" for="nomeLocalidade" />
<h:inputText id="nomeLocalidade"
value="#{localidadeMB.localidade.nome}" required="true"
immediate="true"/>
</h:inputText>
</h:form>
</rich:popupPanel>
</ui:composition>
*ManagedBean
private Localidade localidade;
public void setLocalidade(Localidade l){
this.localidade = l;
}
public void carregarColecoes(ActionEvent action){
System.out.println(localidade.getNome());
***** print NULL *****
}
If you want to set up a variable first and then execute a method you have to use #action for that method, actionListeners are executed first but since both of your methods are actionListeners the localidadeMB.carregarColecoes is executed before the variable is set. (And btw. h:commandLink has no "ajaxSingle" or "oncomplete" attributes.)
With the suggestion of Makhiel and this link I decided.
The xhtml looked like this:
<a4j:commandLink id="editlink" ajaxSingle="true"
oncomplete="#{rich:component('modalEditarLocalidade')}.show()"
action="#{localidadeMB.carregarColecoes}"
render="modalEditarLocalidade">
<h:graphicImage value="/img/edit.png"/>
<f:setPropertyActionListener value="#{loc}"
target="#{localidadeMB.localidade}" />
</a4j:commandLink>
and ManagedBean like this:
public String carregarColecoes(){
(....)
}

Initializing primefaces datatable rowkey

I have a primefaces datatable that I'm populating with properties of objects in an ArrayList once the user clicks a search button. I need to add a column with a radio button so that the user can select a row of the table to update. I'd like to set the rowkey to be the metadataKey property of my objects, but I get the following error:
rowKey="#{result.metadataKey}": Property 'metadataKey' not found on
type java.lang.String
I believed that this was caused by the metadataKey not existing at the time the table is rendered. To remedy it, I set the table to render only after the user had completed their search, but this resulted in the same error.
Here is the relevant html:
<h:form id="dataForm">
<p:panel styleClass="centered">
<p:messages id="message" showDetails="true" autoUpdate="true" />
<p:outputLabel id="searchLabel" value="Search for Metadata: " />
<p:inputText id="search"
value="#{updateMetadataItemsBean.searchTerm}" />
<p:commandButton id="searchButton" value="Search"
action="#{updateMetadataItemsBean.search}"
update="dataForm:metadataitems, message, dataForm:dataPanel" />
<br />
<br />
<br />
</p:panel>
<p:panel styleClass="center" id="dataPanel" >
<p:dataTable id="metadataitems" var="result"
value="#{updateMetadataItemsBean.results}" styleClass="center"
resizableColumns="true"
selection="updateMetadataItemsBean.selectedMetadataItem"
rowKey="#{result.metadataKey}" rendered="#{updateMetadataItemsBean.show}">
<p:column headerText="Select Item to Update" selectionMode="single"></p:column>
<p:column headerText="Metadata Key">
<h:outputText value="#{result.metadataKey}" />
</p:column>
<p:column headerText="Map Name">
<h:outputText value="#{result.mapName}" />
</p:column>
<p:column headerText="Metadata Name">
<h:outputText value="#{result.metadataName}" />
</p:column>
<p:column headerText="Metadata Value">
<h:outputText value="#{result.metadataValue}" />
</p:column>
<p:column headerText="WTX Adapter">
<h:outputText value="#{result.wtxAdapter}" />
</p:column>
<p:column headerText="Card Number">
<h:outputText value="#{result.cardNumber}" />
</p:column>
<p:column headerText="Create Date TS">
<h:outputText value="#{result.createDateTS}" />
</p:column>
</p:dataTable>
<br />
<br />
<br />
</p:panel>
This is the relevant code from the bean:
public class UpdateMetadataItemsBean implements Serializable{
public static final long serialVersionUID = 4;
private String metadataKey;
private String mapName;
private String metadataName;
private String metadataValue;
private String wtxAdapter;
private String cardNumber;
private String createDateTS;
private String searchTerm;
private String selectedDataKey;
private boolean show = false;
private MetadataItems selectedMetadataItem;
private ArrayList<MetadataItems> results = new ArrayList<MetadataItems>();
[getters and setters]
public void search() {
Search s = new Search();
setResults(s.search(searchTerm));
setShow(true);
}
Thanks in advance to anyone who can point me in the right direction.
Alter
selection="updateMetadataItemsBean.selectedMetadataItem"
to
selection="#{updateMetadataItemsBean.selectedMetadataItem}".

How to change the value of <p:dataTable> dynamically based on <p:selectItem>?

I am working with jsf 2.0 et Primefaces. i have a selectOneMenu that have dynamic values of datas that correspond to the user connected. I want that when i choose a data and click on the button view the list of emails related to the data selected will be shown on the dataTable.
<p:panel>
<p:selectOneMenu id="data" value="#{mailMB.database}" styleClass="auto" required="true" effect="fade" >
<f:selectItem itemLabel="Select Data" itemValue="" />
<f:selectItems value="#{dataMB.datas}" var="data" itemLabel="#{data.keyword}" itemValue="#{data.keyword}"/>
</p:selectOneMenu>
<p:commandButton value="View" action="#{mailMB.grabemails()}" ajax="true" update="datas" icon="ui-icon-circle-check" styleClass="ui-priority-primary" />
</p:panel>
<p:panel id="panelform" header="Emails List" >
<p:dataTable value="#{mailMB.emailsByData}" var="item" id="datas" rowsPerPageTemplate="5,10,15,20,25,30"
paginator="true" rows="10"
selectionMode="single" filteredValue="#{mailMB.filteredMails}" rowKey="#{item.id}"
selection="#{mailMB.selectedMail}">
<p:ajax event="rowSelect" update=":form:dataView , :form:confirmDelete, :form:viewButton" listener="#{dataMB.onRowSelect}"/>
<p:ajax event="rowToggle" />
<p:column style="width:2%" exportable="false">
<p:rowToggler />
</p:column>
<p:column sortBy="#{item.email}" filterBy="#{item.email}">
<f:facet name="header">
<h:outputText value="Email"/>
</f:facet>
<h:outputText value="#{item.email}"/>
</p:column>
</p:dataTable>
</p:panel>
and this is my method in the managed Bean that returns the list of emails by data using the named query:
public List<Email> getEmailsByData() {
System.out.println("the database" + getDatabase());
return emailsByData = mailBusinessLocal.mails(getDatabase());
}
public List<Email> grabemails() {
return emailsByData = mailBusinessLocal.mails(database);
}
when i choose a data and click view nothing happens and the databate return null as it shown on the glassfish log.
You need to put your <p:selectOneMenu> inside a <h:form>. That's my first guess.

form rendered on primefaces isn't calling the manage bean

I'm having problems with a form that is rendered by a booleanButtom on PrimeFaces 3.5
the form appear as expected but when I commit the values of the field come null.
The code of the pag:`
<p:panelGrid>
<p:row>
<p:column>
<h:form id="city">
<p:panelGrid columns="2">
<h:outputText value="Name: "/>
<p:inputText label="Name" value="#{managedBean.city.name}"/>
<h:outputText value="Status: "/>
<p:selectBooleanButton value="#{managedBean.city.status}" onLabel="Enable" offLabel="Disable">
<p:ajax listener="#{managedBean.changeStatusCity()}"/>
</p:selectBooleanButton>
<h:outputText value="Add neighborhood?"/>
<p:selectBooleanButton id="btAddNeighborhood" value="#{managedBean.addNeighborCity}" onLabel="Cancel" offLabel="Yes">
<p:ajax update=":addNeighbor" listener="#{managedBean.addNeighborCity()}"/>
</p:selectBooleanButton>
</p:panelGrid>
</h:form>
</p:column>
</p:row>
<p:row>
<p:column>
<h:form id="addNeighbor">
<p:panel header="Neighborhood" rendered="#{managedBean.addNeighborCity}">
<p:panelGrid columns="2">
<h:outputText value="Name: "/>
<p:inputText label="Name" value="#{managedBean.neighborhood.name}"/>
<h:outputText value="Status: "/>
<p:selectBooleanButton value="#{managedBean.neighborhood.status}" onLabel="Enable" offLabel="Disable" onIcon="ui-icon-check" offIcon="ui-icon-close">
<p:ajax listener="#{managedBean.changeStatusNeighbor()}"/>
</p:selectBooleanButton>
</p:panelGrid>
</p:panel>
</h:form>
<h:form id="formBt">
<p:commandButton id="bt" value="Add" actionListener="#{managedBean.saveNeighborCity()}" update=":addNeighbor, :city:btAddNeighborhood"/>
</h:form>
</p:column>
</p:row>
</p:panelGrid>`
And the manage bean
public void addNeighborCity(){
if(addNeighborCity){
neighborhood = new Neighborhood();
neighborhood .setStatus(true);
neighborhood .setStringStatus("Enable");
}else{
neighborhood = null;
}
}
public void changeStatusNeighbor() {
if (neighborhood .isStatus()) {
neighborhood .setStringStatus("Enable");
} else {
neighborhood .setStringStatus("Disable");
}
}
public void saveNeighborCity(){
city.getNeighborhoods().add(neighborhood );
neighborhood = null;
addNeighborCity = false;
}
All the input inside of the form that was rendered doesn't send the information to the manage bean and when I put the button that add the neighbor to the list of the city the button stop working and doesn't call the manage bean any more.
Does someone knows what I'm doing wrong or what is happening.
I'm using Primefaces3.5, GlassFish4.0 and JSF2.2
As you did not post the whole managed bean, I guess that you're using the default scope of the managed bean: #RequestScoped. In that case you should use #ViewScoped.
I solved the problem, I was using glassfish 4 and it forces the jsf2.2 even when you put the jsf2.1 in our project, then I changed to glassfish 3 and all work just fine, thanks for the answers, and I'm using #ScopeSession.

How to deselect the selected rows in Datatable programmatically

In my application in a dialog I displayed a dataTable in each column there are a check box to select corresponding row. At the bottom of dialog I paced two
button one for display selected rows another for reset the datatable means to deselect the selected rows.
.xhtml code is given below:
<p:dialog id="popUp" header="Activity Detail" widgetVar="popUpWidget"
showEffect="fade" hideEffect="explode" resizable="false" modal="true">
<h:panelGrid>
<p:row>
<p:column colspan="2">
<p:dataTable id="userListForAdminpopup" value="#{activityListController.activityUsers}" var="user"
paginator="true" paginatorPosition="bottom" widgetVar="userListForAdminpopUp"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rows="10" selection="#{activityListController.selectedActivityUsers}">
<p:column headerText="#{adbBundle['fullName']}"
sortBy="#{user.lastName}" filterBy="#{user.fullName}"
filterMatchMode="contains" styleClass="userName">
<h:outputLabel value="#{user.firstName}" />
</p:column>
<p:column selectionMode="multiple" />
</p:dataTable>
</p:column>
</p:row>
<p:row>
<p:column colspan="2">
<h:panelGroup layout="block">
<p:commandButton value="Update" oncomplete="confirmation.show()"/>
<p:commandButton value="Reset"/>
</h:panelGroup>
</p:column>
</p:row>
</h:panelGrid></p:dialog>
I want to deselect the rows when click on reset button. How it can be done?
We can deselect p:dataTable rows using unselectAllRows()
<p:dataTable
id="dataTableId"
widgetVar="dtWidgetVar"
value="#{myBean.items}"
var="item"
....>
</p:dataTable>
<p:commandButton value="Reset" onclick="PF('dtWidgetVar').unselectAllRows()" />
From the bean
PrimeFaces.current().executeScript("PF('dtWidgetVar').unselectAllRows()");
You try:
<p:commandButton value="Reset" update="userListForAdminpopup" process="#this" actionListener="#{activityListController.hand}"/>
Bean:
public void hand(){
selectedActivityUsers = new ActivityUsers(); // Type of element of list
}
Try this one:
DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form:dataTable");
dataTable.reset();

Resources