I have one p:selectManyMenu where I can choose multiple items, but I can't manage to get that values, it is always null so I'm not sure if I'm making mistake in processing components or my converter isn't good. Here is XHTML:
<h:form id="form">
<p:selectManyMenu id="advanced" value="#{pickListView.chosenItems}" converter="converterTest"
var="t" filter="true" filterMatchMode="contains" showCheckbox="true" >
<f:selectItems value="#{pickListView.allEquipment}" var="record" itemLabel="#{record.name}" itemValue="#{record}"/>
<p:column style="width:90%">
<h:outputText styleClass="f_text" value="#{t.name} - #{t.price}" />
</p:column>
</p:selectManyMenu>
<p:commandButton id="pojoSubmit" value="Spremi" oncomplete="PF('dlg').show()" actionListener="#{pickListView.saveRecords}" update=":form:table-wrapper" style="margin-top:5px" process="#this" />
<p:dialog header="Selected Values" modal="true" showEffect="fade" widgetVar="dlg" resizable="false">
<p:panelGrid columns="1" id="display" columnClasses="label,output">
<p:dataList value="#{pickListView.chosenItems}" var="t">
<h:outputText value="#{t}" />
</p:dataList>
</p:panelGrid>
</p:dialog>
</h:form>
So, my List<Equipment> chosenItems should contain selected items but is always null. I don't know what should I've done wrong, maybe it's up to converter not managing to return asObject, but I print data from converted object before return, as you can see below, and it's ok, so I'm very confused now...
Here is my Converter:
#FacesConverter(value = "converterTest")
public class ConverterTest implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value != null && value.trim().length() > 0) {
try {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Equipment o = (Equipment) session.get(Equipment.class, Integer.valueOf(value));
System.out.println("EQUIPMENT: " + o.getName() + " : " + o.getId());
return (Equipment) session.get(Equipment.class, Integer.valueOf(value));
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid equipment."));
}
}
else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object object) {
return object instanceof Equipment ?
((Equipment) object).getId().toString() : "";
}
}
In bean I created two lists, one for all items and one for selected items with their getters and setters. Problem is that chosenItems list is always null.
private List<Equipment> chosenItems;
private List<Equipment> allEquipment;
//getters and setters
Any thoughts? If you need more details, feel free to ask. Thank you in advance!
Related
I am not able to remove an item from a arraylist.
What i tried is pasted below. Cannot seem to figure out what is wrong in below code.
The xhtml is
<p:dataTable id="emaildt" styleClass="hide-column-names"
style="width:70%" rowIndexVar="rowIndex"
value="#{myBean.emailAddressList}" var="email">
<p:column style="width:15%">
<p:inputText id="email" value="#{email.email}"
validatorMessage="Invalid email" onblur="TrimString(this)">
<f:validateRegex
pattern="^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+#((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$" />
<p:ajax event="blur"
global="false" listener="#{myBean.checkEmailExist(email)}" />
</p:inputText>
</p:column>
<p:column style="width:13%">
<p:spacer width="10" rendered="#{myBean.emailAddressList.size()>'1'}"/>
<p:commandLink id="delete" immediate="true"
actionListener="#{myBean.removeEmailFromList}"
update="emaildt" process="emaildt"
rendered="#{myBean.emailAddressList.size()>'1' && false}">
<h:graphicImage value="../images/button_remove.gif" />
<f:param name="rowToRemove" value="#{rowIndex}" />
</p:commandLink>
<p:spacer width="5" rendered="#{rowIndex == myBean.emailAddressList.size()-1}"/>
<p:commandLink id="addemailbtn" immediate="true"
actionListener="#{myBean.addEmail}"
style="float:right;" update="emaildt" process="#this emaildt"
rendered="#{rowIndex == myBean.emailAddressList.size()-1}">
<h:graphicImage value="../images/addbutton.jpg" />
</p:commandLink>
</p:column>
</p:dataTable>
Create a model class EmailAddressModel with string email and its getters and setters.
MyBean code is
List<emailAddressList> emailAddressList; //make its getters and setters
#PostConstruct
public void fillPage() {
emailAddressList = new ArrayList<EmailAddressModel>();
emailAddressList.add(new EmailAddressModel());
}
public void addEmail() {
try
{
EmailAddressModel emailAddress = new EmailAddressModel();
emailAddressList.add(emailAddress);
}
catch(IndexOutOfBoundsException I) {
log.warn("FL Warning", I);
}
}
public void removeEmailFromList() {
String rowIndex = null;
try {
rowIndex = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("rowToRemove");
int index = Integer.parseInt(rowIndex);
emailAddressList.remove(index);
} catch (Exception e) {
log.warn("FL Warning", e);
}
}
Issue is -> after we add and enter the values to first and second remove, click on delete of first row, then the second row gets deleted. On debugging, the first row is gets removed in backend arraylist but in front end, the second row gets deleted.
Hope that the above information is helpful.
Check the value of what's passed to rowIndex, as Boris the Spider mentioned, Java is zero indexed.
It's likely you're returning a rowIndex of 1, when the first item is indexed at 0.
To test, In your try-catch block you could use:
int index = Integer.parseInt(rowIndex) - 1;
Got the solution added atrribute resetValues="true" to p:commandLink.
Thank you all helping me..:)
I have a problem, well when I save my object to the DB it works fine, but when i want to retrieve it from the DB doesn't work, I'm using selectItemsConverter by Omnifaces
I have my Object "Modelo" which has two other objects inside, which are "Marca" and "Gama"
These are my Java entities (the toString() is for Omnifaces):
Modelo:
private Marca marca;
private Gama gama;
getters and setters...
#Override
public String toString() {
return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
}
Marca:
getters and setters...
#Override
public String toString() {
return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
}
Gama:
getters and setters...
#Override
public String toString() {
return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
}
Well and this is my managedBean
ModeloBean
#ManagedBean
#ViewScoped
public class ModeloBean {
private Modelo modelo = new Modelo();
getters and setters ...
//This is for call the DB to retrieve the value, and works fine, but i cant show the preselected value to the xhtml
public void leer(Modelo mo) throws Exception {
ModeloDAO dao = new ModeloDAO();
try {
this.init();
this.modelo = dao.leer(mo);
} catch (Exception e) {
throw e;
} finally {
dao = null;
}
}
This is my xhtml Page
I have a dialog which I used it for save and update an object
<p:dialog id="dlgDatos" widgetVar="wdlgDatos" modal="true" appendToBody="true" header="#{modeloBean.accion}" draggable="false" resizable="false">
<h:form>
<h:panelGrid columns="2">
<p:outputLabel value="Marca" />
<p:selectOneMenu value="#{modeloBean.modelo.marca}" converter="omnifaces.SelectItemsConverter" filter="true" filterMatchMode="startsWith" required="true">
<f:selectItem itemLabel="Seleccione" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{marcaBean.lstMarcasVigentes}" var="marca" itemLabel="#{marca.nombre}" itemValue="#{marca}" />
</p:selectOneMenu>
<p:outputLabel value="Gama" />
<p:selectOneMenu value="#{modeloBean.modelo.gama}" converter="omnifaces.SelectItemsConverter" filter="true" filterMatchMode="startsWith" required="true">
<f:selectItem itemLabel="Seleccione" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{gamaBean.lstGamasVigentes}" var="gama" itemLabel="#{gama.nombre}" itemValue="#{gama}" />
</p:selectOneMenu>
<p:outputLabel for="txtNombre" value="Modelo" />
<p:column>
<p:inputTextarea id="txtNombre" value="#{modeloBean.modelo.nombre}" />
<p:watermark for="txtNombre" value="Para registrar varios modelos, sepárelos por comas (,)" />
</p:column>
<p:outputLabel value="Vigencia" rendered="#{modeloBean.accion eq 'Modificar'}"/>
<p:selectBooleanCheckbox value="#{modeloBean.modelo.vigencia}" rendered="#{modeloBean.accion eq 'Modificar'}"/>
<p:commandButton value="#{modeloBean.accion}" actionListener="#{modeloBean.operar()}" oncomplete="PF('wdlgDatos').hide(); PF('wdtLista').clearFilters();" update=":frmLista:dtLista, :msj"/>
<p:commandButton value="Cancelar" immediate="true" onclick="PF('wdlgDatos').hide();"/>
</h:panelGrid>
</h:form>
</p:dialog>
The selectOneMenu works fine for save, but for update only retrieve me the Strings value and not the preselected value of my comboBoxes
This is the dialog which only retrieve the String value of "105" cause is a String and my boolean value for the checkbox "Vigencia" but not my comboBoxes values. Where am I wrong?
I solved it adding this to my entites (hashCode and equals)
#Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + this.codigo;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Modelo other = (Modelo) obj;
if (this.codigo != other.codigo) {
return false;
}
return true;
}
I have 2 selectOneMenu, second one is depend on first. When I choose an element on first, the second select load right, but I want to clean the second select (and other elements) when I choose default element, Seleccione marca, on first select. I'm using converter. The code:
<p:selectOneMenu id="marcas" value="#{adminBean.marca}" converter="categoriaConverter" required="true">
<f:selectItem itemLabel="Seleccione marca" itemValue="" />
<f:selectItems value="#{categoriaBean.marcas}" var="cat" itemLabel="#{cat.nombre}" itemValue="#{cat}" />
<p:ajax listener="#{adminBean.loadTipos}" update="tipos" />
</p:selectOneMenu>
<p:selectOneMenu id="tipos" value="#{adminBean.tipo}" converter="categoriaConverter" required="true">
<f:selectItem itemLabel="Seleccione tipo" itemValue="" />
<f:selectItems value="#{adminBean.tipos}" var="tip" itemLabel="#{tip.nombre}" itemValue="#{tip}" />
<p:ajax listener="#{adminBean.loadProductos}" update=":formTablaProductos" />
</p:selectOneMenu>
This is my categoriaConverter:
#FacesConverter(value = "categoriaConverter")
public class CategoriaConverter implements Converter {
CategoriaBeanLocal categoriaBean = lookupCategoriaBeanLocal();
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
Categoria categoria = null;
if (value != null && !value.equals("") && !value.contains("Seleccione"))
categoria = categoriaBean.findByIdCategoria(Integer.valueOf(value));
return categoria;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
String salida = null;
if (value != null && !value.equals("") && !value.equals("0"))
salida = String.valueOf(((Categoria)value).getIdCategoria());
return salida;
}
private CategoriaBeanLocal lookupCategoriaBeanLocal() {
try {
Context c = new InitialContext();
return (CategoriaBeanLocal) c.lookup("java:global/TiendaOnline/TiendaOnline-ejb/CategoriaBean!ejb.CategoriaBeanLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
lookupCategoriaBeanLocal() was autogenerated using Call Enterprise Bean in NetBeans. As can be seen, I compare value in getAsObject with 'Seleccione', that's the itemLabel in my first selectOneMenu, I don't know why send that.
More code, this is my loadTipos():
public void loadTipos() {
if (marca != null) {
tipos = categoriaBean.findByIdCategoriaPadre(marca.getIdCategoria());
} else {
tipos.clear();
}
}
The thing is that when I choose Seleccione marca don't get to loadTipos(), and nothing is updated, and I don't know why. Anyone can see the problem?
Greetings.
When I print the selected item in the console , it is always returned as null
here is the method that create the SelectItem in my ManagedBean:
public List<String> getlisteMatricule() throws HibernateException
{
List<String> matricules = new ArrayList<String>();
for (Vehicule v : vehiculedao.getAll())
{
matricules.add(v.getMatricule());
System.out.println(v.getMatricule());
}
return matricules ;
}
public List<SelectItem> getAllMatricules()
{
List<SelectItem> options = new ArrayList<SelectItem>();
List<String> listMatricules = getlisteMatricule();
for (String mat : listMatricules)
{
options.add(new SelectItem(mat));
System.out.println("items = " + new SelectItem(mat));
}
return options ;
}
And here is my variables in my model which contain the getter and the setters and the constructor:
public class Program
{
private int id_progf;
private int nbrHeure;
private float montantGlobal;
private String commentaire;
private int cin_mon;
private String matricule;
private int cin_cand;
///gettersand setters
.... }
The methode that bring the variables from the database (List)
#Override
public Vehicule getMatricule(String matricule) {
Session session = HibernateUtil.currentSession();
Vehicule v=(Vehicule)session.get(Vehicule.class, matricule);
return v;
}
And finally my xhtml file, it contains the form:
<h:panelGrid columns="2" >
<h:outputText value="Moniteur :" />
<h:selectOneMenu id="listeNomPrenom" title="Nom et Prenom" value="{#programMB.np}">
<f:selectItems value="#{moniteurMB.allNomPrenom}" />
</h:selectOneMenu>
<h:outputText value="Vehicule :" />
<h:selectOneMenu id="ListeMatricules" title="Matricules" value="{#programMB.program.matricule}">
<f:selectItems value="#{vehiculeMB.allMatricules}" />
</h:selectOneMenu>
<h:outputText value="Nombre heures:" />
<p:inputText value="#{programMB.program.nbrHeure}" />
</h:panelGrid>
<p:commandButton value="Save" action="#{programMB.ajouterProg}" />
In the first look, I saw the problem is in the value attribute of both of your selectOneMenu bellow:
<h:selectOneMenu id="listeNomPrenom" title="Nom et Prenom" value="{#programMB.np}">
<f:selectItems value="#{moniteurMB.allNomPrenom}" />
</h:selectOneMenu>
and:
<h:selectOneMenu id="ListeMatricules" title="Matricules" value="{#programMB.program.matricule}">
<f:selectItems value="#{vehiculeMB.allMatricules}" />
</h:selectOneMenu>
In both of them you just putted # in the wrong place. change value="{#programMB.np}" to value="#{programMB.np}" and value="{#programMB.program.matricule}" to value="#{programMB.program.matricule}" and it should work for you!
I am working on an application using JSF 2.1 and PrimeFaces 3.2, server Tomcat 7. Right now, I am working on form to register new users. The problem is in converter.
I use few standard fields and two of them are passwords. I have custom data type for password, so I want to use converter to convert String data from field to Password variable in a bean. Primefaces forms use AJAX after submit, and there is probably the problem. If I fill in the form completely, without validation errors, everything works fine. But if there is a validaton error and no converter error (I check for the password length in the converter), whole form stops working at all. I have to refresh page to have it working again.
Here are some sources:
Password class:
public class Password {
public static final short MIN_LENGTH = 5;
private String text;
private String hash;
public Password(String text) {
this.text = text;
this.hash = Hasher.sha512(text);
}
/**
* Get password instance with known hash only
* #param hash SHA-512 hash
* #return Password instance
*/
public static Password getFromHash(String hash) {
Password password = new Password(null);
password.hash = hash;
return password;
}
#Override
public int hashCode() {
return hash.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Password other = (Password) obj;
if ((this.hash == null) ? (other.hash != null) : !this.hash.equals(other.hash)) {
return false;
}
return true;
}
#Override
public String toString() {
return hash;
}
/**
* #return the text
*/
public String getText() {
return text;
}
}
Password converter:
#FacesConverter(forClass = Password.class)
public class PasswordConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
String text = (String) value;
if (text.length() >= Password.MIN_LENGTH) {
return new Password(text);
}
FacesMessage msg = new FacesMessage(Texter.get("forms/forms", "shortPassword").replace("%limit%", String.valueOf(Password.MIN_LENGTH)));
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ConverterException(msg);
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
try {
Password password = (Password) value;
return password.getText();
} catch (Exception ex) {
throw new ConverterException(ex);
}
}
}
The form in facelet:
<h:form id="registration">
<p:panelGrid columns="3">
<h:outputLabel value="#{commonTxt.email}:" for="email" />
<p:inputText id="email" value="#{userRegistrationForm.email}" required="true" requiredMessage="#{formsTxt.msgEmpty}">
<f:validator validatorId="email" />
<f:validator validatorId="unique" />
<f:attribute name="entity" value="SystemUser" />
<f:attribute name="field" value="email" />
<f:attribute name="uniqueMessage" value="#{formsTxt.nonUniqueEmail}" />
</p:inputText>
<p:message for="email" />
<h:outputLabel value="#{usersTxt.password}:" for="password" />
<p:password id="password" value="#{userRegistrationForm.password}" binding="#{password}" autocomplete="off" feedback="true" weakLabel="#{formsTxt.passwordWeak}" goodLabel="#{formsTxt.passwordGood}" strongLabel="#{formsTxt.passwordStrong}" promptLabel="#{formsTxt.passwordPrompt}" />
<p:message for="password" />
<h:outputLabel value="#{usersTxt.passwordCheck}:" for="passwordCheck" />
<p:password id="passwordCheck" value="#{userRegistrationForm.passwordCheck}" binding="#{passwordCheckInput}" autocomplete="off">
<f:validator validatorId="match" />
<f:attribute name="matchAgainst" value="#{password}" />
<f:attribute name="matchMessage" value="#{formsTxt.passwordMismatch}" />
</p:password>
<p:message for="passwordCheck" />
<p:column /><p:column /><p:column />
<h:outputLabel value="#{usersTxt.name}:" for="name" />
<p:inputText id="name" value="#{userRegistrationForm.name}" maxlength="255" required="true" requiredMessage="#{formsTxt.msgEmpty}" />
<p:message for="name" />
<f:facet name="footer">
<p:commandButton value="#{usersTxt.register}" action="#{userRegistrationForm.register()}" update="registration" />
</f:facet>
</p:panelGrid>
</h:form>
I won't post code of the bean #{userRegistrationForm}, there are two Passwords properties with getters and setters.
Any help leading to solution of my problem appreciated. Thanks in advance.
Solved! I just used FacesContext.getCurrentInstance().isValidationFailed() to see if the validation failed or not. In case of failure, the converter now returns null (the conversion won't be done), in other case the converter will return proper object. And the form works fine with the conversion working.