seinecle seinecle - 4 months ago 22
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">
</div>


(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

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="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
    <title>Tiles</title>
    <h:outputStylesheet name="css/320andup_cle.css" />
</h:head>
<h:body>
    <h:form>
        <h:commandButton actionListener="#{bean.createNewTile}" title="new"
            value="new" />
    </h:form>

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

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

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

    public void createNewTile() {
        strings.add("output");
    }
}

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.