Custom Validator for p:selectOneMenu make it not working rendering / not rendering other components

I have this select:

<p:selectOneMenu  value="#{bean.val}">
    <f:selectItem itemValue="X" itemLabel="Select" />
    <f:selectItems value="#{bean.getVals()}" />
    <p:ajax update="wrapper" />
</p:selectOneMenu>

And this is the wrapper it updates:

<p:panel id="wrapper">
    <p:panel rendered="#{bean.val == 'A' or bean.val == 'B'}">
        <!-- insert your code here -->
    </p:panel> 
</p:panel>

The wrapper is outside the select, at the same level.

At the start, it's all ok. The wrapper is hidden.

If I select 'A' and then 'C', for example, the wrapper disappear. BUT, if I select 'A' or 'B' and 'X' again (the first "choice", Select), the wrapper does NOT disappear!

I have put a breakpoint inside the setter of bean.val. The setter in invoked for all the choices BUT for the first one the value inside the debugger is the same as the previous one!

BUT! If I remove the validator, it works!

This is the validator:

@FacesValidator(value="requiredSelect")
public class RequiredSelect implements Validator {
    protected MessageUtil messageUtil = new MessageUtil();
    
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String val = (String) value;
        
        if ("X".equals(val)) {
            FacesMessage msg = this.messageUtil.getDefaultValidationError();
            throw new ValidatorException(msg);
        }
    }
}

Previously I used another validator:

@FacesValidator(value="requiredString")
public class RequiredString implements Validator {
    protected MessageUtil messageUtil = new MessageUtil();
    
    @Override
    public void validate(
        FacesContext context, 
        UIComponent component, 
        Object value
    ) throws ValidatorException {
        String val = (String) value;
        
        if (val == null || val.trim().isEmpty()) {
            FacesMessage msg = this.messageUtil.getDefaultValidationError();
            throw new ValidatorException(msg);
        }
    }
}

but it did not work, because the empty string was not saved to the backing bean at menu change. So, if, for example, you selected 'A' and then back '' (Select) and you try to submit the form, the select is signaled with errors, but the value of the select returns to be 'A'! So the bogus 'X' value.

I'm using Primefaces 3.4.1 and Mojarra 2.1.7



Read more here: https://stackoverflow.com/questions/68457571/custom-validator-for-pselectonemenu-make-it-not-working-rendering-not-renderi

Content Attribution

This content was originally published by Marco Sulla at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: