Submit the value without the mask in PrimeFaces <p:inputMask> component - jsf

Is there a way to submit to the model just the raw value without the mask (format) in the PrimeFaces <p:inputMask> component?
I mean, if I have this mask 999.999.999-99 in the mask attribute and the component displays 123.456.789-10 as the value entered by the user, I would like to get in the backing bean property just 12345678910 as the value, not 123.456.789-10.

You need to write a converter to convert between the value in you backend and the value you want to use in your UI. For example:
#FacesConverter("myConverter")
public class MyConverter implements Converter {
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
if (string == null || string.isEmpty()) {
return null;
}
return string.replace(".", "").replace("-", "");
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object o) {
final String value = (String) o;
if (value == null || value.length() != 11) {
return null;
}
return value.substring(0, 3) + "."
+ value.substring(3, 6) + "."
+ value.substring(6, 9) + "-"
+ value.substring(9);
}
}
Which can be used as:
<p:inputMask value="#{testView.string}"
converter="myConverter"
mask="999.999.999-99"/>

Related

JSF FacesConverter ELResolver.getValue returns null

I am trying to use a converter for an input form where I use some "selectOneMenu" components.
When I try to obtain my controller object inside converter's "getAsObject" method using:
facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "usersController");
I get always null.
This is my converter class which is nested inside UserController class.
#FacesConverter(forClass = User.class, value="userConverter")
public static class UsersControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
UserController controller = (UserController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "usersController");
System.out.println(value);
System.out.println(getKey(value));
System.out.println(controller);
return controller.getUsers(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof User) {
User o = (User) object;
return getStringKey(o.getUsername());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + User.class.getName());
}
}
}
UserController class declaration:
#Named("userController")
#ManagedBean
#SessionScoped
public class UserController implements Serializable{
PS: I am a newbie, I just started learning Java EE/Faces.
This,
UserController controller = (UserController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "usersController");
is indeed not the right way. The following is the right way:
UserController controller = facesContext.getApplication().evaluateExpressionGet(
facesContext, "#{usersController}", UsersController.class);

Bypassing a faces converter for certain properties in JSF

I have a converter as follows to trim all leading and trailing white spaces and strip additional spaces between words.
#ManagedBean
#ApplicationScoped
#FacesConverter(forClass=String.class)
public final class StringTrimmer implements Converter
{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
return value != null ? value.trim().replaceAll("\\s+", " ") : null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
return value!=null ? ((String) value).trim().replaceAll("\\s+", " ") : null;
}
}
This converter is applied globally to all string type properties in associated backing beans.
Sometimes it is necessary to bypass this converter for certain properties like "password" in which no white spaces or additional spaces between words should be trimmed or striped respectively.
How can such string type properties be bypassed so that this converter is not applied to them?
Several ways.
Explicitly declare a converter which does effectively nothing with the value.
E.g.
<h:inputSecret ... converter="noConverter" />
with
#FacesConverter("noConverter")
public class NoConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return value;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return (value != null) ? value.toString() : ""; // This is what EL would do "under the covers" when there's no converter.
}
}
Pass an additional component attribute and let the converter check that.
<h:inputSecret ...>
<f:attribute name="skipConverter" value="true" />
</h:inputSecret>
with
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (Boolean.valueOf(String.valueOf(component.getAttributes().get("skipConverter")))) {
return value;
}
// Original code here.
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (Boolean.valueOf(String.valueOf(component.getAttributes().get("skipConverter")))) {
return (value != null) ? value.toString() : "";
}
// Original code here.
}
Let the converter check the component type. The UIComponent behind <h:inputSecret> is an instance of the HtmlInputSecret class.
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (component instanceof HtmlInputSecret) {
return value;
}
// Original code here.
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (component instanceof HtmlInputSecret) {
return (value != null) ? value.toString() : "";
}
// Original code here.
}
Which way to use depends on business requirements and degree of reusability of the converter.

JSF Converter issue in SelectOneMenu [duplicate]

