p:pickList doesn't update the source and target - jsf

I have been accessing the p:picklist for the first time and I am facing a issue where I am not able to get source and target values updated as in the p:picklist ui. I am using list of DualListModel<String>. Here is the code..
Please help me.
Thanks for the help!
code.xhtml
<p:dataTable value="#{updateSiteObj.dsList}" var="pickListObjDS" >
<p:column headerText="DS">
<p:pickList id="pojoPickListDSID" value="#{pickListObjDS}" var="ds" itemValue="#{ds}" itemLabel="#{ds}" showSourceFilter="true" showTargetFilter="true" filterMatchMode="contains" style="border-color: white!important" onTransfer="ajaxSubmit3()">
<f:facet name="sourceCaption">Available</f:facet>
<f:facet name="targetCaption">To be removed</f:facet>
</p:pickList>
<p:remoteCommand action="#{updateSiteObj.onDSTransfer}" name="ajaxSubmit3"/>
</p:column>
</p:dataTable>
UpdateSite.java
#ManagedBean(name = "updateSiteObj")
#SessionScoped
public class UpdateSite {
private List<DualListModel<String>> dsList = new ArrayList<DualListModel<String>>();
public List<DualListModel<String>> getDsList() {
return dsList;
}
public void setDsList(List<DualListModel<String>> dsList) {
this.dsList = dsList;
}
public String updateSiteDetails() {
ds.add(sg.getPrimaryDSID());
if (sg.getSecondaryDSID() != null) {
ds.add(sg.getSecondaryDSID());
}
System.out.print("DS:" + sg.getPrimaryDSID() + "=>" + sg.getSecondaryDSID());
DualListModel<String> tempDS = new DualListModel<String>();
tempDS.setSource(ds);
dsList.add(tempDS);
return "someSite?faces-redirect=true";
}
public void onDSTransfer() {
System.out.print("DSTransfer");
for (DualListModel<String> str1 : dsList) {
System.out.print("RemovedLBEntry:");
for (String dsName1 : str1.getTarget()) {
System.out.print("RemovedLB:" + dsName1);
}
}
}
}
When I try to call onDSTransfer after moving the values from source panel to target panel in picklist UI doesn't show any value from target.

Add update="#all" in p:remoteCommand.
You are doing a ajax call and not updating your UI.
<p:remoteCommand action="#{updateSiteObj.onDSTransfer}" name="ajaxSubmit3" update="#all"/>

Related

Primefaces: Form fields not synced with Managed Bean automatically

