JSF 1.2 empty <h:selectManyListbox /> validation issue - validation

I'm kind of new to JSF and I'm having trouble to understand what values JSF renders in a form after its validation fails. Im using WebSphere 7 and its default implementation of JSF, MyFaces (I think 2.0).
My xhtml looks like this:
<h:form id="form">
<h:inputText id="text" value="#{backing.text}" required="true"/>
<h:message for="text" />
<h:selectManyListbox id="options" value="#{backing.options}" required="true">
<f:selectItem itemLabel="1" itemValue="1" />
<f:selectItem itemLabel="2" itemValue="2" />
<f:selectItem itemLabel="3" itemValue="3" />
</h:selectManyListbox>
<h:message for="options" />
<h:commandButton value="Save" />
</h:form>
And my backing bean like this:
public class Backing {
private String text;
private String[] options;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String[] getOptions() {
return options;
}
public void setOptions(String[] options) {
this.options = options;
}
}
I fill the <h:inputText /> with some text.
I select two options from the <h:selectManyListbox />
I press the 'Save' button
The form is rendered with the value I entered for <h:inputText /> and with the options I selected on the <h:selectManyListbox /> (no validation messages are shown, as expected)
Now ...
I empty the <h:inputText />
I deselect the two options from the <h:selectManyListbox />
I press the 'Save' button
The form renders the <h:inputText /> empty and the <h:selectManyListbox /> with the previous options I had selected (both validation messages are shown, as expected)
As you can see, the behaviour when rendering the <h:inputText /> and the <h:selectManyListbox /> is different:
<h:inputText /> renders component's submitted value
<h:selectManyListbox /> renders bean's value
I've been trying to render <h:selectManyListbox /> with no options selected without hacking or messing my code, but had no luck.
¿Is this some bug? ¿Am I missing something?

The less hacky solution I found is to copy and re-implement the method renderOption, overriding the default MenuRenderer.
The original source is something like this as I had to decompile (version 1.2_13).
Notice that I'm pasting only the lines that actually need to be changed. If you need to use this solution you will have to copy the full contents of the method:
public class MenuRenderer extends HtmlBasicInputRenderer {
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, HtmlBasicRenderer.OptionComponentInfo optionInfo) throws IOException {
(...)
Object valuesArray;
Object itemValue;
if (submittedValues != null) {
boolean containsValue = containsaValue(submittedValues);
if (containsValue) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
(...)
}
}
I created CustomListboxRenderer (ListboxRenderer extends MenuRenderer) like this:
public class CustomListboxRenderer extends ListboxRenderer {
#Override
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, HtmlBasicRenderer.OptionComponentInfo optionInfo) throws IOException {
(...)
Object valuesArray;
Object itemValue;
if (submittedValues != null) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
(...)
}
}
and then added in faces-config the next lines:
<render-kit>
<renderer>
<component-family>javax.faces.SelectMany</component-family>
<renderer-type>javax.faces.Listbox</renderer-type>
<renderer-class>CustomListboxRenderer</renderer-class>
</renderer>
</render-kit>

Related

JSF/PrimeFaces: Selection based visibility