This question already has answers here:
Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
(2 answers)
Closed 6 years ago.
one more time i'm in trouble here. My point is:
In my project i need a converter for (obviously) convert the items from the SelectOneMenu component to a list property in the respective bean. In my jsf page i have:
<p:selectOneMenu id="ddlPublicType" value="#{publicBean.selectedPublicType}" effect="fade" converter="#{publicBean.conversor}" >
<f:selectItems value="#{publicoBean.lstPublicTypes}" var="pt" itemLabel="#{pt.label}" itemValue="#{pt.value}"></f:selectItems>
</p:selectOneMenu>
And my bean is:
#ManagedBean(name = "publicBean")
#RequestScoped
public class PublicBean {
// Campos
private String name; // Nome do evento
private TdPublicType selectedPublicType = null;
private List<SelectItem> lstPublicTypes = null;
private static PublicTypeDAO publicTypeDao; // DAO
static {
publicTypeDao = new PublicTypeDAO();
}
// Construtor
public PublicoBean() {
lstPublicTypes = new ArrayList<SelectItem>();
List<TdPublicType> lst = publicTypeDao.consultarTodos();
ListIterator<TdPublicType> i = lst.listIterator();
lst.add(new SelectItem("-1","Select..."));
while (i.hasNext()) {
TdPublicType actual = (TdPublicType) i.next();
lstPublicTypes.add(new SelectItem(actual.getIdPublicType(), actual.getNamePublicType()));
}
}
// Getters e Setters
...
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// This value parameter seems to be the value i had passed into SelectItem constructor
TdPublicType publicType = null; // Retrieving the PublicType from Database based on ID in value parameter
try {
if (value.compareTo("-1") == 0 || value == null) {
return null;
}
publicType = publicTypeDao.findById(Integer.parseInt(value));
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Error in data conversion.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext.getCurrentInstance().addMessage("info", msg);
}
return publicType;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value.toString(); // The value parameter is a TdPublicType object ?
}
};
}
...
}
In the getAsObject() method, the value parameter seems to be the value i had passed into SelectItem constructor. But in the getAsString() method, the value also seems to be a string representation of an Id. This parameter shouldn't be of type TdPublicType ? There is anything wrong in my code?
The getAsString() should convert the Object (which is in your case of type TdPublicType) to a String which uniquely identifies the instance, e.g. some ID, so that it can be inlined in HTML code and passed around as HTTP request parameters. The getAsObject() should convert exactly that unique String representation back to the concrete Object instance, so that the submitted HTTP request parameter can be converted back to the original object instance.
Basically (trivial prechecks and exception handling omitted):
#Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) throws ConverterException {
// Convert Object to unique String representation for display.
return String.valueOf(((TdPublicType) modelValue).getId());
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) throws ConverterException {
// Convert submitted unique String representation back to Object.
return tdPublicTypeService.find(Long.valueOf(submittedValue));
}
Update: you've another problem, you're specifying the value property of TdPublicType class as the item value instead of the TdPublicType instance itself. This way the converter will retrieve the value property instead of the TdPublicType instance in the getAsString(). Fix it accordingly:
<f:selectItems value="#{publicoBean.lstPublicTypes}" var="pt"
itemLabel="#{pt.label}" itemValue="#{pt}"/>
Now the code is working. My error was in the loading method. I was doing this:
// Loading menu
List<TdPublicType> l = daoPublicType.retrieveAll();
Iterator<TdPublicType> i = l.iterator();
while (i.hasNext()) {
TdPublicType actual = (TdPublicType) i.next();
lstMenuPublicType.add(new SelectItem(actual.getIdtPublicType(), actual.getNamePublicType()));
}
But the right way is:
// Loading menu
List<TdPublicType> l = daoPublicType.retrieveAll();
Iterator<TdPublicType> i = l.iterator();
while (i.hasNext()) {
TdPublicType actual = (TdPublicType) i.next();
lstMenuPublicType.add(new SelectItem(actual, actual.getNamePublicType())); // In the first parameter i passed the PublicType object itself not his id.
}
use can use generic converter which will convert the value in the backing bean.
You do not need any casting also.
#FacesConverter(value = "GConverter")
public class GConverter implements Converter{
private static Map<Object, String> entities = new WeakHashMap<Object, String>();
#Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
synchronized (entities) {
if (!entities.containsKey(entity)) {
String uuid = UUID.randomUUID().toString();
entities.put(entity, uuid);
return uuid;
} else {
return entities.get(entity);
}
}
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
for (Entry<Object, String> entry : entities.entrySet()) {
if (entry.getValue().equals(uuid)) {
return entry.getKey();
}
}
return null;
}
}
Example usage would be
<p:selectOneMenu id="ddlPublicType" value="#{publicBean.selectedPublicType}" effect="fade" converter="GConverter" >
<f:selectItems value="#{publicoBean.lstPublicTypes}" var="pt" itemLabel="#{pt.label}" itemValue="#{pt}"></f:selectItems>
</p:selectOneMenu>

selectOneMenu do not render/display value