Have a nice day. I don't know if i'm wrong about this. I have a form in my xhtml like this:
<p:outputLabel value="Número de pasajeros" />:
<p:inputText value="#{vueloMB.instancia.numPasajeros}" maxlength="3" >
</p:inputText>
<br />
<p:outputLabel value="Hora de salida" />:
<p:calendar value="#{vueloMB.instancia.fechaHoraSalida}" navigator="true"
mode="popup" pattern="dd/MM/yyyy HH:mm" />
<br />
<p:outputLabel value="Avión" />:
<p:selectOneMenu value="#{vueloMB.instancia.avion}" >
<f:selectItems value="#{vueloMB.aviones}" var="avi"
itemLabel="#{avi.modelo}" itemValue="#{avi}" />
</p:selectOneMenu>
<br />
<p:outputLabel value="Pais de salida" />:
<p:selectOneMenu value="#{vueloMB.instancia.paisSalida}" converter="omnifaces.SelectItemsConverter" >
<f:selectItems value="#{vueloMB.paises}" var="pai"
itemLabel="#{pai.nombre}" itemValue="#{pai}" />
<f:param name="tipoPais" value="S"></f:param>
<p:ajax update="ciusal" listener="#{vueloMB.cargarListaCiudades}" process="#this" >
</p:ajax>
</p:selectOneMenu>
<br />
<p:outputLabel value="Ciudad de salida" />:
<p:selectOneMenu value="#{vueloMB.instancia.ciudadSalida}" converter="omnifaces.SelectItemsConverter"
id="ciusal" disabled="#{vueloMB.instancia.paisSalida==null}" >
<f:selectItems value="#{vueloMB.ciudadesSalida}" var="ciu"
itemLabel="#{ciu.nombre}" itemValue="#{ciu}" />
</p:selectOneMenu>
<br />
<p:commandButton value="Guardar" rendered="#{vueloMB.instancia.id == null}" action="#{vueloMB.guardar()}" process="#form" ajax="true" />
</h:form>
The dropdown labeled "Ciudad de salida" refreshes another dropdown after i choose a country here, updates the list that feeds the second dropdown and it works fine. The problem is when i press the "Guardar" button to save the entity (vueloMB.instancia is my entity) with JPA, because it doesn't do anything.
So, i added the attribute immediate="true" to the button, it calls the ManagedBean method, but when i see the entity, only the field vueloMB.instancia.paisSalida isn't null, even if i fill all the fields. Because of that, i assumed that, because the dropdown calls an MB method because it refresh the second dropdown, it's value is refreshed on the MB. Based on that, i modified the first field like this:
<p:inputText value="#{vueloMB.instancia.numPasajeros}" maxlength="3" >
<p:ajax />
</p:inputText>
I added the ajax tag to my inputText. After doing that, i press the "Guardar" button and the field that i've modified (Número de pasajeros) now it carries the value on vueloMB.instancia.numPasajeros.
So, if i add to all my fields, when i press the submit button it will work, it will save the entity without problems and all the fields will travel to the managed bean, but is necessary to do that with every field? There's no automatic way JSF does this? Or i have something wrong with my code?
EDIT: Here is the code of the managed bean. A CDI Managed Bean with #ConversationScoped:
package com.saplic.fut.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import com.saplic.fut.daos.VueloDAO;
import com.saplic.fut.entity.Avion;
import com.saplic.fut.entity.Ciudad;
import com.saplic.fut.entity.Pais;
import com.saplic.fut.entity.Vuelo;
#Named("vueloMB")
#ConversationScoped
public class VueloManagedBean implements Serializable {
private static final long serialVersionUID = -203436251219946811L;
#Inject
private VueloDAO vueloDAO;
#Inject
private Conversation conversation;
#PostConstruct
public void iniciarConversacion() {
if(conversation.isTransient())
conversation.begin();
}
public void finalizarConversacion() {
if(!conversation.isTransient())
conversation.end();
}
private Vuelo instancia;
private List<Vuelo> vuelos;
private List<Avion> aviones = new ArrayList<Avion>();
private List<Pais> paises = new ArrayList<Pais>();
private List<Ciudad> ciudadesSalida = new ArrayList<Ciudad>();
private List<Ciudad> ciudadesAterrizaje = new ArrayList<Ciudad>();
private Integer idVuelo;
public String cargarLista() {
iniciarConversacion();
vuelos = vueloDAO.cargarVuelos();
return "/vuelos/lista";
}
public void cargarListaCiudades() {
String tipoLista = FacesContext.getCurrentInstance().
getExternalContext().getRequestParameterMap().get("tipoPais");
if(tipoLista.equalsIgnoreCase("S"))
setCiudadesSalida(vueloDAO.cargarCiudades(getInstancia().getPaisSalida()));
if(tipoLista.equalsIgnoreCase("A"))
setCiudadesAterrizaje(vueloDAO.cargarCiudades(getInstancia().getPaisAterrizaje()));
}
public String cargarDetalle() {
Vuelo fltVuelo = new Vuelo();
fltVuelo.setId(getIdVuelo());
instancia = vueloDAO.cargarDetalle(fltVuelo);
if(instancia == null)
setInstancia(new Vuelo());
//Cargamos lista de aviones para combo
setAviones(vueloDAO.cargarAviones());
setPaises(vueloDAO.cargarPaises());
return "/vuelos/detalle";
}
public String guardar() {
vueloDAO.guardar(instancia);
finalizarConversacion();
return cargarLista();
}
public String actualizar() {
vueloDAO.actualizar(instancia);
finalizarConversacion();
return cargarLista();
}
public String eliminar() {
vueloDAO.eliminar(instancia);
finalizarConversacion();
return cargarLista();
}
public Vuelo getInstancia() {
return instancia;
}
public void setInstancia(Vuelo instancia) {
this.instancia = instancia;
}
public List<Vuelo> getVuelos() {
return vuelos;
}
public void setVuelos(List<Vuelo> vuelos) {
this.vuelos = vuelos;
}
public Integer getIdVuelo() {
return idVuelo;
}
public void setIdVuelo(Integer idVuelo) {
this.idVuelo = idVuelo;
}
public List<Avion> getAviones() {
return aviones;
}
public void setAviones(List<Avion> aviones) {
this.aviones = aviones;
}
public List<Pais> getPaises() {
return paises;
}
public void setPaises(List<Pais> paises) {
this.paises = paises;
}
public List<Ciudad> getCiudadesSalida() {
return ciudadesSalida;
}
public void setCiudadesSalida(List<Ciudad> ciudadesSalida) {
this.ciudadesSalida = ciudadesSalida;
}
public List<Ciudad> getCiudadesAterrizaje() {
return ciudadesAterrizaje;
}
public void setCiudadesAterrizaje(List<Ciudad> ciudadesAterrizaje) {
this.ciudadesAterrizaje = ciudadesAterrizaje;
}
}
Regards.
Your entities must implements the method equals() hashCode() and toString as specified in the omnifaces showcase. I can't help you much more than that since I'm not familiar with omnifaces and the ConversationScope. I think it's because the two objects are not at the same place in memory so when you use equals the result is false. In the case of omnifaces I read it uses toString() to see if two objects are equal so if the method is not reimplemented you will have different results.
In other words you have null values because when the value as string comes back from the form it cannot be converted back to the original object. I'd appreciate if someone could attest this as I'm not 100% positive that's what is happening.

