Toby Samples
Toby Samples

Reputation: 2178

Insert/Add JSF component at render time

Is it possible to add a child component during render? If not what would be the best practice to add a child component dynamically in a JSF 1.2 Environment? Thanks

Upvotes: 2

Views: 1035

Answers (1)

gersonZaragocin
gersonZaragocin

Reputation: 1202

The better place where you can do that is in a PhaseListener implementation.

For instance the next code snippet samples how you can add a new component in to the view root:

public class ViewModifierPhaseListener implements
        javax.faces.event.PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
    }

    // Just sampling add component on ViewRoot
    @Override
    public void beforePhase(PhaseEvent event) {
        // Gets the target component from ViewRoot
        UIViewRoot viewRoot = event.getFacesContext().getViewRoot();
        UIComponent parent = viewRoot.findComponent("parentComponentId");
        // UIComponents to create depend on JSF implementation, 
        // Try to use the available factories when suplied by the implementation
        UIComponent child = Factory.getComponent("ComponentClassName");
        // Customize the component, for instance it has to be disabled
        child.getAttributes().put("disabled", true);
        // Adds the fresh created component to the parent
        parent.getChildren().add(child);
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }
}

Please note that getPhaseId returns the RENDER_RESPONSE phase because in that phase is where you have the components tree complete.

Your phase listener definition has to be set in the faces-config.xml's lifecycle element like this:

<lifecycle>
    <phase-listener>your.package.ViewModifierPhaseListener</phase-listener>
</lifecycle>

Or if you work with facelets you could define it in the template of the pages you want to be affected by your listener. This helps you to discriminate when to execute your PhaseListener.

<f:phaseListener type="your.package.ViewModifierPhaseListener"/>

Upvotes: 1

Related Questions