Primefaces: How to display a variable that can take only 'Y' or 'N' or a boolean value.

I need to display a field in an xhtml that can only take 'Y' or 'N'. It could be drop down list or check box, where user selects the value. The original value should be displayed as per corresponding variable value in Managed Bean. That means if value is Y or true, the listbox or checkbox should be in that state.
VakilsDeveloperAsked:
Who is Participating?
 
sajjadzCommented:
Hi, follow the source.
<p:selectOneMenu converter="#{genderConvertor}">
	<f:selectItem itemLabel="check_all"
		noSelectionOption="true" />
	<f:selectItems
		itemLabel="#{_val.label}"
		itemValue="#{_val}" var="_val"
		value="#{customerController.genders}" />
</p:selectOneMenu>


--------------------------------------

@ManagedBean(name = "genderConvertor")
public class GenderConvertor implements Converter {

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (!(value instanceof Gender)) {
			return null;
		}

		return ((Gender) value).getLabel();
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (value == null) {
			return null;
		}

		if (value.equals("check_all"))
			return null;

		Gender gender = Gender.genderValueOf(value);

		if (gender == null) {
			throw new ConverterException(new FacesMessage("Unknown gender: "
					+ value));
		}

		return gender;
	}
}
------------------------------


public enum Gender {
	MALE("male", "Y"), FEMALE("female", "N");
	private String label;
	private String value;

	private Gender(String label, String value) {
		this.label = label;
		this.value = value;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	public static Gender genderValueOf(String k) {
		for (Gender c : Gender.values()) {
			if (c.getLabel().equals(k)) {
				return c;
			}
		}
		return null;
	}
}

----------------------
in customerController:

public Gender[] getGenders() {
	return Gender.values();
}

public void setGenders(Gender[] genders) {
	this.genders = genders;
}

Open in new window

0
 
VakilsDeveloperAuthor Commented:
Thanks! Works.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.