adwilk
adwilk

Reputation: 61

dynamically add and remove panels PrimeFaces

How would you go about dynamically adding panels in primefaces?

The goal is to have a button to add panels. Removing panels is easy to with the closeable option in the following code:

<p:panel id="panel1" header="Panel 1" style="width : 150px;" toggleable="true" closable="true" toggleSpeed="500" closeSpeed="500"> Move and Resize ME!</p:panel>

Upvotes: 1

Views: 9503

Answers (2)

Serkan Arıkuşu
Serkan Arıkuşu

Reputation: 5619

Assuming that you have a panelgrid to hold the panels, a simple jsf fragment would be

<p:panelGrid id="myPanelGrid" columns="1">
</p:panelGrid>

<h:form>
    <p:commandButton value="Add Panel" actionListener="#{bean.addPanel}" update=":myPanelGrid" />
</h:form>

In your backing bean, an addPanel method needed for dynamically adding panels

public void addPanel(ActionEvent event) {
    UIComponent component = FacesContext.getCurrentInstance().getViewRoot().findComponent("myPanelGrid");
    if (component != null) {
        Panel p = new Panel();
        p.setClosable(true);
        p.setHeader("Test");
        p.setVisible(true);
        component.getChildren().add(p);
    }
}

This method will find your holder panelgrid component by its id, add a new org.primefaces.component.panel.Panel and set a few fields and add it to the parent component.

The update=":myPanelGrid" property of your commandButton will inform the panelGrid to update itself with the new data.

Upvotes: 9

Alexandre Jacob
Alexandre Jacob

Reputation: 3041

Simply I would nest my <p:panel in a <h:panelGroup with a rendered attribute this way :

<h:panelGroup id="myPanelGroup">
    <p:panel rendered="#{myBean.renderPanel}">
        <span>Content</span>
    </p:panel>
</h:panelGroup>
<p:commandButton action="#{myBean.showPanel()}" update="myPanelGroup"
    value="Show Panel" />
<p:commandButton action="#{myBean.hidePanel()}" update="myPanelGroup"
    value="Hide Panel" />

The Bean :

@ManagedBean
@ViewScoped
public class MyBean {

    private boolean renderPanel;

    public void showPanel() {
        this.renderPanel = true;
    }

    public void hidePanel() {
        this.renderPanel = false;
    }

    // Getter for renderPanel
}

Note : It would be even better to avoid using @ViewScoped here depending on your needs, you could bind renderPanel in a form (eg a checkbox)

Upvotes: 1

Related Questions