In my JSF application, I use a rich:dataTable as follows:
<rich:dataTable id="itemTable" value="#{backingBean.itemsList}" var="i" >
<rich:column> <f:facet name="header">ItemValue</f:facet>
<h:inputText id="myId" value="#{i.value}" style="width: 30px" />
</rich:column> </rich:dataTable>
<h:commandButton id="saveB" value="Save" action="#{backingBean.doSave()}" />
Bean code of doSave:
public String doSave() {
Iterator<Item> = itemsList.iterator();
while(iter.hasNext()) {
//do something
}
}
In the doSave()-Method, i need to know the row index of the current Item, is there a way to achieve this?
While Richfaces extended data tables support a selection management, Richfaces datatables don't.
What I found the easiest way to do to retrieve a somehow selected item from a list, is to add an icon to every row. For this, put the command-Button into the data table itself:
<rich:dataTable id="itemTable" value="#{backingBean.itemsList}" var="i" >
<rich:column>
<h:inputText id="myId" value="#{i.value}" />
<h:commandButton id="saveB" action="#{backingBean.doSave}" />
</rich:column>
</rich:dataTable>
In the bean code, provide the method doSave but with an additional parameter ´ActionEvent´
public String doSave(ActionEvent ev) {
Item selectedItem = null;
UIDataTable objHtmlDataTable = retrieveDataTable((UIComponent)ev.getSource());
if (objHtmlDataTable != null) {
selectedItem = (Item) objHtmlDataTable.getRowData();
}
}
private static UIDataTable retrieveDataTable(UIComponent component) {
if (component instanceof UIDataTable) {return (UIDataTable) component;}
if (component.getParent() == null) {return null;}
return retrieveDataTable(component.getParent());
}
You see, that the ActionEvent ev provides you with the source element (UIComponent)ev.getSource(). Traverse through it until you hit the UIDataTable element and use it's row data.
Possible way two is to justgive the element as parameter with the function call:
<rich:dataTable id="itemTable" value="#{backingBean.itemsList}" var="i" >
<rich:column>
<h:inputText id="myId" value="#{i.value}" />
<h:commandButton id="saveB" action="#{backingBean.doSave(i)}" />
</rich:column>
</rich:dataTable>
and in the bean
public String doSave(Item item) {
// do stuff
}
That's not as clean, but should work with the EL, too. Hope, it helps...
Related
I have a datatable that is initially populated with no data (an empty list). There is a commandButton in the footer of the table that adds rows to the table. When a row is added, the last cell in the row is another commandButton to delete the row. My issue is that the delete button keeps deleting the first row in the table regardless of which row is selected.
Example: if I add 3 rows to the table and hit the delete button in the last cell of the second row, action="#{addAccountBean.deleteFixVendor(dataItem)}" passes the first row to the deleteFixVendor method instead of the second row which was clicked. I can't figure out why the object for the first row keeps on getting passed to the delete method regardless of which row button is clicked.
My JSF code:
<h:form>
<f:validateBean disabled="#{!empty param['disableValidation']}" >
<p:panel id="panel" header="Add New Account" >
<p:dataTable var="dataItem" value="#{addAccountBean.account.vendors}" >
<p:column headerText="Vendor" >
<p:selectOneMenu value="#{dataItem.vendor}">
<f:selectItems value="#{addAccountBean.menu.fixOption}" />
</p:selectOneMenu>
</p:column>
<p:column headerText="Monthly Cost" >
<p:inputText value="#{dataItem.cost}" />
</p:column>
<p:column headerText="Cost Date" >
<p:calendar value="#{dataItem.CDate}" pattern="MM/dd/yyyy" navigator="true" />
</p:column>
<p:column headerText="Delete" >
<h:commandButton value="Delete" action="#{addAccountBean.deleteFixVendor(dataItem)}" >
<f:param name="disableValidation" value="true" />
</h:commandButton>
</p:column>
<f:facet name="footer" >
<h:commandButton value="Add New Vendor" action="#{addAccountBean.addFixVendor}" >
<f:param name="disableValidation" value="true" />
</h:commandButton>
</f:facet>
</p:dataTable>
</p:panel>
</f:validateBean>
</h:form>
Bean code:
#ManagedBean
#SessionScoped
public class AddAccountBean implements Serializable {
private AccountData account = new AccountData();
public String addFixVendor() {
account.getVendors().add(new VendorData());
return "";
}
public String deleteFixVendor(VendorData vData) {
account.getVendors().remove(vData);
return "";
}
Any suggestions are appreciated.
The code posted so far looks fine. The only feasible explanation for this problem is a broken equals() method in the VendorData class. The Collection#remove() will remove the first item in the collection which equals() the given object.
Provided that your (base) entity has an id property, then this should do:
#Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((VendorData) other).id)
: (other == this);
}
#Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
I want to get the selected item from an orderList. It seems to me that this functionality is missing. Is there a functionality in PF? Or is there a possible workaround?
I really appreciate your answer!
My technology stack:
Hibernate: 4.0.1.Final
Spring: 3.1.1.RELEASE
Primefaces: 3.5
jsf-version: 2.2.0-m08
PrimefacesMobile-version: 0.9.3
Apache Tomcat/7.0.12
I've resolved this by using a button for delete. The code snippet is below:
<p:orderList id="layersList" value="#{mappingLayerController.layers}"
converter="layerConverter" var="layer" itemValue="#{layer}"
controlsLocation="left">
<p:column>
<h:outputText value="#{layer.layerName}"/>
</p:column>
<p:column style="width: 4%">
<p:commandButton icon="ui-icon-close" actionListener="#{controller.deleteLayer()}">
<f:param name="layerName" value="#{layer.layerName}" />
</p:commandButton>
</p:column>
</p:orderList>
And in the backing bean you can get the supplied parameter via the f:param tag as:
String layerName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("layerName");
I hope this helps.
I ran into the same issue trying to create an edit action for each item in my orderList. I tried passing my var to the action, creating an action listener in combination with an attribute, and a select listener all without success.
I ended up using a dataTable ... draggableRows="true" (see data table reorder in showcase). In the data table I could simply pass my var as a parameter to an action... So I thought. I ran into the issue that after reordering, clicking the edit button gave me the wrong item. I created a workaround being that on reorder I update the model and redraw the table. It works, but doesn't feel right.
<p:dataTable id="myTable"
value="#{myBean.myItems}"
var="item"
sortBy="#{item.orderNumber}" sortOrder="ascending"
draggableRows="true">
...
<p:column headerText="Actions">
<p:commandButton title="Edit"
action="#{myBean.edit(item)}"
process="#this">
</p:column>
<p:ajax event="rowReorder"
listener="#{myBean.onSlotContentReorder}"
update="myTable"/>
</p:dataTable>
It is possible in PrimeFaces 5 and higher. There is no out of box feature, but it can be easily achieved with additional list of selected items. See example
Java code
private List<Record> allItems; // with getter and setter
private List<Record> selectedItems; // with getter and setter
public void onSelect(SelectEvent event) {
if (null == event || null == event.getObject()) {
return;
}
if (!event.isCtrlKey()) {
setSelectedItems(new ArrayList<Record>());
}
Record item = (Record)event.getObject();
if (!getSelectedItems().contains(item)) {
getSelectedItems().add(item);
}
}
public void onUnselect(UnselectEvent event) {
if (null == event || null == event.getObject()) {
return;
}
Record item = (Record)event.getObject();
if (getSelectedItems().contains(item)) {
getSelectedItems().remove(item);
}
}
public void deleteSelected() {
if (getAllItems().isEmpty()) {
addErrorMessage("listEmpty");
return;
}
if (getSelectedItems().isEmpty()) {
addErrorMessage("noItemSelected");
return;
}
for (Record item : getSelectedItems()) {
if (getAllItems().contains(item)) {
getAllItems().remove(item);
}
}
}
XHTML
<h:panelGroup id="listGroup">
<p:orderList id="list" value="#{bean.allItems}"
var="item" itemLabel="#{item.code}" itemValue="#{item}"
converter="#{itemConverter}" controlsLocation="none">
<f:facet name="caption">#{msg.listName}</f:facet>
<p:ajax event="select" listener="#{bean.onSelect}" />
<p:ajax event="unselect" listener="#{bean.onUnselect}" />
</p:orderList>
<p:contextMenu id="listMenu" for="list">
<p:menuitem value="#{msg.delete}"
actionListener="#{bean.deleteSelected}"
update="listGroup, messages"
rendered="#{not empty bean.allItems}" />
</p:contextMenu>
</h:panelGroup>
I have a datatable with search field and commandLink to sort. The commandLink that I use to trigger sorting is located not in column header but on the header of datatable. When I load my page and use only commandLink to sort everything works ok. Table sorts in two orders and I see result on my page. Problem appears when I search something in globalFilter. It also works, but after that I cant sort my table. I clear inputText of globalFilter and I cant sort table. To sum up, I see result of sorting only when I not use search field. Sort operation works but request not update the datatable. I put my code below. Maybe somebody knows how to solve it.
<ui:composition>
<p:panel header="Moje pomiary" footer="#{msgs.footer}" id="myMeasurement">
<h:form id="form" prependId="false">
<p:dataTable var="m" value="#{myMeasurementTable.measurement}" id="measureList" editable="true"
widgetVar="mTable"
emptyMessage="No files found with given criteria" filteredValue="#{myMeasurementTable.filteredMeasurement}" >
<f:facet name="header">
Sortowanie według: <p:commandLink id="sortByName" actionListener="#{myMeasurementTable.sortByName}" update="measureList">
<h:outputText value="nazwa pliku" />
</p:commandLink>
|<h:commandLink action="#{myMeasurementTable.sortByArchivisationDate}"> data archiwizacji </h:commandLink>
|<h:commandLink action="#{myMeasurementTable.sortByMeasureDate}"> data badania </h:commandLink>
<p:outputPanel styleClass="searchPanel">
<h:outputText value="Szukaj: " />
<p:inputText styleClass="globalFilter" id="globalFilter" onkeyup="mTable.filter()" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column headerText="Informacje pomiarowe" style="width:125px" filterStyle="display:none" filterBy="#{m.fileName} #{m.measureDate} #{m.place} #{m.archivisationDate}"
filterMatchMode="contains" >
<p:separator styleClass="separatorColumn"/>
Nazwa pliku: <h:outputText value="#{m.fileName}" /><br />
Data badania: <h:outputText value="#{m.measureDate}" /><br />
Data archiwzacji: <h:outputText value="#{m.archivisationDate}" /><br />
Miejscowość: <h:outputText value="#{m.place}"/> <br />
Współrzędne GPS:
</p:column>
<p:column headerText="Wykresy">
<img src="/tmp/21/myfile.xls/myfile.xls_Parametr x.png" width="150"/>
</p:column> </p:dataTable></h:form></p:panel></ui:composition>
and part of my bean
#ManagedBean(name = "myMeasurementTable")
#ViewScoped
public class myMeasurementTable implements Serializable{
private static final long serialVersionUID = -9193902657201234669L;
private List<Measurement> measurement;
private List<Measurement> filteredMeasurement;
private boolean sortAscending = true;
public myMeasurementTable() {
measurement = new ArrayList<Measurement>();
fillTable(measurement);
}
public String sortByName() {
System.out.println("naciskam sortowanie");
if (sortAscending) {
Collections.sort(measurement, new Comparator<Measurement>() {
#Override
public int compare(Measurement m1, Measurement m2) {
return m1.getFileName().compareTo(m2.getFileName());
}
});
sortAscending = false;
} else {
Collections.sort(measurement, new Comparator<Measurement>() {
#Override
public int compare(Measurement m1, Measurement m2) {
System.out.println(m2.getFileName());
return m2.getFileName().compareTo(m1.getFileName());
}
});
sortAscending = true;
}
return null;
}
Ok I found solution on primefaces forum. It's simple. I only added oncomplete="mTable.filter()" to commandButton and everything works as I want.
I have a h:datatable showing a list of rows, and the fields of each row are input fields.
I render an "Add Row" button before the table, and a "Remove Row" button on each row of the table.
The baking bean is viewScoped, and the buttons add/remove elements from the java list in the backing bean, and then return to the same view.
I set the immediate attribute to "true" in the buttons in order to not validate the input fields when I add or remove a row.
Everything works ok but one thing: the values of the input fileds are cleared. I thought that the view kept the values beacuse the bean is viewScoped.
How can I achieve adding/removing rows without triggering validations and keeping the values that were already typed by the user in the form?
My view:
<h:form>
<h:commandButton value="Añadir Fila" immediate="true" action="#{tablaController.addRowAction}" />
<h:dataTable value="#{tablaController.lista}" var="fila" cellpadding="0" cellspacing="0" border="1">
<f:facet name="header">TABLA</f:facet>
<h:column>
<f:facet name="header"><h:outputLabel value="NOMBRE" /></f:facet>
<h:inputText id="nom" value="#{fila.nombre}" />
<h:message for="nom" class="msjError" />
</h:column>
<h:column>
<f:facet name="header"></f:facet>
<h:commandButton value="Quitar Fila" immediate="true" action="#{tablaController.removeRowAction(fila)}" />
</h:column>
</h:dataTable>
</h:form>
My backing bean:
#ManagedBean(name="tablaController")
#ViewScoped
public class TablaController {
private List<Fila> lista;
...
public TablaController() { }
...
#PostConstruct
public void init() {
this.lista = new ArrayList<Fila>();
for (int i=0; i<5; i++) {
Fila fila = new Fila();
fila.setNombre("");
this.lista.add(i,fila);
}
}
...
public String addRowAction () {
Fila fila = new Fila();
fila.setNombre("");
this.lista.add(fila);
return "";
}
public String removeRowAction (Fila f) {
boolean exito = this.lista.remove(f);
return "";
}
...
}
UPDATE --> MY SOLUTION:
I write here my solution if someone is interested.
The problem is that I use immediate="true" to skip validations, but this makes to skip the update_model_values too, so that the values entered by the user in the form are lost after clicking the add/remove buttons and re-redenring the page.
As I use "JSR-303 bean validation", my solution was to skip validations using the f:validateBean to enable/disable them. Depending on the button I click, if I want the validations to execute, I enable the bean validation (for example in a "submit" button), and if I want to skip them, I disable bean validation (like in the add/remove row buttons). But anyway the update_model_values always executes, so the values are not lost.
Here's the view:
<h:form>
<f:validateBean disabled="#{!empty param['disableValidation']}">
<h:commandButton value="Añadir Fila" action="#{tablaController.addRowAction}">
<f:param name="disableValidation" value="true" />
</h:commandButton>
<h:dataTable value="#{tablaController.lista}" var="fila" cellpadding="0" cellspacing="0" border="1">
<f:facet name="header">TABLA</f:facet>
<h:column>
<f:facet name="header"><h:outputLabel value="NOMBRE" /></f:facet>
<h:inputText id="nom" value="#{fila.nombre}" />
<h:message for="nom" class="msjError" />
</h:column>
<h:column>
<f:facet name="header"></f:facet>
<h:commandButton value="Quitar Fila" action="#{tablaController.removeRowAction(fila)}">
<f:param name="disableValidation" value="true" />
</h:commandButton>
</h:column>
</h:dataTable>
<h:commandButton value="Submit" action="#{tablaController.saveData}" />
</f:validateBean>
</h:form>
The backing bean:
#ManagedBean(name="tablaController")
#ViewScoped
public class TablaController {
private List<Fila> lista;
...
public TablaController() { }
...
#PostConstruct
public void init() {
this.lista = new ArrayList<Fila>();
for (int i=0; i<5; i++) {
Fila fila = new Fila();
fila.setNombre("fila "+i);
this.lista.add(i,fila);
}
}
...
public String addRowAction () {
Fila fila = new Fila();
fila.setNombre("");
this.lista.add(fila);
return "";
}
public String removeRowAction (Fila f) {
this.lista.remove(f);
return "";
}
...
public String saveData () {
...
//processes the valid data
//for example, calls to a service method to store them in a database
...
return "";
}
...
}
I set the immediate attribute to "true" in the buttons in order to not validate the input fields when I add or remove a row.
immediate="true" is the wrong tool for the job. It should be used to prioritize validation, not to enable/disable validation. The difference is rather huge as you encountered yourself.
You want to trigger validation conditionally. In case of e.g. required="true" that'd be as easy as
<h:inputText ... required="#{saveButtonPressed}" />
where #{saveButtonPressed} evaluates true when the save button is pressed. E.g. when its client ID is present in request parameter map.
In case of JSR 303 bean validation, that'd be a matter of
<f:validateBean disabled="#{not saveButtonPressed}">
<h:inputText ... />
</f:validateBean>
or with OmniFaces <o:validateBean> which allows controlling that on a per-command basis.
<h:commandButton id="add" ...>
<o:validateBean disabled="true" />
</h:commandButton>
I had exactly the same problem. In short, you can NOT use immediate for action that update data table(UIData) or facelet repeat. Short explanation:submitted values are not kept for re-display if inputs in UIData do not go through validation. Long explanation can be found here: long explanation and a related bug in Mojarra
I need one help from you. I am using JSF 2.0 and I have a datatable component . One of the column in the datatable is an action column and I need to create a toolbar which contains different type of actionsource component such as command button, link etc. The type of actionsource is determined at run time and number of actionsource is also done at run time. How I can implement this in JSF 2.0
<p:dataTable value="#{listBranchBean1.rowDataModel}" var="rowItem"
id="myId" paginator="true"
paginatorTemplate="{FirstPageLink}{PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}{RowsPerPageDropdown} "
rowsPerPageTemplate="10,5,2" previousPageLinkLabel="<"
nextPageLinkLabel=">" widgetVar="branchTable"
selection="#{listBranchBean1.selectedBranchesPrime}"
resizableColumns="true"
sortBy="#{rowItem.columnsValueMap['branchId'].value}">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search all fields:" />
<p:inputText id="globalFilter" onkeyup="branchTable.filter()"
style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column selectionMode="multiple" style="text-align:left">
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:outputText value="#{rowItem.uniqueId}" />
</p:column>
<p:column
rendered="#{listBranchBean1.columnsMap['objectId'].hidden==false}"
sortBy="#{rowItem.columnsValueMap['objectId'].value}"
filterBy="#{rowItem.columnsValueMap['objectId'].value}">
<f:facet name="header">
<h:outputText
value="#{listBranchBean1.columnsMap['objectId'].displayLabel}" />
</f:facet>
<h:outputText
value="#{rowItem.columnsValueMap['objectId'].value}" />
</p:column>
<p:column
rendered="#{listBranchBean1.columnsMap['actions'].hidden==false}">
<f:facet name="header">
<h:outputText
value="#{listBranchBean1.columnsMap['actions'].displayLabel}" />
</f:facet>
<p:toolbar>
<p:toolbarGroup>
<ui:repeat var="action"
value="#{rowItem.columnsValueMap['actions'].value}">
<p:commandButton title="#{action}" type="button">
</p:commandButton>
</ui:repeat>
</p:toolbarGroup>
</p:toolbar>
</p:column>
</p:dataTable>
I want to replace the last column with something like
<p:toolbar binding="#{listBranchBean1.getActions(rowItem)}">
</p:toolbar>
I appreciate your help
Prajeesh Nair
There is a difference between build-time and render-time in JSF. Build-time tags like <ui:repeat> have the ability to create new components dynamically, but they can only use data that is available at build-time.
However, using Java you are also allowed to alter the component tree programmatically, but this too can not just happen at any moment. The safe moment to do this is the preRenderViewEvent, which is a good bit later than the build-time moment (which is the restore view phase) and you should have all the data you need by then.
Inside an event handler for this event you can reference the tool bar you bound to your backing bean, and programmatically add columns to it.
For examples see:
http://balusc.omnifaces.org/2006/06/using-datatables.html#PopulateDynamicDatatable
http://arjan-tijms.omnifaces.org/2011/09/authoring-jsf-pages-in-pure-java.html
Do note that if your backing bean is #ViewScoped, you'd better not use binding but use a manual lookup instead. This is due to some bugs with respect to the view scope and binding components in JSF.
below code will create dynamic column on the basis of selected country
public void loadDynamicList() throws Exception {
int i=0;
dynamicList = new ArrayList<List<String>>();
dynamicList.add(Arrays.asList(new String[] { "ID1" }));
existingCountryList = new ArrayList<Country>();
String countryCode="US";
existingCountryList.add(getCountryService().getCountryByCode(countryCode));
Country country=getCountryService().getCountryByCode(countryCode);
countryLanguageSet=country.getCountryLanguage();
i=country.getCountryLanguage().size();
dynamicHeaders = new String[i] ;
int j=0;
for (CountryLanguage count: countryLanguageSet) {
System.out.println(count.getLanguage().getLanguageName());
dynamicHeaders[j]=count.getLanguage().getLanguageName();
j++;
}
}
public void populateDynamicDataTable() {
debugLogger.debug("populateDynamicDataTable:Enter");
// Create <h:dataTable value="#{myBean.dynamicList}" var="dynamicItem">.
HtmlDataTable dynamicDataTable = new HtmlDataTable();
dynamicDataTable.setValueExpression("value", createValueExpression("#{relationBean.dynamicList}", List.class));
dynamicDataTable.setVar("dynamicItem");
// Iterate over columns.
for (int i = 0; i < dynamicHeaders.length; i++) {
// Create <h:column>.
HtmlColumn column = new HtmlColumn();
dynamicDataTable.getChildren().add(column);
// Create <h:outputText value="dynamicHeaders[i]"> for <f:facet name="header"> of column.
HtmlOutputText header = new HtmlOutputText();
header.setValue(dynamicHeaders[i]);
column.setHeader(header);
HtmlInputText input=new HtmlInputText();
column.getChildren().add(input);
}
dynamicDataTableGroup = new HtmlPanelGroup();
dynamicDataTableGroup.getChildren().add(dynamicDataTable);
debugLogger.debug("populateDynamicDataTable:Exit");
}
public HtmlPanelGroup getDynamicDataTableGroup() throws Exception {
// This will be called once in the first RESTORE VIEW phase.
if (dynamicDataTableGroup == null) {
loadDynamicList(); // Preload dynamic list.
populateDynamicDataTable(); // Populate editable datatable.
}
return dynamicDataTableGroup;
}
public List<List<String>> getDynamicList() {
return dynamicList;
}
public void setDynamicList(List<List<String>> dynamicList) {
this.dynamicList = dynamicList;
}
public void setDynamicDataTableGroup(HtmlPanelGroup dynamicDataTableGroup) {
this.dynamicDataTableGroup = dynamicDataTableGroup;
}
public ValueExpression createValueExpression(String valueExpression, Class<?> valueType) {
FacesContext facesContext = FacesContext.getCurrentInstance();
return facesContext.getApplication().getExpressionFactory().createValueExpression(
facesContext.getELContext(), valueExpression, valueType);
}