Refreshing PrimeFaces form element dataTable (code details provided)

I have Search form. After clicking on Search button data refreshes, but dataTable columns not (columns get refreshed only on second button click). Apparently I am doing something wrong. Dynamic column code is inspired by PrimeFaces Showcase
myForm.xhtml:
<h:form id="MY_FORM">
#{myBean.initBean()}
...
<h:panelGrid id="main">
<h:panelGrid id="buttons">
<p:commandButton id="submitSearch"
value="#{msg['button.execute']}"
actionListener="#{myBean.submitSearch}"
update="resultPanel"/>
</h:panelGrid>
</h:panelGrid>
<h:panelGrid id="resultPanel" border="0">
<p:dataTable id="resultTable" var="result" value="#{myBean.searchResults}">
<p:columns value="#{myBean.columns}" var="column" columnIndexVar="colIndex">
<f:facet name="header">
<h:outputText value="#{column.header}" />
</f:facet>
<h:outputText value="#{result[column.property]}" />
</p:columns>
</p:dataTable>
</h:panelGrid>
</h:form>
I've called column calculation method createColumns() from myBean.initBean() and myBean.submitSearch() with the same result (I see it works correctly from debugger).
#ManagedBean("myBean")
#Scope(value = "session")
public class MyBean {
private ArrayList<HashMap<String,Object>> searchResults;
private List<ColumnModel> columns;
...
public void initBean() {
...
createColumns(selectedDates);
}
public void submitSearch() {
...
ArrayList<HashMap<String, Object>> results = prpRepository.getSearchResultByParams(searchParams);
createColumns(selectedDates);
}
private void createColumns(ArrayList<String> selectedDates){
columns = new ArrayList<ColumnModel>();
columns.add(new ColumnModel("Name", "NAME"));
columns.add(new ColumnModel("Amount", "AMOUNT"));
for (int i = 0; i < selectedDates.size(); i++) {
columns.add(new ColumnModel(selectedDates.get(i), "DATE" + i));
}
setColumns(columns);
}
public List<ColumnModel> getColumns() {
return columns;
}
public void setColumns(List<ColumnModel> columns) {
this.columns = columns;
}
}
Additional information:
I am using:
Oracle's Implementation of the JSF 2.1 Specification
JavaServer Pages API 2.2
Springframework 3.1.2 (incl. spring-context, spring-web)
Glassfish Javax.annotation 3.1.1
The problem is that columns is calculted only once time in the org.primefaces.component.datatable.DataTabe
public List<UIColumn> getColumns() {
// if(columns == null) {
columns = new ArrayList<UIColumn>();
FacesContext context = getFacesContext();
char separator = UINamingContainer.getSeparatorChar(context);
for(UIComponent child : this.getChildren()) {
if(child instanceof Column) {
columns.add((UIColumn) child);
}
else if(child instanceof Columns) {
Columns uiColumns = (Columns) child;
String uiColumnsClientId = uiColumns.getClientId(context);
uiColumns.updateModel(); /* missed code */
for(int i=0; i < uiColumns.getRowCount(); i++) {
DynamicColumn dynaColumn = new DynamicColumn(i, uiColumns);
dynaColumn.setColumnKey(uiColumnsClientId + separator + i);
columns.add(dynaColumn);
}
}
}
// }
return columns;
}
You could comment it and overwrite the class file,
or find the DataTable object and setColumns to NULL inside the createColumns method
Finally I've worked better with debugger and found an answer. Solution was to put createColumns() method call into columns getter getColumns() as it is called automatically before submitSearch(). My problem was in application lifecycle understanding.

