Primefaces text in outputLabel pattern of réal - jsf

Is there any way to make a pattern to the value of outputLabel, I tried like this way :
#Digits(integer=3, fraction=2)
I put this annotation in my Entity but nothing is changed
Someone have an idea to chnage this number in ENTITY or in the page?
<p:outputLabel value="#{VarAvancementPrj.avancementprojet}%"/>
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "avancementprojet", precision = 17, scale = 17)
#Digits(integer=3,fraction=2)
private Double avancementprojet;

You should add converter inside your outputlabel
<f:convertNumber pattern="#0.00" />

Related

Do not fill p:inputText with 0 when binding to an integer property [duplicate]

I have an input place that should get a number. I want it to be displayed as empty. However when I run my program, I get 0 or 0.00 as default. How can I make it empty?
This will happen if you bound the value to a primitive instead of its wrapper representation. The primitive int always defaults to 0 and the primitive double always defaults to 0.0. You want to use Integer or Double (or BigDecimal) instead.
E.g.:
public class Bean {
private Integer number;
// ...
}
Then there are two more things to take into account when processing the form submit. First, you need to instruct JSF to interpret empty string submitted values as null, otherwise EL will still coerce the empty string to 0 or 0.0. This can be done via the following context parameter in web.xml:
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
Second, if you're using Tomcat/JBoss or any server which uses Apache EL parser under the covers, then you need to instruct it to not coerce null to 0 or 0.0 in case of Number types by the following VM argument (it's unintuitively dealing with Number types as if they are primitives):
-Dorg.apache.el.parser.COERCE_TO_ZERO=false
See also:
The empty string madness
h:inputText which is bound to Integer property is submitting value 0 instead of null
h:inputText which is bound to String property is submitting empty string instead of null
javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL does not work anymore since Java EE 7 / EL 3.0
I don't disagree with previous answers given, but I think you might be looking for
<h:inputText id="number" binding="#{controller.inputBox}" value="#{controller.number}" >
<f:event type="preRenderComponent" listener="#{controller.preRenderInput}" />
</h:inputText>
and inside the controller
private double number; // getters and setters
private UIInput inputBox; // getters and setters
public void preRenderInput() {
// if it is the first request
if(!FacesContext.getCurrentInstance().isPostback()) {
inputBox.setValue("");
}
}
JSF 2.0+
You can use inputNumber in primefaces-extension instead of inputText.
Like this
<pe:inputNumber />
In your XHTML code, assume you have your input field as :
<h:inputText id="newname" value="#{youAction.newName}"
style="width:130px" styleClass="form">
</h:inputText>
In your Managed Bean Action Class, map this field as :
#ManagedBean(name="yourAction")
public class YourAction {
private String newName;
...
// Add Getter & Setter Methods
...
}
By doing in this way, you won't get 0 or 0.00 as default value in your input fields.

Bind the value of an input component to a list item by index

here is an example :
<h:outputLabel for="category1" value="Cateogry"/>
<h:selectOneMenu id ="category1" value="#{articleManageBean.categoryId1}"
converter="categoryConverter">
<f:selectItems value="#{articleManageBean.categories}" var="category"
itemValue="#{category.id}" itemLabel="#{category.name}" />
</h:selectOneMenu>
and here is the managed bean that I have
#ManagedBean
#SessionScoped
public class ArticleManageBean {
private Long categoryId1;
private List<Category> categories;
//...
}
The categories list gets populated from db, and selectOneMenu gets populated with this list using a converter.
My First question:
If I want to create another selectOneMenu in my jsf page I would have to copy paste the entire thing and just change the value of selectOneMenu to say categoryId2 thus putting another attribute to managed bean called categoryId2. That is not practical. I want to map these values of selectMenu to list items, for instance to an attribute
List<Long> categoryIds;
if I use
<h:selectOneMenu id ="category1" value="#{articleManageBean.categoryIds.[0]}" >
I get an error
javax.el.PropertyNotFoundException: /createArticle.xhtml #47,68 value="#{articleManageBean.categoriesId[0]}": Target Unreachable, 'null' returned null
If I nitialize the Araylist then I get this exception
javax.el.PropertyNotFoundException: /createArticle.xhtml #47,68 value="#{articleManageBean.categoriesId[0]}": null
My second question:
Is there a way to dinamicly write selectOneMenu tags, by that I mean not to copy paste the entire tag, just somehow create a function that take the categoryId parameter and writes automaticaly the tag (somekind of custom tag maybe ?)
Hope you understood my questions
thanks in advance
Use the brace notation instead to specify the index.
<h:selectOneMenu id="category1" value="#{articleManageBean.categoryIds[0]}">
You only need to make sure that you have already prepared the values behind #{articleManageBean.categoryIds}. JSF won't do that for you. E.g.
private List<Long> categoryIds = new ArrayList<Long>();
public ArticleManageBean() {
categoryIds.add(null);
categoryIds.add(null);
categoryIds.add(null);
// So, now there are 3 items preserved.
}
an alternative is to use Long[] instead, this doesn't need to be prefilled.
private Long[] categoryIds = new Long[3]; // So, now there are 3 items preserved.

