0

I have a need to create command links dynamically based on content coming from elsewhere. When a user clicks on a link it should call a method in a managed bean, and the method needs to know which link was clicked.

I can create the command links using the following code:

JSF: <h:outputText value="#{myBean.dynamicLinks}" escape="false" />

Bean: public String getDynamicLinks(){ // Return an html string that contains a set of <a> elements, based on the dynamic content }

This works fine, but what I can't work out is how my <a> elements can call back into the bean.

Ant Waters
  • 510
  • 1
  • 5
  • 22

1 Answers1

0

This is not the right way to "dynamically" create markup. For that you should be using XHTML, and absolutely not Java and for sure not massage some plain HTML in the model and present it with escape="false". That's plain nonsense. You're basically mingling the view into the model. You need to make the model itself dynamic, not the view. The view must be static and dumb. The view must just present the model to the world. The model itself can be dynamic. You normally achieve that by using a flexible collection, such as List<String>, List<SomeEntity>, etc which you then present using an iterator in the view such as <ui:repeat> or <h:dataTable>.

E.g.

<ui:repeat value="#{bean.links}" var="link">
    <h:commandLink value="link" action="#{bean.action(link)}" />
</ui:repeat>
public void action(Link link) {
    // ...
}

You see, the action method can know about the pressed link by just inspecting the method argument.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • OK, I see the logic of that, but what if my content has a variable structure that I want to represent visually. For example, it might have a tree structure with a variable number of items and levels? In my case, I am representing an equation as a simple list of symbols, but later on I might want to represent it in a more complex graphical format that would be hard to do non-programmatically. – Ant Waters Jun 18 '15 at 11:07
  • As to producing the desired HTML output, there's **nothing** which is impossible with XHTML and only possible with Java. If you can't figure out the right XHTML way to produce the given desired HTML output, just press Ask Question on right top. – BalusC Jun 18 '15 at 12:29