seinecle seinecle - 1 year ago 107
Java Question

how to add a component to the page from a managed bean in jsf / primefaces

A click on a commandButton should trigger an action in a ManagedBean: to add a new "outputText" component to the current page.

The overall idea is to have the page changed dynamically with user action, with server side action because new elements added to the page need data from a db to be laid out.

-> How do I add a component to the page from a managed bean in jsf / primefaces? Let's say that the elements should be added in an existing div like:

<div id="placeHolder">

(this div could be changed to a jsf panel if needs be)

Note: if alternative methods are better to achieve the same effect I'd be glad to learn about them.

Answer Source

I'll provide you another solution apart from the one you posted. Basically it has a List of given outputs, which is increased everytime the button is pushed. That should render exactly the same DOM tree as the solution you stated:

<html xmlns=""
    <h:outputStylesheet name="css/320andup_cle.css" />
        <h:commandButton actionListener="#{bean.createNewTile}" title="new"
            value="new" />

    <h:panelGroup layout="block" id="tiles">
        <ui:repeat var="str" value="#{bean.strings}">
                <h:outputText styleClass="tile" value="#{str}" />
public class Bean {

    List<String> strings = new ArrayList<String>();

    public List<String> getStrings() {
        return strings;

    public void createNewTile() {

Apart from being much simpler IMHO, it has a main advantage: it doesn't couple your server side code to JSF implicit API. You can change the @ManagedBean annotation for @Named if you want it to be a CDI managed bean.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download