Search code examples
jsf-2primefaces

How to get parametrs to BackingBean from jsf page in <ui:repeat>


My xhtml:

<ui:repeat value="#{c.voices}" var="v"> 
    <h:form enctype="multipart/form-data">  
        <p:fileUpload fileUploadListener="#{AddNote.handleFileUpload}"
            converterMessage="converterMessage"
            mode="advanced"  
            update="messages"  
            sizeLimit="100000"                                                 
            allowTypes="/(\.|\/)(gif|jpe?g|png)$/">
        </p:fileUpload>  
        <p:growl id="messages" showDetail="true"/>                                     
    </h:form> 
</ui:repeat>

My BackingBean:

 public void handleFileUpload(FileUploadEvent event) {
    //int v.id= here i need to know the v.id value from ui:repeater
    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
}

c.voices is list of objects. Every object have attribute id. I need to know the id in handelFileUpload how can I achieve that?


Solution

  • I would simply put v.id in an hidden field :

    Your xhtml:

    <ui:repeat value="#{c.voices}" var="v">
        <h:form enctype="multipart/form-data">
            <input type="hidden" name="vid" value="#{v.id}" />
            <p:fileUpload fileUploadListener="#{AddNote.handleFileUpload}"
                converterMessage="converterMessage"
                mode="advanced"
                update="messages"
                sizeLimit="100000"
                allowTypes="/(\.|\/)(gif|jpe?g|png)$/">
            </p:fileUpload>
            <p:growl id="messages" showDetail="true"/>
        </h:form> 
    </ui:repeat>
    

    And then get it back in the bean using FacesContext :

    Your BackingBean:

    public void handleFileUpload(FileUploadEvent event) {
        HttpServletRequest request = (HttpServletRequest) 
            FacesContext.getCurrentInstance().getExternalContext().getRequest();
        request.getParameter("vid"); // <= Here you are!
    }
    

    UPDATE

    As stated in the comments each iteration will have it's own <h:form with it's own <input type="hidden" name="vid". When a file is uploaded the handleFileUpload will be fired with the data of the enclosing form, thus the vid parameter will be sent with the correct #{v.id}

    UPDATE 2

    As BalusC commented you should preferably get vid parameter this way :

    public void handleFileUpload(FileUploadEvent event) {
         FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get("vid") // <= Here you are!
    }