2

I want to dynamically create controls in my bean. I am using JSF 2.0

HtmlOutputTag objHtmlOutputTag = new HtmlOutputTag();

Now which property of HtmlOutputTag should I set to set the content of HtmlOutputTag?

ewernli
  • 38,045
  • 5
  • 92
  • 123
TCM
  • 16,780
  • 43
  • 156
  • 254

2 Answers2

6

The HtmlOutputTag represents a tag, not a component. Rather use HtmlOutputText. Then, you can just set the value property, exactly as you would do in a real component in the JSF page. If you need it to be a ValueExpression rather than a raw value, then you need to create it using ExpressionFactory#createValueExpression(). Here's a kickoff example:

HtmlOutputText text = new HtmlOutputText();
text.setValueExpression("value", createValueExpression("#{bean.property}", String.class));

where the convenience method createValueExpression() here look like:

private static ValueExpression createValueExpression(String valueExpression, Class<?> valueType) {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().getExpressionFactory()
        .createValueExpression(context.getELContext(), valueExpression, valueType);
}

hide it far away in some utility class so that you don't need to repeat all that code again and again ;) The valueType argument obviously should represent the actual type of the property.

The final result in the JSF page should then look like this:

<h:outputText value="#{bean.property}" />

That said, depending on the functional requirement, there may indeed be better and cleaner ways to solve the functional requirement. If you want, you can elaborate a bit more about it so that we can if necessary suggest better ways.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I know it's old, but if you need this and you are implementing Omnifaces (thanks @BalusC for that library), you could use Components class http://showcase.omnifaces.org/utils/Components – rekiem87 Aug 06 '14 at 18:26
1

As usual, my advice would be to not add/remove component dynamically. Solve your problem another way:

  • Toggle visibility of components
  • Rebind the data belonging to a component

Adding/removing component dynamically is always a source of trouble and chances are that you can do it another way much simpler.

The outputText component is easy to use:

<h:outputText value="#{BackingBean.myProperty}"/>

And you define a getter/setter for myProperty in your backing bean. If you really want to do it programmatically (which I discourage unless you have strong arguments), here is an example with a dynamic table.

Community
  • 1
  • 1
ewernli
  • 38,045
  • 5
  • 92
  • 123
  • Actually i am primefaces AccordionPanel. It does not allow me to bind items directly. So i am manually creating "RSSFeeds" object and adding to accordion to show news on my webpage – TCM Mar 14 '10 at 02:23