ClassCastException in selectManyMenu - Integer cannot be cast to String - jsf

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">

Related

Why selected items is always empty in the Bean for Primefaces selectCheckboxMenu

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

JSF 2 convertNumber permille

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>

JSF - "Value is not a valid option" for unknown reason >> To re-evaluate 'duplicate' [duplicate]

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.

#Inject PersonDao is null in #FacesConverter class [duplicate]

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();
}
}
}

Creating JSF 2.2 Custom Component Dynamically

I've written (well, modified) a custom component for radio buttons appearing inside a datatable based on this article. I've modified it slightly for JSF 2.2 by using the #FacesRenderer and #FacesComponent tags and omitting the custom tag class. Everything works fine in my XHTML page
xmlns:custom="http://mynamespace"
...
<h:dataTable id="mySampleTable3"
value="#{myBackingBean.sampleTable3}"
var="item"
width="100%"
border="1"
first="0">
<f:facet name="header">
<h:panelGrid id="gridHeader3" columns="2" width="100%" >
<h:outputText id="outputText3"
value="Radios grouped in row(With our custom tag)"/>
</h:panelGrid>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Emp Name" />
</f:facet>
<h:outputText id="empName" value="#{item.empName}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Excellent" />
</f:facet>
<custom:customradio id="myRadioId2"
name="myRadioRow"
value="#{item.radAns}"
itemValue="E" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Good" />
</f:facet>
<custom:customradio id="myRadioId3"
name="myRadioRow"
value="#{item.radAns}"
itemValue="G" />
</h:column>
...
</h:dataTable>
and the datatable of radio buttons work correctly (they are grouped by row). The problem arises when I use this component dynamically. So I have
HtmlPanelGrid radioGrid = (HtmlPanelGrid) getApplication()
.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
...
UICustomSelectOneRadio customSelectOneRadio = (UICustomSelectOneRadio) getApplication().
createComponent(UICustomSelectOneRadio.COMPONENT_TYPE);
customSelectOneRadio.setId("rb_" + question.getQuestionId() + "_" + row + "_" + col);
customSelectOneRadio.setName("myRadioRow");
String binding = "#{" + beanName + "." + propName +
"[\"" + question.getQuestionId().toString() + "_" +
subQuestion.getId() + "\"]}";
ValueExpression ve = getExpressionFactory().
createValueExpression(getELContext(), binding, String.class);
customSelectOneRadio.setValueExpression("value", ve);
customSelectOneRadio.setItemValue(value);
radioGrid.getChildren().add(customSelectOneRadio);
Unfortunately, although the datatable is rendered, the radio buttons aren't. Blank columns appear. I was wondering if anyone knows if there is some method I should be overriding in my renderer. Mine looks like:
#FacesRenderer(componentFamily = UICustomSelectOneRadio.COMPONENT_FAMILY, rendererType = HTMLCustomSelectOneRadioRenderer.RENDERER_TYPE)
public class HTMLCustomSelectOneRadioRenderer extends Renderer {
public static final String RENDERER_TYPE = "com.myapp.jsf.renderers.HTMLCustomSelectOneRadioRenderer";
#Override
public void decode(FacesContext context, UIComponent component) {
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
UICustomSelectOneRadio customSelectOneRadio;
if (component instanceof UICustomSelectOneRadio) {
customSelectOneRadio = (UICustomSelectOneRadio) component;
} else {
return;
}
Map map = context.getExternalContext().getRequestParameterMap();
String name = getName(customSelectOneRadio, context);
if (map.containsKey(name)) {
String value = (String) map.get(name);
if (value != null) {
setSubmittedValue(component, value);
}
}
}
private void setSubmittedValue(UIComponent component, Object obj) {
if (component instanceof UIInput) {
((UIInput) component).setSubmittedValue(obj);
}
}
private String getName(UICustomSelectOneRadio customSelectOneRadio,
FacesContext context) {
UIComponent parentUIComponent
= getParentDataTableFromHierarchy(customSelectOneRadio);
if (parentUIComponent == null) {
return customSelectOneRadio.getClientId(context);
} else {
if (customSelectOneRadio.getOverrideName() != null
&& customSelectOneRadio.getOverrideName().equals("true")) {
return customSelectOneRadio.getName();
} else {
String id = customSelectOneRadio.getClientId(context);
int lastIndexOfColon = id.lastIndexOf(":");
String partName = "";
if (lastIndexOfColon != -1) {
partName = id.substring(0, lastIndexOfColon + 1);
if (customSelectOneRadio.getName() == null) {
partName = partName + "generatedRad";
} else {
partName = partName + customSelectOneRadio.getName();
}
}
return partName;
}
}
}
private UIComponent getParentDataTableFromHierarchy(UIComponent uiComponent) {
if (uiComponent == null) {
return null;
}
if (uiComponent instanceof UIData) {
return uiComponent;
} else {
//try to find recursively in the Component tree hierarchy
return getParentDataTableFromHierarchy(uiComponent.getParent());
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
UICustomSelectOneRadio customSelectOneRadio
= (UICustomSelectOneRadio) component;
if (component.isRendered()) {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
writer.writeAttribute("id", component.getClientId(context), "id");
writer.writeAttribute("name", getName(customSelectOneRadio, context), "name");
if (customSelectOneRadio.getStyleClass() != null && customSelectOneRadio.getStyleClass().trim().
length() > 0) {
writer.writeAttribute("class", customSelectOneRadio.getStyleClass().trim(), "class");
}
if (customSelectOneRadio.getStyle() != null && customSelectOneRadio.getStyle().trim().length() > 0) {
writer.writeAttribute("style", customSelectOneRadio.getStyle().trim(), "style");
}
...
if (customSelectOneRadio.getValue() != null
&& customSelectOneRadio.getValue().equals(customSelectOneRadio.getItemValue())) {
writer.writeAttribute("checked", "checked", "checked");
}
if (customSelectOneRadio.getItemLabel() != null) {
writer.write(customSelectOneRadio.getItemLabel());
}
writer.endElement("input");
}
}
}
To quickly summarise, this is working when I use a custom tag in an facelets/XHTML file, but not when I use it dynamically, e.g.
<h:panelGroup id="dynamicPanel" layout="block" binding="#{documentController.dynamicPanel}"/>
If anyone has any ideas on what I could be missing I'd be grateful.
Gotcha! It all revolved around changing the rendererType property. From the Renderer class above, you can see I had it set to my own, i.e.
public static final String RENDERER_TYPE = "com.myapp.jsf.renderers.HTMLCustomSelectOneRadioRenderer";
(1) I changed it to
public static final String RENDERER_TYPE = "javax.faces.Radio";
(2) I also changed my xxx.taglib.xml file to reflect this, e.g.
<namespace>http://mycomponents</namespace>
<tag>
<tag-name>customradio</tag-name>
<component>
<component-type>CustomRadio</component-type>
<renderer-type>javax.faces.Radio</renderer-type> /*<----- See Here */
</component>
</tag>
(3) But, here's the final step to note. I also had to create the following constructor in my UICustomSelectOneRadio component. It didn't work without this either.
public UICustomSelectOneRadio() {
this.setRendererType("javax.faces.Radio");
}
Remember - I extended my component from UIInput, so javax.faces.Text would have been set. Leaving my component family as "CustomRadio" was fine.
I'm still not 100% comfortable with renderer types etc., but for anyone who wants a little info, BalusC explains it well here.

Resources