Made a post earlier about this topic (Display values in drill-down SelectOneMenus). The problem that have is not connected to the Object converters as I first thought.
I have two selectOneMenu depending on each other, Sector -> Category. When I persist the background business object that holds a Sector and Category, everything works as expected. Even after the current user session terminates and the user log on again and edit the previous saved business object.
The problem occur when and the entity manager flushes the objects and user wants to display the Sector, Category again from the database. The Sector selectOneMenu displays its value as it should, but the Category selectOneMenu value is not displayed. Although the backing bean has the correct value from the database.
What makes the selectOneMenuto not display certain persisted values/objects when they are loaded from database instead from in-memory?
Edit.xhtml
<h:outputLabel value="Sector:" />
<h:selectOneMenu id="sectorSelector" value="#{activityController.selected.category.sector}" title="#{bundle.CreateSectorLabel_sectorName}" valueChangeListener="#{activityController.changeSectorMenu}" immediate="true">
<a4j:ajax event="change" execute="#this categoryMenu" render="categoryMenu"/>
<f:selectItems value="#{sectorController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
<h:outputLabel value="Category:" />
<h:selectOneMenu id="categoryMenu" value="#{activityController.selected.category}" title="#{bundle.CreateSectorLabel_sectorName}"
binding="#{activityController.categoryMenu}"
required="true" requiredMessage="#{bundle.CreateCategoryRequiredMessage_sector}">
<f:selectItems value="#{activityController.categorySelection}"/>
</h:selectOneMenu>
Controller bean for Category
#ManagedBean(name = "categoryController")
#SessionScoped
public class CategoryController implements Serializable{
....
#FacesConverter(forClass = Category.class)
public static class CategoryControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
CategoryController controller = (CategoryController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "categoryController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Category) {
Category o = (Category) object;
return getStringKey(o.getIdCategory());
}
else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CategoryController.class.getName());
}
}
}
Part of POJO object
...
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idCategory")
private Integer idCategory;
...
#Override
public boolean equals(Object object) {
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.idCategory == null && other.idCategory != null) || (this.idCategory != null && !this.idCategory.equals(other.idCategory))) {
return false;
}
return true;
}
Functon for creating the SelectItem[] array
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = entities.size();
SelectItem[] items;
int i = 0;
if (selectOne) {
items = new SelectItem[size + 1];
items[0] = new SelectItem("", ResourceBundle.getBundle("/resources/Bundle").getString("Select_item"));
i++;
} else {
items = new SelectItem[size];
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
The problem was that I didn't have the right collection of SelectItems when the user edited a business object. Plus that I added the <f:converter> to explicitly invoke the converter, where I did some changes in the getAsString() (the else part).
Thank you for your time, and hope the post can be useful to someone else.
SelectMenuOne
public String prepareEditOrganisationActivity() {
current = (Activity) organisationActivityItems.getRowData();
Sector sector = current.getCategory().getSector();
CategoryController categoryBean = JsfUtil.findBean("categoryController", CategoryController.class);
categorySelection = categoryBean.categoryItemsBySector(sector);
return "EditActivity";
}
CategoryControllerConverter
...
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Category) {
Category o = (Category) object;
return getStringKey(o.getIdCategory());
}
else {
Category tmp = new Category();
return getStringKey(tmp.getIdCategory());
}
}

How to set default value to <h:selectOneMenu>

I am trying to set default value to h:selectOneMenu. But, It is not working.
This is my code
index.xhtml
<h:body>
<h:form id="test">
<h:selectOneMenu value="#{selectMenuBean.selectedItem}"
title="select version"
onchange="submit()"
disabled="false" id="combo">
<f:selectItems value="#{selectMenuBean.selectItems}" />
</h:selectOneMenu>
</h:form>
</h:body>
BackingBean
private String selectedItem;
private List selectItems;
private int version=3;
public List getSelectItems() {
List<Version> selectedItems = ExportDao.getVersionsList();
System.out.println("List size: "+selectedItems.size());
selectItems = new ArrayList();
for (Version v1 : selectedItems) {
String DATE_FORMAT = "yyyy-MM-dd HH:mm";
//Create object of SimpleDateFormat and pass the desired date format.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
selectItems.add(new SelectItem(v1.getVersion(), "V" + v1.getVersion() + "/" + sdf.format(v1.getDate())));
if(version = v1.getVersion()) // I have to check the version and set the matching version as selected.
selectedItem = "V" + v1.getVersion() + "/" + sdf.format(v1.getDate());
}
return selectItems;
}
You're setting the selectedItem with the item label instead of the item value.
Replace
selectedItem = "V" + v1.getVersion() + "/" + sdf.format(v1.getDate());
by
selectedItem = v1.getVersion();
A few possible solutions:
1) Set the type of selectItems to SelectItem[] instead of and untyped List.
or 2) Try setting the var, itemValue and itemLabel attributes of the selectItems like below, and put actual Version objects in your list.
or my favorite, 3) Make a VersionConverter that knows how to convert a Version object from and to a String. Example below if your Version object is persisted in a database and has an Id. After this is constructed, your selectedItem and List selectItems should have the typ Version (and List), not String. JSF will handle the conversion by itself.
#FacesConverter(forClass=Version.class)
public class VersionConverter implements Converter{
public VersionConverter() {
}
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
try {
// Get an EJB that can fetch the Version from a DB. Alternativly, do whatever you need to get your object from a string.
InitialContext ic = new InitialContext();
MyDao myDao = (MyDao)ic.lookup(String.format("java:global/%s/MyBean", (String)ic.lookup("java:module/ModuleName")));
return myDao.findEntity(Version.class, getKey(value));
} catch (NamingException e) {
return null;
}
}
Long getKey(String value) {
Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Version) {
Version e = (Version) object;
return getStringKey(e.getId());
}
else
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Version.class.getName());
}
}

Resources