How do I bind a inputbox values to a map value in a backing bean property when using a wizard

I am using the Primefaces wizard component. On one tab I am dynamically creating input boxes based on previous tabs input(user type). The inputbox text labels are derived from a list. In my backing bean, I have a map that contains input labels as keys and inputbox inputs as values.
Clicking on next, I would like the map(values) to be updated with the user input (corresponding to the key)
<c:forEach items="#{gdsiGeodataBean.actionCommand.fields}" var="reqs">
<h:outputLabel for="#{reqs.name}" value="#{reqs.name}:* " />
<pou:inputText value="#{gdsiGeodataBean.actionCommand.values['reqs.name']}" required="true" requiredMessage="Input is required."/>
</c:forEach>
My backing bean :
private List<RequiredParam> fields; // +getter (no setter required)
private Map<String, String> values; // +getter (no setter required)
public CommandAction(String actionName, String actionParams, String context) {
this.actionName = actionName;
this.actionParams = actionParams;
this.contextName = context;
//Set up parameters
getRequiredParams();
getOptionalParams();
fields = getFields();
values = new HashMap<String, String>();
}
Essentially what I would like is for the map values to be updated with user inputs from the textinput boxes.
Your approach to bind the input value to a map is not entirely correct.
<pou:inputText value="#{gdsiGeodataBean.actionCommand.values['reqs.name']}" required="true" requiredMessage="Input is required."/>
You're specifying a fixed map key instead of a dynamic map key based on the currently iterated #{reqs}. This way all submitted values will end up in one and same fixed map key "reqs.name", whereby each one overrides each other so that you only get the value of the last field in the map.
You need to remove those singlequotes to make it a really dynamic key.
<pou:inputText value="#{gdsiGeodataBean.actionCommand.values[reqs.name]}" required="true" requiredMessage="Input is required."/>
Unrelated to the concrete question, even though this approach will work when used as-is in your question, the <c:forEach> will fail in certain circumstances. E.g. when used inside a composite component or an iterating JSF component. Rather use <ui:repeat> instead. See also JSTL in JSF2 Facelets... makes sense?

"ValueExpression Map" of a JSF component

