How to access a composite component's sibling via clientId - jsf

I have a composite component that bundles some input fields. The component will be used multiple times on a page and contains a button to copy the values of another of these components. For this I would need to access one of those siblings via its clientId as a target for an
<f:ajax execute=":XXX:siblingId" render="...">
My problem lies in constructing this ID. I have the name of the sibling and I can make sure that it is located in the same naming container as the component that contains the copy button, but I can't control the complete nesting hierarchy, so it might be :form:foo:bar:parent:child or just form:parent:child. So essentially I would want to get the prefix of the current composite component, but without the component's own ID and then attach the ID of the component from which to copy.
This is similar to these questions:
How to address the surrounding naming container in jsf
How to access the parent naming container of composite
However, both answers make use of PrimeFaces-sepcific features like #parent and widgetVar, which does not apply to my project.
When experimenting with EL's implicit objects I basically tried the same things as the poster of the second question - with the same results: cc.parent.clientId is always empty. I also tried cc.namingContainer.clientId and some combinations of the two, alas - no success. Especially the fact that parent does not work as expected confuses me...
So: Is there a component-library-agnostic way to access the "path" of containing naming containers for a composite component? How is the parent object supposed to work, especially: when can we use it and when not?
PS: I was thinking about using the composite's full clientId and then trimming its actual ID with fn:split, however, if there was a more direct way I'd be happy to use it.

The #{cc.parent} resolves to UIComponent#getCompositeComponentParent() which returns the closest parent composite component. In other words, it returns only non-null when the composite component is by itself nested in another composite component.
The #{cc.namingContainer} simply refers to #{cc} itself, fully conform as specified in UIComponent#getNamingContainer():
Starting with "this", return the closest component in the ancestry that is a NamingContainer or null if none can be found.
Composite components namely implicitly implement NamingContainer themselves.
So your attempts unfortunately won't work. I also do not see any "standard API" ways to achieve the concrete functional requirement. The CompositeComponentAttributesELResolver causes that the #{cc.parent} doesn't resolve to UIComponent#getParent() which is what you ultimately want.
You can however provide a custom UIComponent implementation for the composite which adds an extra getter with an unique name which in turn properly delegates to UIComponent#getParent().
Here's a kickoff example:
#FacesComponent("myComposite")
public class MyComposite extends UINamingContainer {
public UIComponent getParentComponent() {
return super.getParent();
}
}
If you register it as follows in the composite interface:
<cc:interface componentType="myComposite">
then you'll be able to use
#{cc.parentComponent.clientId}
to get the client ID of the real parent UIComponent.
Ultimately you should be able to use the following construct to refer the sibling:
process=":#{cc.parentComponent.clientId}:siblingId"

Related

Can JSF be configured to not invoke Entity setter unless the field actually changed?

When a JSF form field is wired into an entity bean field (which is mapped to a DB field), each setter in the entity bean is called regardless of whether the user changed the form field value in the front end, i.e. the setters on unchanged fields are invoked the same as those that have changed but their new value is the same as the old value.
My question is simple: Is there a way to configure JSF to only call the setters mapped to the fields that have changed in the front end? The reason for this is that I have a requirement by which I have to detect deltas on every persist and log them, more about which can be read in this question.
Maybe I didn't understand you clearly, but why are you mapping directly your entity beans to a JSF view ?! IMHO it would be better if you add managed beans between your JSF pages and the entities in order to better separate your business logic from data access.
Any way, I think the easiest solution to impelement for that case is by making use of Value Change Events which are invoked "normally" after the Process Validations phase (unless you make use of the immediate attribute).
The good news about Value Change Events (regarding your example) is they are invoked ONLY after you force form submit using JavaScript or Command components AND the new value is different from the old value.
So, as an example on how to use value change listeners, you can add valueChangeListner attribute to each of your JSF tags like following:
<h:inputText id="input" value="#{someBean.someValue}"
valueChangeListener="#{someBean.valueChanged} />
Then, implement your valueChanged() method to look something like:
public void valueChanged(ValueChangeEvent event) {
// You can use event.getOldValue() and event.getNewValue() to get the old or the new value
}
Using the above implementation, may help you to separate your logging code (it will be included in the listeners) from your managed properties setters.
NB: Value Change Listeners may also be implemetend otherwise using the f:valueChangeListener Tag, but this is not the best choice for your example (you can find some examples in the section below, just in case)
See also:
Valuechangelistener Doubt in JSF
JSF 2 valueChangeListener example
When to use valueChangeListener or f:ajax listener?

