Search code examples
jsfruntimeloadingcomposite-component

Adding JSF 2 composite component at runtime from backing bean


Edited question...

Hello,

I would like to load a .xhtml file of my composite component from a backing bean, and add it to the page dynamically. The name of the .xhtml file comes form a variable.

Ex.:

public MyBean (){

    String componentFile = "myCompositeComponent.xhtml"

    public String addComponentToPage(){

          //how do that?...

          return null;
    }

} 

Thank you!


Solution

  • That's not possible. A composite component is template-based and can only be used in views. Your best bet is to repeat exactly the JSF code which you've originally written in the composite component in the model. Better would be to create a full worthy @FacesComponent class which extends UIComponent, complete with a @FacesRenderer. True, it's a tedious and opaque job, but this way you'll end up with a component which is reuseable in both the view and the model by a single code line.

    An -ugly- alternative is to place all possible components in the view and use the rendered attribute.

    <my:component1 rendered="#{bean.myComponentType == 'component1'}" />
    <my:component2 rendered="#{bean.myComponentType == 'component2'}" />
    <my:component3 rendered="#{bean.myComponentType == 'component3'}" />
    ...
    

    Wrap this if necessary in a Facelets tag file so that it can be hidden away and reused in several places.