I'm storing value expressions in a JSF component with the f:attribute tag, e.g.:
<h:inputText ...>
<f:attribute name="myId1" value="#{bean.prop1}" />
<f:attribute name="myId2" value="#{bean.prop2}" />
<f:attribute name="myId3" value="#{bean.prop3}" />
</h:inputText>
Is there a way to access all of those value expressions programmatically? (without knowlegde of the names myId1, myId2,...)
Section 9.4.2 of the JSF 2.1 specification says that those values are stored "in the component’s ValueExpression Map".
That's the only occurrence of the term "ValueExpression Map" in the complete spec.
How do I access that map?
In the UIcomponent's Method getValueExpression() of the Jboss/Mojarra implementation the map
getStateHelper().get(UIComponentBase.PropertyKeys.bindings)
is used to obtain a single value expression.
I guess that map is a super set of the "ValueExpression Map"?
Can I be sure that all implementations and all inherited (standard) components use that map to store ValueExpressions?
Thanks.
In theory you should be able to see them all by UIComponent#getAttributes():
Map<String, Object> attributes = component.getAttributes();
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
System.out.printf("name=%s, value=%s%n", entry.getKey(), entry.getValue());
}
However, that doesn't work the way as you'd expect. It only returns static attributes. This does not seem to ever going to be fixed/implemented. See also JSF issue 636. I'd suggest to stick to attribtues with predefinied prefix and an incremental numerical suffix, like as you've presented in your example. That's also what I've always used to pass additional information from the component on to custom validators and converters. You can just collect them as follows:
Map<String, Object> attributes = component.getAttributes();
List<Object> values = new ArrayList<Object>();
for (int i = 1; i < Integer.MAX_VALUE; i++) {
Object value = attributes.get("myId" + i);
if (value == null) break;
values.add(value);
}
System.out.println(values);
An alternative to the answer given by BalusC might be to use nested facets or UIParameter components. Facets can be retrieved as a map using getFacets but you probably need to put an additional UIOutput inside each facet to access its value expression.
Nested UIParameters can be accessed by iterating over the components children and checking for instanceof UIParameter. UIParameters have name and value attributes and so could be easily converted to a map.
I have used parameters in a custom component, but I'm not sure how a standard UIInput like in your example reacts to these.
BalusC is right. UIComponent#getAttributes().get(name) gets values from both places - at first from attributes map and then if not found from "value expression map". To put some value you have to call UIComponent#setValueExpression(name, ValueExpression). If value is literal, it gets stored into the attribute map, otherwise into the "value expression map". Everything is ok then.

Using h:outputFormat to message-format the f:selectItems of a h:selectOneRadio

I am having some trouble with using h:selectOneRadio. I have a list of objects which is being returned which needs to be displayed. I am trying something like this:
<h:selectOneRadio id="selectPlan" layout="pageDirection">
<f:selectItems value="#{detailsHandler.planList}" />
</h:selectOneRadio>
and planList is a List of Plans. Plan is defined as:
public class Plan {
protected String id;
protected String partNumber;
protected String shortName;
protected String price;
protected boolean isService;
protected boolean isOption;
//With all getters/setters
}
The text that must appear for each radio button is actually in a properties file, and I need to insert params in the text to fill out some value in the bean. For example the text in my properties file is:
plan_price=The price of this plan is {0}.
I was hoping to do something like this:
<f:selectItems value="<h:outputFormat value="#{i18n.plan_price}">
<f:param value="#{planHandler.price}">
</h:outputFormat>" />
Usually if it's not a h:selectOneRadio component, if it's just text I use the h:outputFormat along with f:param tags to display the messages in my .property file called i18n above, and insert a param which is in the backing bean. here this does not work. Does anyone have any ideas how I can deal with this?
I am being returned a list of Plans each with their own prices and the text to be displayed is held in property file. Any help much appreciated.
Thanks!
I am now able to resolve the above issue following the recommendation below. But now I have another question.
Each radio button item must display like this:
Click **here** to see what is included. The cost is XX.
Now the above is what is displayed for each radio button. The "here" needs to be a hyperlink which the user can click and should bring up a dialog box with more info.I can display the sentence above but how do I make the "here" clickable?
Since the above is what is displayed it is the label for SelectItem(Object value, String label) which is returned.
Any ideas much appreciated.
The value passed to <f:selectItems /> must be a list or array of type javax.faces.model.SelectItem.
You can set the output label in the constructor of the SelectItem. I imagine you can access your properties file from the backing bean. The method to get the SelectItems would look something like this:
public List<SelectItem> getPlanItems() {
List<SelectItem> list = new ArrayList<SelectItem>();
for (Plan plan : planList) {
String label = buildPlanPriceLabel(plan.getPrice());
list.add(new SelectItem(plan, label));
}
return list;
}
Leaving buildPlanPriceLabel as an exercise for the reader.

Resources