How to get UIComponent value in Java?

I have a method in my JSF controller that is invoked by an ajax tag nested inside a visual component (really irrelevant which one). The method takes a single argument of type AjaxBehaviorEvent, from which I can obtain a Java representation of the invoking HTML visual component as a UIComponent and also downcast it to its specific corresponding type (e.g. h:inputText corresponding to HtmlInputText).
I understand that, in most cases, the value of the HTML visual component would be retrieved easily by referencing either the controller or entity [g|s]etters to which the form fields are mapped in the view. However, in my particular case, I would like to fetch the value of the visual component (in my case a form field) through its Java object rendering. While studying the faces API, I found ways to read various properties of the object, such as the ID or context but not the value that the component currently holds in the view.
Can anybody explain whether I am just not finding the right way to read it or it is so by design? If the latter, can you explain why it is designed like that? Is it to disable "backdoor" access to form fields as opposed to going through the view mapping?
There are a multitude of ways to pull values off a component. Going by what you already have UIInputt#getValue() and UIInput#getSubmittedValue() will provide the value.
The UIInput#getSubmittedValue() is fit for the purpose only between the APPLY_REQUEST_VALUES and VALIDATE phases of the JSF request. All other phases after, use the UIInputt#getValue(). You'll be using UIInput instead of the raw UIComponent you pulled from the event (UIInput extends UIComponent and it's the parent class for all input components that accept user-edited values). What you'll have will eventually look like:
UIInput theInput = (UIInput)event.getSource();
Object theValue = theInput.getValue();
There are other ways (not as clean) to get values within the request lifecycle also

How to programmatically generate JSF components at run time?

I've got to create screens to display a lot of JPA entities in the View. It would be great to create one facelet and pass to it a collection of fields e.g. List<Object>.
The facelet/custom component would need to convert each element of the list into the appropriate tag for display e.g. an enum field to h:selectOneMenu, String field to h:inputText, etc. This would need to be done at run time.
What's the easiest way to do this?
Worked on a project previously that created entire pages dynamically from stored configuration. There are two basic things you need
A BackingBean. You'll used this to get access to the UIComponent on the facelet which will act as the parent to the generated UIComponents. Something like a panelGroup. But, you'll need to bind the UIComponent to the backing bean, in order to have a parent against which you'll add the dynamically-created UIComponents
Access to the Application component. Typically FacesContext.getApplication() (I worked on this in JavaEE 5, so it might look a little different with injection). Once you have the Application component, you call the createComponent method, passing in the type of component you want to create.
It then becomes an activity of creating components dynamically, configuring them in code and adding them to the parent UIComponent defined via a binding bean. It can be tricky, but it can be done.

How do I access the current TreeNode in primefaces tree (in mark-up or programmatically) without binding to UI component in managed bean?

