Java – Retrieving other component’s client ID in JSF 2.0

clientidjavajsfprimefacesrichfaces

Does JSF 2.0 have a built-in method for finding the client ID of another component? There are about a thousand client ID-related questions on SO and there are a lot of hackish methods to do this, but I'm wondering if JSF 2.0 brought a simpler method that I just don't know.

#{component.clientId} evaluates to a given component's own client ID, but I want to reference another component's ID.

This blog post mentions component.clientId, and it also says #{someComponent.clientId} works, but from what I can tell it does not. I believe he wrote that before any reference implementations of JSF 2.0 were out, so he was just going by the JSR and maybe that functionality changed. I'm not sure.

I know PrimeFaces and RichFaces both have their own functions to return a client ID, but I'm just wondering if there's a built-in JSF 2.0 method for this. Here are some examples:

This works to return the outputText's ID.

`<h:outputText value="My client ID : #{component.clientId}" />`

According to the blog post above, this should work, but it does not. I just get no output.

`<h:button id="sampleButton" value="Sample" />`

`<h:outputText value="sampleButton's client ID : #{sampleButton.clientId}" />`

This works in PrimeFaces:

`<h:outputText value="PrimeFaces : sampleButton's client ID : #{p:component('sampleButton')}" />` 

Works in RichFaces:

`<h:outputText value="RichFaces : sampleButton's client ID : #{rich:clientId('sampleButton')}" />`

Also, if at all possible I'm looking for solutions that won't break if I change the javax.faces.SEPARATOR_CHAR value or if I add/remove containers outside the referenced components. I've spent plenty of time tracking down issues caused by hard-coded ID paths.

Best Answer

You need to assign the component a variable name in the view scope by binding attribute.

<h:button id="sampleButton" binding="#{sampleButton}" value="Sample" />
<h:outputText value="sampleButton's client ID : #{sampleButton.clientId}" />
Related Topic