JSF validation for client side injected elements - jsf

I know there is a property in asp.net (probably this EnableEventValidation of "<%# Page%> tag) .Which, once caused problem when i try to add select items to a component using javascript ,I want to know how jsf handling this. That is,
if i send a h:select* like below and client add a new item "option3 " to item list, is jsf detect this automaticly before update model values .
<h:selectOneMenu id="type"
value="#{foo.value}"
required="true"
requiredMessage="Type is required"
style="width:100px">
<f:selectItem value="option1}"/>
<f:selectItem value="option2}"/>
</h:selectOneMenu>

I think what you need to understand regarding JSF is that the client/server parts of the components are tightly coupled together. You are probably better off thinking of them strictly as one entity, and forget about fiddling with one side only, reverting to custom Javascript when that is the only solution left.
The other way to think of it is that the server side renders the client side, not vice versa! So whenever you need to update a component the update must be done on the server side first, which will propagate to the client side (the browser).
In your example the proper way to add and element to the select* items is to store the selectable items in a data structure within a bean (probably #ViewScoped), and then do a partial update via AJAX for the select* component or its container component, when the server side gets the chance to become aware of the changes and can update the client side properly as well.
Sure, you can hack your way through Javascript only, but then why use JSF? The whole point of JSF is to avoid the need for hacks like this.
Remember, JSF is not JSP, which is basically a println macro for html output. JSF stores the page components' representation on the server side, mirroring the browser's representation.
Check the Primefaces showcase for examples on how to do partial updates. More specifically this is the example you could be looking for. This is available in standard JSF2, for JSF 1.2 you must use a component library to get AJAX support.

You should not add the new option by JavaScript, but you should add the new option by JSF. JSF needs to know about the new option somehow in order to allow the submitted value. The new option really needs to be served by <f:selectItem(s)>. Otherwise you will face Validation error: Value not valid all the time when submitting the option value which is added by JS. This is after all just a safeguard of JSF to prevent clients from manipulating the request and submitting values which they are not supposed to submit.
The following kickoff example should work:
<h:form>
<h:selectOneMenu id="menu" value="#{bean.item}">
<f:selectItems value="#{bean.items}" />
</h:selectOneMenu>
<h:inputText id="newItem" value="#{bean.newItem}" />
<h:commandButton value="add" action="#{bean.addNewItem}">
<f:ajax execute="#this newItem" render="menu" />
</h:commandButton>
<h:commandButton value="submit" action="#{bean.submit}" />
</h:form>
with a #ViewScoped managed bean something like follows:
private String item;
private List<String> items = Arrays.asList("option1", "option2");
private String newItem;
public void addNewItem() {
items.add(newItem);
}
// ...

Related

Disable and empty an input field after an AJAX call using JSF and Richfaces

I am using richfaces 4.2.0.Final and have the following situation: within a rich:dataTable, in which each row describes an article in a shopping cart, I have an input field
in which the user can input the quantity she wants to order. As soon as the user focuses on this input field, I have to perform some controls on the server (using Ajax) and if
the controls fail, I must empty the field and disable it.
My solution:
<rich:dataTable var="article" value="#{cart.articles} >
...
<rich:column>
<h:panelGroup id="orderQty">
<h:inputText id="qtyInput" value="#{article.qty}" disabled="#{article.controlsFailed}">
<a4j:ajax event="focus" bypassUpdates="true"
listener="#{requestBean.doAjaxControls(article)}"
execute="#this" render="qtyInput " />
</h:inputText>
</h:panelGroup>
#RequestScoped
#Named
public class RequestBean{
public void doAjaxControls(Article article){
boolean everyThingOK = doControls();//....
if (!everyThingOK){
article.setControlsFailed(true);
article.setQty(null);
} else {
article.setControlsFailed(false);
}
}
}
Before coming to this solution I tried several other combinations of execute/render, without succeeding in what I need (for example, I tried to use execute="#none" as I don't want
the value of qty to be updated on the server when I perform the ajax call, but this won't work).
My problem is I know this solution is not perfect: when I focus on a position for which the control will fail, and I am faster to type in a quantity than the server performing the controls, the field will be disabled and the server value for article#qty still set to null, but I will see the value I typed in until the next rendering of qtyInput will happen.
More strangely, if I execute this code on JBoss EAP 6.0.0.GA (AS 7.1.2.Final-redhat-1, which includes the module jboss-jsf-api_2.1_spec-2.0.2.Final-redhat-1),
every quantity typed in before doAjaxControls() is done will be cleared: this strange behaviour is fortunately not present with JBoss EAP 6.0.1.GA (AS 7.1.3.Final-redhat-4, jboss-jsf-api_2.1_spec-2.0.7.Final-redhat-1).
Do you know if/how could I improve my solution?
Thanks in advance for helping!

How does JSF load property values of managed bean?

I am a JSF beginner. I have a question about managed bean.
Step 0:
There is a managed bean BeanA, scope is request. And BeanA instance1.propertyA = "0";
Step 1:
using ajax to change country, then in BeanA.countryChanged method, change managed bean BeanA.propertyA = "A".
<t:selectOneMenu id="Country" required="true" valueChangeListener="#{BeanA.countryChanged}">
<a4j:support event="onchange" limitToList="true" ajaxSingle="true" />
<f:selectItems value="#{BeanA.countries}" />
</t:selectOneMenu>
Step2:
submit form to do validate a text input
<h:inputText id="street" required="#{BeanA.propertyA == "A"}"
I expect that in step2 the value propertyA of BeanA instance2 should be "A" in JSF validate phase, but actually it is "0". I don't know how does JSF load BeanA instance property values to create new BeanA instance. And what should I do, the value will changed to "A"? Thanks,
The symptoms indicate that your bean is request scoped. This means that it's reconstructed on every single HTTP request. You probably didn't realize that every single ajax request also counts as a separate HTTP request. In effects, you're not reusing the same bean instance across ajax postbacks on the same view. Every time a brand new instance is been created, with all its properties set to default.
JSF 2.0, which is designed with ajax in mind, has solved it with the new view scope in the standard API.
In JSF 1.x, you need to fall back to 3rd party component libraries. In your particular case, given that you're using both Tomahawk and Ajax4jsf, you've 2 options:
Use <t:saveState>.
<t:saveState value="#{BeanA}" />
Or, use <a4j:keepAlive>.
<a4j:keepAlive beanName="BeanA" />

Opening a new window if condition true in managed bean

I want to implement a situation where the user enter a URL, and if a specified condition is true in my managed bean this URL will be opened in a new web page.
I found this possibility:
The “h:link” tag is useful to generate a link which requires to interact with the JSF “outcome” , but lack of “action” support make it hard to generate a dynamic outcome.
The “h:commandLink” tag is suck, the generated JavaScript is really scary! Not recommend to use this tag, unless you have a solid reason to support. But it supports the “action” attribute, which is what “h:link” lack of.
The “h:outputLink” is useful to generate a link which does not require to interact with the JSF program itself.
At last, it will be perfect if the “action” attribute is added into the “h:link“.
But I didn't find a way to launch the open web page from my managed bean after the condition is verified.
I'm using JSF2.0, Facelets and PrimeFaces 3.4.
To open the target in a new window using one of those link components, you need to specify target="_blank" attribute, but this will already open the target in a new window at the moment you click the link and does thus not depend on the response. You basically need to open the target in a new window at the moment the response has been arrived. The only way is returning a JavaScript window.open() call to the response so that it get executed in the webbrowser.
In standard JSF, you could just render JavaScript's window.open() conditionally.
<h:form>
<h:inputText value="#{bean.url}" />
<h:commandButton value="submit" action="#{bean.submit}">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
<h:outputScript rendered="#{bean.valid}">window.open('#{bean.url}')</h:outputScript>
</h:form>
with
private String url;
private boolean valid;
public void submit() {
valid = validate(url);
}
// ...
In PrimeFaces, you could use RequestContext#execute() to specify JavaScript code which needs to be executed on complete of the response.
<h:form>
<p:inputText value="#{bean.url}" />
<p:commandButton value="submit" action="#{bean.submit}" />
</h:form>
with
private String url;
public void submit() {
if (validate(url)) {
RequestContext.getCurrentInstance().execute("window.open('" + url + "')");
}
}
// ...
Unrelated to the concrete problem: the ranty statements which you cited there are seemingly written by someone who know nothing about HTTP/HTML basics (limitations of GET vs POST and so on). Please take them with a good grain of salt.

where are f:attribute name/value pairs stored?

I'm using the following (example)
<h:commandButton value="Submit" action="#{indexBean.submit}"
actionListener="#{indexBean.btnListener}" >
<f:attribute name="valueOne" value="v1" />
<f:attribute name="valueTwo" value="v2" />
<f:attribute name="valueThree" value="v3" />
</h:commandButton>
When the page is rendered i'm looking at the source code through the browser, but i cant find the values in some sort of hidden fields or anything else.
Are they stored at the back end on server side, in the view state or some where else?
Best Wishes,
They are stored as attribtues of the component in question. They do not end up in the generated HTML output because the component's renderer does not recognize them as standard HTML attributes.
The component is in turn stored in the component tree in the server side memory and if it concerns an UIForm, UIInput or UICommand component, then it's also stored in the view state.
If you want to pass visible parameters, you should rather be using <f:param>. They will then be visible in the generated JavaScript onclick function of the component's HTML representation. Note that <f:param> in <h:commandButton> is only supported since JSF 2.0.

What is the JSF behaviour, if you bind the same backing bean property to two input fields in the same form?

Is there a defined behaviour in JSF, if two input fields are bound to the same session scoped Backing Bean property.
Here is my code snippet
<h:form id="myForm">
<h:inputText id="field1" value="#{TheBackingBean.theProperty}" />
<h:inputText id="field2" value="#{TheBackingBean.theProperty}" />
<h:commandButton id="continueButton" action="#{TheBackingBean.doSomething}" />
</h:form>
My question: If field1 and field2 receive different values, what will be bound to the backing bean property? Is this even allowed?
I know this is a crude scenario. My motivation is, that we have htmlunit tests running for our application. In our JSF application we want to use a cool ajaxified custom component. This doesnt work together very well with htmlunit. So my idea was, I just put in a hidden field that binds to the same property. The unit test then fills the hidden field instead of the "real" thing.
Regards
I think this kind of code is allowed, but I am not sure of the value of theProperty after the submission. What I think is that JSF will do the following:
TheBackingBean.setTheProperty(field1.value);
TheBackingBean.setTheProperty(field2.value);
However, nothing - as far as I know - specifies the order of the setter calls. Thus, after the update values JSF phase, you will not be sure if theProperty will be equal to field1.value or field2.value.
Concerning your scenario, you say that you want to bind the same property to an inputText and an hiddenText. As the hiddenText will not submit its value, unlike the inputText, this problem will not occur. Indeed, if you have this kind of JSF code:
<h:inputText id="field1" value="#{TheBackingBean.theProperty}"/>
<h:inputHidden id="field2" value="#{TheBackingBean.theProperty}"/>
then JSF will only do:
TheBackingBean.setTheProperty(field1.value);
during the submission phase.

Resources