How to pass a row object to the backing bean using JSF 2 and RichFaces?

I am using RichFaces's ordering list to display a table custom Command objects to the user. The user uses a form to create new commands which are then added to the list. Here is the orderingList implementation:
app.xhtml
<rich:orderingList id="oList" value="#{commandBean.newBatch}" var="com"
listHeight="300" listWidth="350" converter="commandConverter">
<f:facet name="header">
<h:outputText value="New Batch Details" />
</f:facet>
<rich:column width="180">
<f:facet name="header">
<h:outputText value="Command Type" />
</f:facet>
<h:outputText value="#{com.commandType}"></h:outputText>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Parameters" />
</f:facet>
<h:outputText value="#{com.parameters}"></h:outputText>
</rich:column>
<rich:column>
<h:commandButton value="Remove #{com.id} : #{com.seqNo}"
action="#{commandBean.remove(com.id,com.seqNo)}"
onclick="alert('id:#{com.id} seqNo:#{com.seqNo}');"/>
</rich:column>
My troubles began when I tried to implement a remove button which would send a command's ID and seqNo to the backing bean (cb) to be removed from the list. Here is the backing bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class CommandBean implements Serializable{
private static final long serialVersionUID = 1L;
private CommandType type;
private String parameters;
private List<Command> newBatch = new ArrayList<Command>();
private Set<Command> commandSet = new HashSet<Command>();
private String msg = "not removed";
public CommandType[] getCommandTypes() {
return CommandType.values();
}
public void addCommand(CommandType type, String parameters) {
newBatch.add(new Command(type, parameters));
}
CommandType getType() {
return type;
}
void setType(CommandType type) {
this.type = type;
}
String getParameters() {
return parameters;
}
void setParameters(String parameters) {
this.parameters = parameters;
}
public List<Command> getNewBatch() {
return newBatch;
}
public void setNewBatch(List<Command> newBatch) {
this.newBatch = newBatch;
}
public Set<Command> getCommandSet() {
return commandSet;
}
public void setCommandSet(Set<Command> commandSet) {
this.commandSet = commandSet;
}
String getMsg() {
return msg;
}
public void remove(Integer id, Integer seqNo) {
for(Command c : newBatch) {
if(c.getId() == id && c.getSeqNo() == seqNo) {
newBatch.remove(c);
msg = "removed " + c;
return;
}
}
msg = String.format("%d : %d", id,seqNo);
}
}
When the Command (com)'s id and seqNo are passed via #{cb.remove(com.id,com.seqNo)} they are both 0. I also read somewhere that null values are transformed to 0's, so that would explain it. I also tried to pass the Command object directly via #{cb.remove(com)} but the Command was null when bean tried to process it.
I'm betting there is something off with the scoping, but I am too new to JSF to figure it out...
UPDATE
I have eliminated the conflicting #Named tag and have updated the html to reflect the new name of the bean, namely commandBean. Still having issues though.
you can pass the two values as request parameters:
<h:commandButton ... >
<f:param name="id" value="#{com.id}"/>
<f:param name="seqNo" value="#{com.seqNo}"/>
</h:commandButton>
and get retrieve them in managed bean like this:
HttpServletRequest request = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest());
System.out.println(request.getParameter("id"));
System.out.println(request.getParameter("seqNo"));
You're trying to get a value from a variable that is used in a for-cycle after the cycle is over. The #action is being resolved on the server side, by the time the #var is null.
You can do this:
<a4j:commandButton action="#{commandBean.remove()}" … >
<a4j:param assignTo="#{commandBean.idToRemove}" value="#{com.id}"/>
</a4j:commandButton>
The a4j:param resolves the value on client side, when the button is clicked it sends it to the server.

