primefaces binding attribute in multiple included pages - jsf-2

I have a page inc.xhtml included in four different pages. This included page has a component which has binding attribute specified by binding="#{repeatType}" Since this page is included in multiple pages my component is not rendering. If i remove the binding attribute it is working. If i am not including it in multiple page, only one page and specifying the binding attribute it is working. I think if i can specify a different binding name for each including page might solve the problem. All the ids in the inc.xhtml are made different by id="#{idPrefix}_recDrop". Id prefix is passed as parameter from the including page. Is there anything that i can do to make the binding name different?

You could change the include page to a composite component. One of your incoming attributes for the component could then be some bean to bind the component to.
For design reasons it's best to define some interface for the incoming bean which defines the binding attribute. You then can have multiple beans implementing that interface and thus multiple different instances of the composite component with another binding instance.

Related

Can Orbeon controls have multiple values?

I think the answer is no, but the question has been put to me so I'd like to confirm. My understanding is that any custom XBL control that I create for use in Form Builder can have one and only one value. Is this correct?
I have always assumed this because the control name is then used in the data instance as the name of the node which contains the the value.
This question comes from the desire to have reusable components with multiple values, for example, an Address control so that addresses can be recorded consistently and the same set of fields does not need to be added many times. Orbeon does have some support for this in the form of Section Templates but because the control names stay the same in each instance of a Section Template this does not work well with our design.
The best idea I've had is that a custom control which records multiple values could encode all the values into a single text string for example in JSON. Of course, this is not ideal.
Are there any other options?
It is possible for controls to have multiple values. When that happens the values are typically stored in nested elements. I.e. a control could bound to an element <address>, and could create nested elements <street>, <city>,<country>, etc to store the different parts of the address.
In practice, you can look at how this is done in the Image Annotation annotation control (see wpaint.xbl), which creates nested elements <image> and <annotation>, leveraging the xxbl:mirror="true" functionality.

JSF duplicates actionListener, valueChangeListener and validator calls many times [duplicate]

There are lot of materials out there differentiating value attribute and binding attribute in JSF.
I'm interested in how both approaches differ from each other. Given:
public class User {
private String name;
private UICommand link;
// Getters and setters omitted.
}
<h:form>
<h:commandLink binding="#{user.link}" value="#{user.name}" />
</h:form>
It is pretty straight forward what happens when a value attribute is specified. The getter runs to return the name property value of the User bean. The value is printed to HTML output.
But I couldn't understand how binding works. How does the generated HTML maintain a binding with the link property of the User bean?
Below is the relevant part of the generated output after manual beautification and commenting (note that the id j_id_jsp_1847466274_1 was auto-generated and that there are two hidden input widgets).
I'm using Sun's JSF RI, version 1.2.
<form action="/TestJSF/main.jsf" enctype="application/x-www-form-urlencoded"
id="j_id_jsp_1847466274_1" method="post" name="j_id_jsp_1847466274_1">
<input name="j_id_jsp_1847466274_1" type="hidden" value="j_id_jsp_1847466274_1">
Name
<input autocomplete="off" id="javax.faces.ViewState" name="javax.faces.ViewState"
type="hidden" value="-908991273579182886:-7278326187282654551">
</form>
Where is the binding stored here?
How does it work?
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Component instances are request scoped!
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed
Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly
recommend that application developers place managed beans that are pointed at by component binding expressions in
“request” scope. This is because placing it in session or application scope would require thread-safety, since
UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on
memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Threads stuck at 100% CPU utilization in HashMap during JSF saveState(), or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).
Also, as a single component basically references the rest of the entire component tree via getParent() and getChildren(), when binding a single component to a view or session scoped bean, you're essentially saving the entire JSF component tree in the HTTP session for nothing. This will get really costly in terms of available server memory when you have relatively a lot of components in the view.
Using binding on a bean property is bad practice
Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
Only use binding in local scope
However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:
Validate input as required only if certain command button is pressed
How to render a component only if another component is not rendered?
JSF 2 dataTable row index without dataModel
Primefaces dependent selectOneMenu and required="true"
Validate a group of fields as required when at least one of them is filled
How to change css class for the inputfield and label when validation fails?
Getting JSF-defined component with Javascript
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
See also:
How to use component binding in JSF right ? (request-scoped component in session scoped bean)
View scope: java.io.NotSerializableException: javax.faces.component.html.HtmlInputText
Binding attribute causes duplicate component ID found in the view
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

Using multiple includes of the same page in the same view

