This question already has answers here:
How to inject #EJB, #PersistenceContext, #Inject, #Autowired, etc in #FacesConverter?
(5 answers)
Closed 7 years ago.
I am trying to get from selectOneMenu an object that has fields such as first name, last name and so on. This is my form:
<h:form>
<p:outputLabel value="Persons: " />
<p:selectOneMenu value="#{personBean.person}">
<f:selectItem itemLabel="Select Person" itemValue="" noSelectionOption="true"/>
<f:selectItems itemLabel="#{person.firstName}" itemValue="#{person}" var="person" value="#{personBean.persons}" />
</p:selectOneMenu>
<br /><br />
<p:commandButton value="Submit"
action="#{personBean.showSomething()}" icon="ui-icon-check" />
I don't understand.. where am i going wrong? How can i get that object?
I've been trying for a few days but i haven't managed to fix this problem...
I tried using a Converter but i kept getting NPEs.
EDIT
This is my converter:(I am trying to get the object from my postgres db with the help of my DAO)
#Named
#FacesConverter(forClass=Person.class)
public class PersonConverter implements Converter {
#Inject
private PersonDao personDao;
#Override
public Object getAsObject(FacesContext arg0, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
Person p = personDao.findById(Long.valueOf(submittedValue));
return p;
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid Person ID"), e);
}
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
if (arg2 == null) {
return "";
}
if (arg2 instanceof Person) {
return String.valueOf(((Person) arg2).getId());
} else {
throw new ConverterException(new FacesMessage(arg2 + " is not a valid Person"));
}
}
}
This is where i get a NPE Person p = personDao.findById(Long.valueOf(submittedValue));
The find() method works anywhere else...
When i used the debugger i noticed that personDao is null. How can i fix this?
In the page:
<p:selectOneMenu value="#{personBean.person}">
<f:selectItem itemLabel="Select Person" itemValue="" noSelectionOption="true"/>
<f:selectItems itemLabel="#{person.firstName}" itemValue="#{person}" var="person" value="#{personBean.persons}" />
<f:converter binding="#{personConverter}" />
<f:attribute name="attrpersons" value="#{personBean.persons}" />
</p:selectOneMenu>
In the Person bean:
You must implement toString and equals methods.
And finally you have to add the converter class:
#Named
public class PersonConverter implements Converter{
public PersonConverter(){}
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
List<Person> persons = (List<Person>)component.getAttributes().get("attrpersons");
if (submittedValue.trim().equals("")) {
return null;
} else {
Iterator<Person> it = persons.iterator();
while(it.hasNext()){
Person p = it.next();
if(p.toString().equals(submittedValue))
return p;
}
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if (value == null) {
return "";
} else {
return value.toString();
}
}
}
Related
I am using selectCheckboxMenu from Primefaces in a JSF project, the problem is that the "selectedDepartments" object in the Bean is always empty.
Here is the code:
Xhtml Page
<p:selectCheckboxMenu id="menu" label="name" style="width: 15rem" converter="#{departmentConverter}" value="#{StudentMB.selectedDepartments}"
multiple="true" filter="true" filterMatchMode="startsWith" panelStyle="width: 15rem" scrollHeight="250" >
<c:selectItems value="#{StudentMB.departmentList}" var="department" itemLabel="#{department.name}" itemValue="#{department}"/>
<p:ajax event="change" process="#this" update=":form2:dt-Students" global="false"/>
</p:selectCheckboxMenu>
The converter for selectCheckboxMenu:
#Named
#FacesConverter(value = "departmentConverter")
public class departmentConverter implements Converter {
#Inject
private departmentDAO departmentDAO;
#Override
public department getAsObject(FacesContext context, UIComponent component, String value) {
if (value != null && value.trim().length() > 0) {
try {
department c= departmentDAO.getdepartmentById(Integer.parseInt(value));
return c;
}
catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid country."));
}
}
else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
department c=(department)value;
return String.valueOf(c.getId());
}
else {
return null;
}
}
}
The code of the Managed Bean
public class StudentMB implements Serializable{
private LazyDataModel<Student> lazyModel = null;
private List<department> departmentList;
private List<department> selectedDepartments;
#Inject
private departmentDAO departmentDAO;
#PostConstruct
public void init() {
this.selectedDepartments= new ArrayList<>();
this.departmentList= new ArrayList<>();
this.departmentList = this.departmentDAO.listDepartments();
lazyModel = new StudentLazyList(StudentDAO){
#Override
public List<Student> load(int first, int pageSize, Map<String, SortMeta> sortBy, Map<String, FilterMeta> filterBy) {
return load2(first, pageSize, sortBy, filterBy,selectedDepartments);
}
};
}
}
Thanks for help.
The solution is found for those who encounter the same problem. it was relative to the converter, indeed I don't know why we have to use a converter when it comes to a Pojo class because we already mentioned the name of class in the value property of selectItems.
Nevermind , here is the code that works
The selectCheckboxMenu component
<h:form id="form1">
<p:selectCheckboxMenu id="menu" label="department" converter="departmentConverter" value="#{studentMB.selectedDepartments}"
multiple="true" filter="true" filterMatchMode="startsWith" style="width: 15rem" panelStyle="width: 15rem" scrollHeight="250" >
<c:selectItems value="#{studentMB.departmentList}" var="department" itemLabel="#{department.name}" itemValue="#{department}"/>
<p:ajax event="change" update=":form2:dt-students"/>
</p:selectCheckboxMenu>
</h:form>
The converter class
#Named
#FacesConverter(value = "departmentConverter")
public class DepartmentConverter implements Converter {
#Override
public Department getAsObject(FacesContext context, UIComponent component, String value) {
if(value == null)
return null;
StudentMB data = context.getApplication().evaluateExpressionGet(context, "#{studentMB}", StudentMB.class);
int actualId=Integer.parseInt(value);
for(Department dep : data.getDepartmentList())
{
if(categ.getId()==actualId)
return dep;
}
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid department."));
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
Department c=(Department)value;
return String.valueOf(c.getId());
}
else {
return null;
}
}
}
Hope this help
We have a #{object.amount} equal to 0.003 and we would like to display it as 3‰ (With the permille operator)
We also would like to convert the value of an inputText to permille. (e.g: a user input of 3 will store 0.003)
The f:convertNumber allow us to convert to the type % but not ‰ :
<h:outputText value="#{object.amount}" >
<f:convertNumber type="percent" />
</h:outputText>
How can we display a value permille in an outputText and convert a value to a permille in an inputText ?
Like Kukeltje suggested, you can implement a custom converter, for example:
#FacesConverter("permilleConverter")
public class PermilleConverter implements Converter {
private static final String PERMILLE_SYMBOL = "‰";
private static final int PERMILLE_FACTOR = 1000;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null) {
return null;
}
return getDoubleValue(value) / PERMILLE_FACTOR;
}
private Double getDoubleValue(String value) {
NumberFormat nf = new DecimalFormat();
Double doubleValue;
try {
Number number = nf.parse(value);
doubleValue = number.doubleValue();
} catch (ParseException e) {
throw new ConverterException("no valid format");
}
return doubleValue;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null;
}
double amount = (double) value;
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(0);
return nf.format(amount * PERMILLE_FACTOR) + PERMILLE_SYMBOL;
}
}
And use it like this:
<h:form>
<h:outputText value="#{userBean.amount}">
<f:converter converterId="permilleConverter" />
</h:outputText>
<h:inputText value="#{userBean.amount}">
<f:converter converterId="permilleConverter" />
</h:inputText>
<h:commandButton value="test">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
</h:form>
This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 6 years ago.
In my JSF application using RichFaces, I have a screen with rich:dataTable
that displays my objects, and a column that refers to another page, with the details of the selected record so that it can be used.
In this second page, after completing the requested data, when running submit, the validation returns the message:
:Value is not a valid option.
Look that, unlike the problem cited in this post, the name of the problem field is not being displayed.
During debugging, I noticed that in the selecionarEmitente() method, the object localidade is null. If I made the set on the dataTable page and the name of the selected object appears on the secondPage, what is missing?
I already researched other posts about this problem. For example, according to this post, my javabeans involved have the equals() and hashCode() methods. Unlike this other post, I'm using custom converters.
Where is my mistake?
I'm using RichFaces 4.5.1.Final, MyFaces 2.2.10, Spring 3.1.1 .
dataTable.xhtml
<h:selectOneMenu id="estado"
immediate="true" validator="#{validadorMB.validarEstado}"
converter="estadoConverter">
<f:selectItem itemLabel="---" />
<f:selectItems value="#{localidadeMB.estados}"
var="est" itemValue="#{est}" itemLabel="#{est.uf}" />
<a4j:ajax event="change" actionListener="#{localidadeMB.filtrarUF}" render="table" />
</h:selectOneMenu>
<a4j:region id="region" immediate="true">
<rich:dataTable id="tabela"
value="#{localidadeMB.getLocalidadesPorUF()}" var="loc"
rowKeyVar="row" rows="20" width="800px" render="scroller">
<rich:column id="col_localidade" sortBy="#{loc.nome}" filterBy="#{loc.nome}">
<h:outputText id="nomeLocalidade" value="#{loc.nome}" />
</rich:column>
...
<rich:column>
<h:commandLink id="declaracaolink" action="#{localidadeMB.carregarLocalidade}">
<h:graphicImage url="/img/declaracao.png" />
<f:setPropertyActionListener value="#{loc}" target="#{localidadeMB.localidade}" />
</h:commandLink>
</rich:column>
</rich:dataTable>
</a4j:region>
secondPage.xhtml
<h:body>
<h:form id="formDeclaracao" focus="estado">
<h:panelGrid columns="2" columnClasses="labelFormulario">
<h:outputLabel value="UF" for="estado" />
<h:selectOneMenu id="estado"
value="#{localidadeMB.localidade.estado}"
label="#{localidadeMB.localidade.estado.uf}"
valueChangeListener="#{localidadeMB.selecionarEstado}"
validator="#{validadorMB.validarEstado}" immediate="true"
converter="estadoConverter"
style="width: 45px;" styleClass="listbox">
<f:selectItems value="#{localidadeMB.estados}"
var="est" itemValue="#{est}" itemLabel="#{est.uf}" />
<a4j:ajax event="change" render="nomeLocalidade" />
</h:selectOneMenu>
<h:outputLabel value="Nome da localidade:" for="nomeLocalidade" />
<h:selectOneMenu id="nomeLocalidade"
value="#{localidadeMB.localidade}"
label="#{localidadeMB.localidade.nome}" immediate="true"
valueChangeListener="#{localidadeMB.selecionarLocalidade}"
validator="#{validadorMB.validarLocalidade}"
converter="localidadeConverter"
style="width: 220px;" styleClass="listbox">
<f:selectItems value="#{localidadeMB.localidades}"
var="loc" itemValue="#{loc}" itemLabel="#{loc.nome}" />
</h:selectOneMenu>
<h:outputLabel value="Interessado:" for="interessado" />
<h:inputText id="interessado" value="" required="true"
requiredMessage="xxxxxxxxx" immediate="true"
styleClass="listbox" style="width: 215px;">
</h:inputText>
<h:outputLabel value="Solicitante:" for="solicitante" />
<h:inputText id="solicitante" value="" required="true"
requiredMessage="xxxxxxxxxxxxx" immediate="true">
</h:inputText>
<h:outputLabel value="Documento apresentado:" for="documento" />
<h:inputText id="documento" value="" required="true"
requiredMessage="xxxxxxxxxxxxx" immediate="true">
</h:inputText>
<h:outputLabel value="Emitente:" for="emitente" />
<h:selectOneMenu id="emitente"
value="#{localidadeMB.emitente}"
label="#{localidadeMB.emitente.descricaoReduzida}"
valueChangeListener="#{localidadeMB.selecionarEmitente}"
validator="#{validadorMB.validarEmitente}"
converter="emitenteConverter">
<f:selectItem itemLabel="---" />
<f:selectItems value="#{localidadeMB.emitentes}" var="em" itemValue="#{em}" itemLabel="#{em.descricaoReduzida}" />
</h:selectOneMenu>
<h:commandButton id="btnGerarDeclaracao" value="Get PDF"
action="#{localidadeMB.getPDF()}" style="width: 84px;" />
</h:panelGrid>
</h:form>
</h:body>
ManagedBean
#ManagedBean
public class LocalidadeMB{
private Emitente emitente;
private Estado estado;
private Localidade localidade;
public String carregarLocalidade() {
estado = localidade.getEstado();
localidade = getLocalidade();
getLocalidades();
carregarLocalidadePorUF(estado);
return "secondPage.xhtml";
}
public void filtrarUF(ActionEvent action) {
try {
String uf = JSFHelper.getRequestParameter("formConsulta"
+ UINamingContainer.getSeparatorChar(JSFHelper
.getFacesContext()) + "estado");
estado = estadoFacade.getEstado(Integer.parseInt(uf));
} catch (Exception e) {
...
}
}
public List<Emitente> getEmitentes() {
try {
return emitenteFacade.getEmitentes();
} catch (Exception e) {
...
}
}
public List<Emitente> getEstados() {
try {
return estadoFacade.getEstados();
} catch (...) {
...
}
}
public List<Localidade> getLocalidades() {
try {
return localidadeFacade.getLocalidades();
} catch (Exception e) {
...
}
}
public List<Localidade> getLocalidadesPorUF() {
try {
String uf = JSFHelper.getRequestParameter("formConsulta"
+ UINamingContainer.getSeparatorChar(JSFHelper
.getFacesContext()) + "estado");
if ((uf != null) && (!uf.equals("---"))) {
estado = estadoFacade.getEstado(Integer.parseInt(uf));
return localidadeFacade.getLocalidadesPorEstado(estado);
} else {
return null;
}
} catch (Exception e) {
...
}
}
public void selecionarEmitente(ValueChangeEvent evento) {
emitente = (Emitente)evento.getNewValue();
}
public void selecionarEstado(ValueChangeEvent evento) {
estado = (Estado)evento.getNewValue();
}
public void selecionarLocalidade(ValueChangeEvent evento) {
localidade = (Localidade)evento.getNewValue();
}
}
Validator
#ManagedBean(name = "validadorMB")
public class ValidadorLocalidadeMB {
public void validarEmitente(FacesContext context, UIComponent componentToValidate, Object value) throws ValidatorException {
if (((Emitente) value).getEmitenteId() == 0) {
FacesMessage msg = new FacesMessage(null, "Selecione o emitente");
throw new ValidatorException(msg);
}
}
public void validarEstado(FacesContext context, UIComponent componentToValidate, Object value) throws ValidatorException {
if (((Estado) value).getEstadoId() == 0) {
FacesMessage msg = new FacesMessage(null, "Selecione uma UF");
throw new ValidatorException(msg);
}
}
public void validarLocalidade(FacesContext context, UIComponent componentToValidate, Object value) throws ValidatorException {
if (((Localidade) value).getLocalidadeId() == 0) {
FacesMessage msg = new FacesMessage(null, "Selecione uma localidade");
throw new ValidatorException(msg);
}
}
}
Converters
#FacesConverter(value = "emitenteConverter")
public class EmitenteConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent ui, String value) throws ConverterException {
ValueExpression vex = context
.getApplication()
.getExpressionFactory()
.createValueExpression(context.getELContext(),
"#{emitenteFacade}", EmitenteFacadeImpl.class);
EmitenteFacadeImpl fac = (EmitenteFacadeImpl) vex.getValue(context
.getELContext());
try {
return fac.getEmitentePorId(Integer.valueOf(value));
} catch (NumberFormatException | DAOException e) {
....
}
}
#Override
public String getAsString(FacesContext context, UIComponent ui, Object value) throws ConverterException {
if (value == null) {
return "";
}
if (value instanceof Emitente) {
return String.valueOf(((Emitente) value).getEmitenteId());
}
}
}
#FacesConverter(value = "estadoConverter")
public class EstadoConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent ui, String value) throws ConverterException {
ValueExpression vex = context
.getApplication()
.getExpressionFactory()
.createValueExpression(context.getELContext(),
"#{estadoFacade}", EstadoFacadeImpl.class);
EstadoFacadeImpl fac = (EstadoFacadeImpl) vex.getValue(context
.getELContext());
try {
return fac.getEstadoPorId(Integer.valueOf(value));
} catch (NumberFormatException | DAOException e) {
....
}
}
#Override
public String getAsString(FacesContext context, UIComponent ui, Object value) throws ConverterException {
if (value == null) {
return "";
}
if (value instanceof Estado) {
return String.valueOf(((Estado) value).getEstadoId());
}
}
}
#FacesConverter(value = "localidadeConverter")
public class LocalidadeConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent ui, String value) throws ConverterException {
ValueExpression vex = context
.getApplication()
.getExpressionFactory()
.createValueExpression(context.getELContext(),
"#{localidadeFacade}", LocalidadeFacadeImpl.class);
LocalidadeFacadeImpl fac = (LocalidadeFacadeImpl) vex.getValue(context.getELContext());
try {
return fac.getLocalidadePorId(Integer.valueOf(value));
} catch (NumberFormatException | DAOException e) {
....
}
}
#Override
public String getAsString(FacesContext context, UIComponent ui, Object value) throws ConverterException {
if (value == null) {
return "";
}
if (value instanceof Localidade) {
return String.valueOf(((Localidade) value).getLocalidadeId());
}
}
}
Your problem might be with this line:
value="#{(localidadeMB.localidade.localidadeId != null) ? localidadeMB.localidade.localidadeId :localidadeMB.localidade}"
The value of a <h:selectOneMenu> should be a simple property, not an expression, as it has to set.
Edit:
There could be another problem with your code:
You construct those SelectItems with the entity's ID as the value property, and then use converter to convert String to/from the entity itself.
Thus there are a few possibilities for you:
Use the converter, and the "whole" entity as the value of SelectItem.
Or don't use Selectitems, but a List of the entities themselves, as your first link does.
The other possibility is to use a dummy entity, set its id property, and in your valueChangeListener retrieve the entity by the ID.
The list passed to the select's value is of Integer type.
<p:selectManyMenu id="estabelecimentos" value="#{questionarioMB.estabelecimentosIds}" var="e" converter="#{estabelecimentoConverter}" style="width:100%" filter="true" filterMatchMode="contains" showCheckbox="true">
<f:selectItems value="#{questionarioMB.estabelecimentos}" var="estabelecimento" itemValue="#{estabelecimento}" itemLabel="#{estabelecimento.nomefantasia}" />
<p:column>
<h:outputText value="#{estabelecimentoMB.getIdentificadorByEstabelecimentoId(e.id)}" />
</p:column>
<p:column>
<h:outputText value="#{e.nomefantasia}" />
</p:column>
</p:selectManyMenu>
Netbeans cannot find the attributes in the outputTexts ("unknown property") and the line throwing the exception is the following:
this.estabelecimentosIds.parallelStream().forEach((Integer id) -> {
this.questionarioBean.insertQuestionarioHasEstabelecimento(this.questionarioBean.getLastId() + 1, id);
});
The converter:
#Named
public class EstabelecimentoConverter implements Converter {
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if (value != null && value.trim().length() > 0) {
try {
EstabelecimentoMB estabelecimentoMB = (EstabelecimentoMB) fc.getExternalContext().getApplicationMap().get("estabelecimentoMB");
return estabelecimentoMB.getEstabelecimentos().get(Integer.parseInt(value));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro de Conversão", "Estabelecimento inválido."));
}
} else {
return null;
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object o) {
if (o != null) {
return String.valueOf(((Estabelecimento) o).getId());
} else {
return null;
}
}
}
P.S.: I can't use the field tradingName because it can be repeated in table establishment, so I must use the "id" to differentiate them. The first column has the identifier for that establishment (in another table, "client_has_establishment", and can be repeated as well - but not for the same client_id).
Based on BalusC's answer here: https://stackoverflow.com/a/13866179/1639141
Changed the converter to JSF builtin IntegerConverter:
<p:selectManyMenu ... converter="javax.faces.Integer">
Here is my SelectOneMenu
<h:selectOneMenu value="#{bean.myObject}" >
<f:ajax render="componentToRender" listener="#{bean.onSelect}"/>
<f:converter converterId="myObjectConverter" />
<f:selectItem itemLabel="None" itemValue="#{null}" />
<f:selectItems value="#{bean.objects}" var="object" itemValue="#{object}" itemLabel="#{object.name}" />
</h:selectOneMenu>
And my converter
#FacesConverter("myObjectConverter")
public class MyObjectConverter implements Converter{
private List<MyObject> objects;
public MyObjectConverter(){
this.objects = MyController.getAllMyObjects();
}
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(!StringUtils.isInteger(value)) {
return null;
}
return this.getMyObject(value);
}
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null) {
return null;
}
return String.valueOf(((MyObject) value).getId()).toString();
}
public MyObject getMyObject(String id) {
Iterator<MyObject > iterator = this.objects.iterator();
while(iterator.hasNext()) {
MyObject object = iterator.next();
if(object.getId() == Integer.valueOf(id).intValue()) {
return object;
}
}
return null;
}
}
The problem is that my ajax listener is never called and my component never rendered.
Is there something wrong with my converter or selectOneMenu? I follow an example and I can't figure the mistake out.
BTW : my simple method in the bean
public void onSelect() {
System.out.println(this.myObject);
if(this.myObject != null) {
System.out.println(this.myObject.getName());
}
}
I already had a problem like this and I changed my selected value from object to id. But here I want to make it work with objects because I know it's possible.
Thanks
I have the solution. I had to override the "equals" method in MyObject class!
Thanks.
EDIT: the code
#Override
public boolean equals(Object obj) {
if(this.id == ((MyObject) obj).id) {
return true;
}else {
return false;
}
}