In JSF I need to check if a component is within a facet with name "foo". I've written the following code to test whether the component is inside a facet:
boolean insideFacet = false;
UIComponent parent = uiComponent.getParent();
if (parent != null) {
UIComponent grandparent = parent.getParent();
if (grandparent != null) {
UIComponent facet = grandparent.getFacet("foo");
if (facet != null && facet.equals(parent)) {
insideFacet = true;
}
}
}
This code works correctly (i.e. insideFacet equals true) when there are multiple tags within the f:facet:
<example:container>
<f:facet name="foo">
<example:componentInFacet />
<h:outputText value="text" />
</f:facet>
</example:container>
However, insideFacet equals false when there is only one component within the f:facet:
<example:container>
<f:facet name="foo">
<example:componentInFacet />
</f:facet>
</example:container>
What am I missing?
According to the source code of mojarra and myfaces---the two implementations of JSF---when only one component is within a facet, that component is the facet. So you need to modify your code to check if the facet is the component like so:
UIComponent facet = parent.getFacet("foo");
if (facet != null && facet.equals(uiComponent)) {
insideFacet = true;
}
Putting that together with your code:
boolean insideFacet = false;
UIComponent parent = uiComponent.getParent();
if (parent != null) {
UIComponent facet = parent.getFacet("foo");
if (facet != null && facet.equals(uiComponent)) {
insideFacet = true;
}
else {
UIComponent grandparent = parent.getParent();
if (grandparent != null) {
UIComponent facet = grandparent.getFacet("foo");
if (facet != null && facet.equals(parent)) {
insidefacet = true;
}
}
}
}
Note: It seems like the JSF spec requires that the first component added to a facet be named as the facet (see: Section 9.2.3). I can't seem to find any spec language about how the implementation should handle multiple components within a facet though. I think it is safe to rely on this behavior anyway since it hasn't changed since JSF 2.0 and it is the same in both JSF implementations. If anyone finds information specifying how implementations are to handle multiple components within facets in the JSF spec, please comment and I'll add it to my answer.
Note 2: I have not tested this method on composite components, so it may not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With