The environment is JSF 2, GlassFish, PrimeFaces.
I am working on an application for editing the data in a very complex model.
All classes in the model have relations to other classes, which in turn have relations to other classes, and so on. In many cases, for a given class, the "cluster" of relations (the whole expanded tree for the class) contains the same class at many places in the tree.
For example :
Class A has relations to class B, C and D.
Class B has no relations.
Class C has relations to class B.
Class D has relations to class E.
Class E has relations to class B.
Now that I have summarized the context, here's what troubles me.
A design decision has been made to put all the data of a given instance of a class in the same page. The current architecture for doing this is the following for a given "root" class :
The "root" class is displayed in a PrimeFaces TabView. The tabs are :
"Main" : contains the simple attributes (String, Integer, ...) of the class.
There is one tab for each relation.
In each tab, there is an include pointing to the appropriate XHTML file.
If the relation points to a single class, the XHTML file pointed to is similar to the "root" form described here. The adequate object is passed as a parameter to the XHTML file in the include directive. There are at most 3 nested TabViews.
If the relation points to a list, the XHTML file pointed to displays a list, with "add", "edit" and "delete" buttons. The adequate list is passed as a parameter to the XHTML file in the include directive.
There are additional complexities concerning lists, but I won't go there for the moment. Just with the single elements, we can see that there is a problem.
At first, I used the same parameter name for all XHTML files to be included. This does not work, because the parameter is "global" to the view. It seems to work for the initial display, but as soon as there is an update in one tab, I get an javax.el.PropertyNotFoundException because the form points to another object.
To mitigate the problem, I changed the parameter name to be unique for each class. Before, all parameters were called "element". After the modification, the parameter for class A is called "aElement", for class B it's "bElement", etc.
This works if all classes in a cluster are different. If a collision occurs, we are back to the same problem as before : in two different inclusions, we use the same parameter names, with different values.
I have thought about a very convoluted way to do it, but it uses Javascript :
I pass an additional parameter to the XHTML forms, which is a unique identifier for the passed object.
I get the identifier in the XHTML form, and put it in a hidden field, which is separated from the rest of the form.
I make sure that the hidden field is never updated, read its value when the form gets focus, and retrieve the right object by an AJAX request using the value.
So my question is : is there a "pure" Java/JSF way to handle this ?
TL;DR : Thanks for reading !
For very complex natures CDI has a lot more to offer then plain JSF2. You could use producers and during runtime you can evaluate and modify objects freely.
You can keep track on what's already been produced and adapt the naming accordingly. For example save every occupied name in a map. Good luck.

MVC: Set Name Attribute w/Helper

I have a situation in an MVC3 app where I would like to be able to set the name attribute on some html being generated by a helper (DropDownList).
It appears this is not possible. Apparently the helpers silently override whatever value you may specify for the name attribute in the html attribute object that you pass to the helper.
I'd like to confirm that before I waste too much more time on trying to work with the existing helpers.
And, as an aside, if it is not possible by design...I think that's a foolish limitation in the MVC framework. Yes, I know that assigning the wrong name attribute can break the automatic model binding. But I should be able to do that when I need to. After all, I can always write the raw html using whatever name attribute I chose. The helpers should help, not be a straitjacket.
Edit to discuss whether editor templates maintain navigational context
Darin, I am using editor templates (I was using the term "partial" generically, since editor templates are a special kind of partial view).
Editor templates do modify the HtmlFieldPrefix -- that's how I noticed I had a problem :). I was using a call like this:
// call in higher level partial - context is 'eae'
#Html.EditorFor(m => m.Value)
...
// inside editor template for typeof(Value) context is 'eae:Value'
That context shift is needed to keep the default binding mechanism working properly. I'm using a different approach, where I want the context to stay fixed throughout a call chain of partials (i.e., as execution burrows down into deeper partials I want the context to stay the same).
This is by design. The HTML helpers do not allow you to override the name attribute. They generate the name based on your view model so that the default model binder is able to properly bind the values according to the well established conventions when the form is submitted.
And, as an aside, if it is not possible by design...I think that's a
foolish limitation in the MVC framework.
You could open a ticket on MS Connect and hope this could change in a future version of the framework. Until then you could also write your own custom helpers that will allow you to override the name attribute for the cases when you need such functionality. Personally I've never needed it so far but I am sure you have valid reasons. Another possibility is to write a custom model binder on the server.

Is NOT providng an ID for a JSF 2.0 form the typical practice?

Is it best to NOT label a form component (or any other component for that matter) unless you have a need to do so e.g. if you want to be able to reliably distinguish one component from another?
When I see examples of reference components I am always seeing them with a preceding colon e.g. ":dialog" rather than "dialog" or "form:dialog". Is not naming the form and then specifying the component using a preceding colon the best practice?
If you don't specify the id of the form because you don't need to reference it by a client ID right now, then it will technically not harm to omit it, because JSF will autogenerate one in any way.
From inside an ID-less form, for example, you can always reference the parent form as #form in execute and render attributes of <f:ajax> to signal that you want to submit and/or render the entire parent form.
<f:ajax execute="#form" render="#form" />
But if you need to reference for example another form or one of its child components on ajax render, then you should give that form a fixed ID, so that you will be able to reference it by client ID.
Another reason which we're experiencing in real world projects is that automated web unit testing software such as Selenium really requires a form with a fixed ID, because it needs to find the input fields and submit buttons by their name attribute which is also composed based on the JSF form ID. If the JSF form ID is not specified, then the input field name is unpredictable on every deploy/request and thus untestable.
All with all, the "best practice" is basically: "only if you need it". I myself am just getting used to always specify the ID of NamingContainer, UIInput and UICommand components. "You never know".
Your component ID would look something like,
:namingContainer:myComponent. Where the first “:” tells JSF that you
want to start looking for the component at the UIViewRoot instance, or
the very top level of the component tree
Read http://ocpsoft.org/java/jsf2-java/how-to-jsf-2-0-render-components-outside-of-the-form/

Resources