I am using Primefaces 3.4.1 with the 2.2.0-m05 milestone build of Oracle's JSF 2.2 implementation. I am also using Spring 3.1 for dependency injection and some AOP.
I am trying to use the Primefaces tree component to display a composite of logical filter rules (and allow the user to create composite/leaf nodes at any depth within the composite structure).
Example composite filter:
((location = 'cal') AND (description contains 'test')) OR (project = 'someProject')
Example tree markup:
<p:tree value="#{form.rootComponent}" var="filterComponent" animate="true">
<p:treeNode type="composite">
<!-- some composite specific components -->
</p:treeNode>
<p:treeNode type="leaf">
<!-- some leaf specific components -->
</p:treeNode>
</p:tree>
Although the "value" attribute on the element accepts the root TreeNode (retrieved from a managed bean), the "var" attribute points to the actual data present in the current tree node, rather than the node itself. I would like a way to access the current tree node, not its wrapped data, either in mark-up or programmatically.
If I can access it in mark-up, I can pass it as a method argument to a managed bean. If there's no way of accessing it in the mark-up, can I gain direct programmatic access through a model object? (presumably by gaining access to the underlying tree model?).
I know you can use an expression which resolves to an underlying DataModel instead of the data collection directly as the "value" of h:dataTable, but I believe you can only use the root node itself with p:tree.
I could include a reference to the tree node in the wrapped data object, but I'd really rather avoid nasty circular references if at all possible.
In the absence of a better alternative, I tried using the "binding" attribute to bind the p:tree element directly to a Tree instance in the managed bean (Tree being the UIComponent class for p:tree), which allows me to access the current node via the getTreeNode() method, but I would prefer to avoid this given the lifecycle mismatch between managed beans and view components. It is not working perfectly as is, and I assume there must be a much better, simpler solution.
I also tried using a jsf data table - with nested data tables to handle the composite part - but decided against it given the difficulty in creating a conditionally recursive structure within jsf markup (I believe the "rendered" attribute is not evaluated at view build time so it's difficult to avoid infinite recursion).
Just to clarify, I am only interested in the current tree node containing the data referred to by "var", not the node currently selected by the user.
PF Lead just added a new attribute called "nodeVar" for the p:treeTable (dunno if p:tree is included) as in PF 5.1.10 / 5.2. This feature will allow to get a hold of the actual TreeNode instead of it's data. Hence, one can now perform extra method calls on the node itself, such as TreeNode.isLeaf().
Well, there is an attribute called "selection" in the tree component. You just need to provide a reference to the managed bean method.
For e.g., in your xhtml define the attribute the following way:
selection="#{myManagedBean.selectedNode}"
And with the definition of the above attribute, you will have to provide the usual setter and getter methods in the managed bean that references to org.primefaces.model.TreeNode instance.

Is the ID generated by JSF guaranteed to be the same across different versions and implementations?

We are about to write a full set of tests for one of our JSF applications using Selenium.
So far, it seems that there are two preferred approaches to uniquely identify each element: by ID or using a unique class name. The later is really a hack and doesn't make sense semantically. The former is the right approach, but the element IDs are generated by JSF.
All the different JSF implementations I've seen seem to be using the same approach: use the parent element as the namespace and then concatenate the element ID using a colon. Fair enough.
The question is: do you know if this is guaranteed in some part of the JSF specification? It'd be a real problem to find out later that we need to rewrite all the component selectors in the tests just because JSF x.y changed the way it generates the ID names.
Thanks!
JSF usually generated the ID of components, if ID attribute is not explicitly mentioned.
It will be generated in the format j_idXXX (XXX will be number incremented)
<h:form id="LoginForm">
<h:inputText id="userName" .../>
</h:form>
for this inputText the id will be formed as LoginForm:userName and if id is not mentioned explicitly,then it will be formed something like LoginForm:j_id15
This is mentioned in JSF specification in section 3.1.6, But the exact format is not specified though.
The clientId is generated using this method UIComponent.getClientId(); Follow this link UIComponent
Is the ID generated by JSF guaranteed to be the same across different versions and implementations?
No. You've to explicitly specify the component ID on the UIInput component of interest and all of its parent UINamingContainer components such as <h:form>, <ui:repeat>, <h:dataTable>, etc yourself. Those IDs will by default be woodstocked using separator character :.
However, the separator character is in turn configureable since JSF 2.0. So, if you change the separator character for your webapp from : to - or something, then you'd have to rewrite the selenium tests which are relying on the HTML element IDs.
From the JSF (2.1) spec:
The client identifier is derived from the component identifier
(or the result of calling UIViewRoot.createUniqueId() if there is
not one), and the client identifier of the closest parent component
that is a NamingContainer according to the algorithm specified
in the javadoc for UIComponent.getClientId(). The Renderer
associated with this component, if any, will then be asked to convert
this client identifier to a form appropriate for sending to the
client. The value returned from this method must be the same
throughout the lifetime of the component instance unless setId() is
called, in which case it will be recalculated by the next call to
getClientId().
Aside from the spec, 3rd party plugins can affect the client identifier (e.g. protlet bridge APIs)

Resources