How to show the desired h: selectOneMenu message with the default selection option?

I ran into one problem with selectOneMenu. I need to display a list of items in a drop-down list, and this is a required field.

In this drop-down list, the first value is "Select . " If the user does not ask any questions, I need to display an error message, for example, "Select any question . "

Can someone give me a solution?

+4
source share
2 answers

Just set the element value for the first element to null . You should not set it with a label value.

eg.

 <h:selectOneMenu value="#{bean.question}" required="true" requiredMessage="Please select a question"> <f:selectItem itemValue="#{null}" itemLabel="Select" /> <f:selectItems value="#{bean.questions}" /> </h:selectOneMenu> 
+11
source

You can also create a validator.

1)

 <h:selectOneMenu id="giftValue" value="#{yourController.giftDO.giftValue}"> <f:selectItems value="#{yourController.giftDO.giftValueMap}" /> <f:validator validatorId="selectOneMenuValidator"/> </h:selectOneMenu> <h:message for="giftValue" errorStyle="color:red"/> //where giftValue enum willcontail the word "Select" 

2) Create SelectOneMenuValidator.java

 public class SelectOneMenuValidator implements Validator { /* (non-Javadoc) * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object) */ public void validate(FacesContext context, UIComponent arg1, Object value) throws ValidatorException { String giftValue = (String)value; if(giftValue != null && giftValue.toUpperCase().equals("SELECT")){ FacesMessage message = new FacesMessage(); message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setSummary("Please Select a question!"); message.setDetail("Please Select a question!"); context.addMessage("Please Select a question!", message); throw new ValidatorException(message); } } } 

3) Add validator to faces-config.xml file

 <validator> <validator-id>selectOneMenuValidator</validator-id> <validator-class>net.roseindia.validations.SelectOneMenuValidator</validator-class> </validator> 
-1
source

All Articles