I want to show / now show (for example) a text, based on a radio selection.
In an ajax style, no roundtrip to server.
How do I have to do this with JSF/PrimeFaces?
<h:outputText value="Show some stupid Text." id="testShowText" />
<p:selectOneRadio id="testRadio" widgetVar="testRadio" value="True" layout="grid" columns="1">
<f:selectItem itemLabel="Show Text" itemValue="True"/>
<f:selectItem itemLabel="Do NOT show Text" itemValue="False"/>
</p:selectOneRadio>
UPDATE
I managed it in my test this way, but I am not sure, if this is the "best practice", I have some doubts; do I really need a managed bean for this?:
First I created a Bean to store the selected value:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class ShowTextBean {
private boolean showBool = false;
private String showString = "False";
public ShowTextBean() {
}
public boolean isShowBool() {
return showBool;
}
public void setShowBool(boolean showBool) {
this.showBool = showBool;
}
public String getShowString() {
return showString;
}
public void setShowString(String showString) {
this.showString = showString;
}
}
Then I changed the Facelets Code to:
<p:panel id="testShowTextPanel" style="display: #{showTextBean.showString eq 'False' ? 'none' : 'block'} ">
<h:outputText value="Show some stupid Text." id="testShowText"/>
</p:panel>
<p:selectOneRadio id="testRadio" widgetVar="testRadio" value="#{showTextBean.showString}" layout="grid" columns="1">
<f:selectItem itemLabel="Show Text" itemValue="True"/>
<f:selectItem itemLabel="Do NOT show Text" itemValue="False"/>
<p:ajax update="testShowTextPanel" />
</p:selectOneRadio>

Change value of checkbox using ajax in JSF

I try to solve the following problem: i have a group of h:selectBooleanCheckbox that generates using ui:repeat:
<h:form>
<ui:repeat value="#{uiCheckboxList.list}" var="boxElement" varStatus="i">
<h:selectBooleanCheckbox id="a">
<f:attribute name="value" value="#{boxElement.enabled}"/>
</h:selectBooleanCheckbox>
<h:outputLabel value="#{boxElement.val}" for="a"/>
</ui:repeat>
</h:form>
Values and label's text stored in array list and controls by servlet:
#ManagedBean(name="uiCheckboxList")
#ApplicationScoped
public class CheckBoxListBean implements Serializable {
private ArrayList<BoxTuple> list;
// BoxTyple is class with 2 fields - val (double) and enabled (boolean)
public CheckBoxListBean() {
list = new ArrayList<>();
for(double i = -2.0; i <= 2.0; i += 0.5) {
list.add(new BoxTuple(i, false));
}
// Set first element to true
list.get(0).setEnabled(true);
}
public ArrayList<BoxTuple> getList() {
return list;
}
public void setList(ArrayList<BoxTuple> list) {
this.list = list;
}
And my problem is this: when you click on one of the h:selectBooleanCheckbox server asynchronously sent request with information about the changed box, and then change the values of the another boxes without reloading page. In other words, I need to get the behavior of radio boxes. Maybe it sounds silly, but I need to solve this problem. How can i implement this?
You can do something like this:
<h:form id="form">
<ui:repeat value="#{uiCheckboxList.list}" var="boxElement"
varStatus="i">
<h:selectBooleanCheckbox id="a">
<f:attribute name="value" value="#{boxElement.enabled}" />
<f:ajax render="form"
listener="#{uiCheckboxList.listen(boxElement)}" />
</h:selectBooleanCheckbox>
<h:outputLabel value="#{boxElement.val}" for="a" />
</ui:repeat>
</h:form>
(get rid of the varStatus if you don't use it)
public void listen(BoxTuple tuple) {
if (tuple.enabled)
for (BoxTuple t : list)
if (!t.equals(tuple))
t.setEnabled(false);
}

JSF Primefaces and ajax listener, button not shown when rendered

I am using JSF and Primefaces to develop a JavaEE application. Each time I press a button(Authenticate), a BUTTON (Button) and a message(Message) must be shown.
The problem is that the message is shown, but not the button. What could I do to show the button?
Here is my code:
ManagedBean IdCertificateManagedBean.java
String m_strRoute;
String m_strMessageRegister;
boolean m_bRegistrationCorrect;
//Getters and Setters
//Constructor
public IdCertificateManagedBean()
{
m_strMessageRegister = "";
m_strRoute = "";
m_bRegistrationCorrect = false;
}
public void authenticateUser()
{
try
{
int a=5;
if (a ==5)
{
m_strMessageRegister = "hello";
m_bRegistrationCorrect = true;
m_strRoute = "/admin/menuadmin";
}
else
{
m_strMessageRegister = "ERROR";
}
}
catch ( Exception e)
{
m_strMessageRegister = "Error";
}
}
}
Facelet
<p:commandButton value="Authenticate">
<p:ajax listener="#{IdCertificateManagedBean.authenticateUser()}" update="Message, Button" />
</p:commandButton>
<h:outputText id="Message" value="#{IdCertificateManagedBean.MessageRegister}" />
<p:commandButton id="Button" value="Go" action="#{IdCertificateManagedBean.route}" rendered=" {IdCertificateManagedBean.registrationCorrect}" />
You must wrap your <h:commandButton /> inside a container as <h:panelGroup /> and then refresh the container.
The problem is that on first page load your button is not rendered so it is not inserted inside the DOM of the page. On page refresh you're trying to refresh it but you can't do it because the button isn't on the page.
A solution could be this
<h:panelGroup layout="block" id="buttonDiv">
<h:commandButton ... />
</h:panelGroup>
and then in your ajax you have to refresh buttonDiv

Validate if new value of <h:inputText> is not higher than old value

I want to control the value in an <h:inputText> ..I want that once I leave the input fieldsif I have a higher value than the old value an error message is displayed and I can not validate fields after entering a value lower (the older value is loaded from the database)
I have done somthing like this :
<p:column headerText="Qte" >
<h:inputText value="#{ligne.qte}" styleClass="span12" required="true" valueChangeListener="#{myBean.changeQte}" >
<h:message id="message"></h:message>
<p:ajax event="keyup" listener="#{myBean.onQteChange}" update="message" />
</h:inputText>
</p:column>
in myBean I have this two methods :
public void onQteChange(){
String message =null;
int newqte = getQte();
if (newqte > previousQTE ){
message="invalid qte";
}
}
public void onQteChange(){
String message =null;
int newqte = getQte();
if (newqte > previousQTE ){
message="invalid qte";
}
}
Can someone tells me how can I do this because even if I try to make ajax call into my inputtext I have no result ?
You can use :
public void onQteChange(){
String message =null;
int newqte = getQte();
if (newqte > previousQTE ){
message="invalid qte";
FacesContext.getCurrentInstance().addMessage(
"message",new FacesMessage(FacesMessage.SEVERITY_ERROR, message,message));
}
}
<p:column headerText="Qte" >
<h:inputText value="#{ligne.qte}" id="x" styleClass="span12" required="true" valueChangeListener="#{myBean.changeQte}" >
<p:ajax event="keyup" listener="#{myBean.onQteChange}" update="message" />
</h:inputText>
<h:message id="message" for="x" />
</p:column>

JSF Validator compare to Strings for Equality

How would you compare two string for equality in a JSF Validator?
if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) {
save = false;
FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null);
}
Use a normal Validator and pass the value of first component as attribute of second component.
<h:inputSecret id="password" binding="#{passwordComponent}" value="#{bean.password}" required="true"
requiredMessage="Please enter password" validatorMessage="Please enter at least 8 characters">
<f:validateLength minimum="8" />
</h:inputSecret>
<h:message for="password" />
<h:inputSecret id="confirmPassword" required="#{not empty passwordComponent.value}"
requiredMessage="Please confirm password" validatorMessage="Passwords are not equal">
<f:validator validatorId="equalsValidator" />
<f:attribute name="otherValue" value="#{passwordComponent.value}" />
</h:inputSecret>
<h:message for="confirmPassword" />
(note that binding in above example is as-is; you shouldn't bind it to a bean property!)
with
#FacesValidator(value="equalsValidator")
public class EqualsValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object otherValue = component.getAttributes().get("otherValue");
if (value == null || otherValue == null) {
return; // Let required="true" handle.
}
if (!value.equals(otherValue)) {
throw new ValidatorException(new FacesMessage("Values are not equal."));
}
}
}
If you happen to use JSF utility library OmniFaces, then you can use <o:validateEquals> for this. The exact case of "confirm password" is demonstrated on <o:validateEqual> showcase.

Resources