views:

1014

answers:

3

I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.

included.xhtml

<ui:component>
  <h:inputText id="contained_field"/>
  <h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>

example_containing.xhtml

<h:form id="containing_form">
  <ui:include src="/included.xhtml"/>
</h:form>

How may I determine the ID of the form in the update method at runtime? Or better yet, the ID of the input field directly.

+5  A: 

Bind the button to your backing bean, then use getParent() until you find the nearest form.

jsight
That's what I was afraid of. I was hoping for something cleaner.
sblundy
A: 

Programmatically I would use jsight's method. You can know the id of your elements (unless you let JSF create them, I don't know the means for numbering in the ids) by looking at it. h:form is a naming container so as long as you don't have it wrapped in another naming container it will be containingForm:containedfield The ':' is the naming separator by default is JSF and the ids are created like this, roughly anyway, (parentNamingContainerId:)*componentId

A: 

Since update method is of type actionListener, you can access your UI component as follows

public void update(javax.faces.event.ActionEvent ac) {
      javax.faces.component.UIComponent myCommand = ac.getComponent( );
      String id = myCommand.getId(); // get the id of the firing component

      ..... your code .........

}