SelectOneMenu control not returning selected value

I am having a problem with the SelectOneMenu control. I want the the selected item to be be displayed via the valueChange Ajax event listen. But this is not happening.
However, when I change the value in the SelectOneMenu and then click on the Submit button, then selected value is getting displayed via the 'save' bean function
Cannot figure out why this is not working. Would appreciate any help on this.
Thanks.
The relevant xhtml code is as follows:
<h:form>
<h:dataTable value="#{dynamicList.myData}" var="item" >
<h:column>
<h:outputText value="#{item.oracleType}"></h:outputText>
</h:column>
<h:column>
<h:selectOneMenu value="#{item.coffeeFlavour}" rendered="#{item.showLov}" >
<f:selectItems value="#{item.coffeeList}"></f:selectItems>
<f:ajax event="valueChange" listener="#{dynamicList.listen}" ></f:ajax>
</h:selectOneMenu>
<h:inputText value="#{item.coffeeFlavour}" rendered="#{item.showText}">
</h:inputText>
</h:column>
</h:dataTable>
<p:commandButton value="Submit" action="#{dynamicList.save}" ></p:commandButton>
</h:form>
The relevant bean code is as follows:
#ManagedBean
#ViewScoped
public class DynamicList implements Serializable{
private List<OraclePrfl> oracleList=new ArrayList<OraclePrfl>();
private String coffee;
private Map<String,String> coffeeList=new LinkedHashMap<String,String>();
public List<OraclePrfl> getOracleList() {
return oracleList;
}
public List<OraclePrfl> getMyData()
{
oracleList.clear();
oracleList.add(new OraclePrfl("Oracle Lot Number",new HashMap<String,String>(){
{
put("Coffee2 - Cream Latte", "Cream Latte");
put("Coffee2 - Extreme Mocha", "Extreme Mocha");
put("Coffee2 - Buena Vista", "Buena Vista");
}
},true,false));
oracleList.add(new OraclePrfl("Oracle Product Number",new HashMap<String,String>(){
{
put("ABC", "abc");put("PQR", "pqr");put("XYZ", "xyz");
}
},true,false));
oracleList.add(new OraclePrfl("Oracle Specification",new HashMap<String,String>(){
{
put("MNP", "mnp");put("WXY", "wxy");put("XYZ", "xyz");
}
},true,false));
oracleList.add(new OraclePrfl("Address",false,true));
return oracleList;
}
public void setOracleList(List<OraclePrfl> oracleList) {
this.oracleList = oracleList;
}
public String getCoffee() {
return coffee;
}
public void setCoffee(String coffee) {
this.coffee = coffee;
}
public Map<String,String> getCoffeeList() {
coffeeList.clear();
coffeeList.put("Coffee2 - Cream Latte", "Cream Latte"); //label, value
coffeeList.put("Coffee2 - Extreme Mocha", "Extreme Mocha");
coffeeList.put("Coffee2 - Buena Vista", "Buena Vista");
return coffeeList;
}
public void setCoffeeList(Map<String,String> coffeeList) {
this.coffeeList = coffeeList;
}
public void save(){
for(OraclePrfl oracle:oracleList){
System.out.println("oracle type------"+oracle.getOracleType()+"------coffee----
"+oracle.getCoffeeFlavour());
}
}
public void listen(AjaxBehaviorEvent event){
System.out.println("calling listener "+event.getSource().toString());
for(OraclePrfl oracle:oracleList){
System.out.println("type....."+oracle.getOracleType()+"----value-----
"+oracle.getCoffeeFlavour());
}
}
}
Try removing the event:
<f:ajax listener="#{dynamicList.listen}" ></f:ajax>
It should default to event="change".

t:dataScroller not working correctly on refresh

I'm using t:dataScroller to scroll some data from a t:dataTable and it is working fine except for one thing: every time an action that causes the screen to be refreshed is triggered the t:dataScroller's index is set to 1.
To be more clear: when i'm in the second page (index == 2) and a screen refreshing action triggers, after the refresh, the data of the dataTable is still from index 2 but the dataScroller shows that the page being displayed is the first one.
I'm using the dataScroller this way:
<t:dataScroller for="myDataTable" id="myDataScroller" paginator="true"
paginatorMaxPages="#{myBean.paginatorMxPgs}"
pageCountVar="pgCount" pageIndexVar="#{myBean.curPg}"
actionListener="#{myBean.pgListener}">
<f:facet name="prv">
<h:panelGroup rendered="#{myBean.curPg > 1}" />
</f:facet>
<f:facet name="nxt">
<h:panelGroup rendered="#{myBean.curPg != pgCount}"/>
</f:facet>
</t:dataScroller>
i'm using tomahawk20-1.1.11.jar and myfaces-api-2.0.4.jar
For setting scroller to firstpage set actionlistener on submit button.
<t:commandButton actionListener="#{IFussBean.resetDataScroller}"
action="#{IFussBean.searchLocation}"
image="images/submit-button.png">
</t:commandButton>
Binding:
if it is datatable
<t:dataTable id="data"
headerClass=""
footerClass=""
rowClasses="text_holder"
columnClasses="search_img,search_txt"
var="item"
value="#{IFussBean.searchVideoList}"
preserveDataModel="false"
rows= "6"
binding="#{IFussBean.iFussData}"
>
Declare HtmlDataTable in your Bean,define its setter getter as below:
private HtmlDataTable iFussData;
Getter and setter
public HtmlDataTable getiFussData() {
return iFussData;
}
public void setiFussData(HtmlDataTable iFussData) {
this.iFussData = iFussData;
}
Now define ActionListener Method in Bean:
public void resetDataScroller(ActionEvent e) {
if(iFussData!= null) {
iFussData.setFirst(0);
}
}
Your page will set to first page when you'll do new search.
/**********************************************************************************************************************************/
if you are using <rich:dataGrid> and your scroller is <t:dataScroller> then
<rich:dataGrid
id="data"
var="item"
columns="3"
elements="6"
width="600px"
value="#{IFussBean.searchVideoList}"
binding="#{IFussBean.iFussDataGrid}"
>
Declare HtmlDataGrid in Bean:
private HtmlDataGrid iFussDataGrid;
Its getter and setter
public HtmlDataGrid getiFussDataGrid() {
return iFussDataGrid;
}
public void setiFussDataGrid(HtmlDataGrid iFussDataGrid) {
this.iFussDataGrid = iFussDataGrid;
}
Now define its action listener in Bean which will invoke on pressing command button for search :
public void resetDataScroller(ActionEvent e) {
if(iFussDataGrid != null) {
iFussDataGrid.setFirst(0);
}
}
Invoke ActionListener on command button
<h:commandButton styleClass="submit-button" actionListener="#{IFussBean.resetDataScroller}" action="#{IFussBean.searchLocation}" image="images/submit-button.png"/>
It also give desire result.

Resources