Inside c:foreach set transient field of a JPA entity and retrieve it

281 Views Asked by At

I'm new to JSF. I have a c:foreach element that gets an images list from a bean. Each images list element is an Image object (created by me) that has a transient boolean field. This field initially is false. I also have an outputText to show the boolean value. Now I want that when a button is clicked the boolean field is set to true and the outputText is refreshed with the new boolean value. I tried but the boolean value is always false. Is this possible to do? It seems like the image where I set the boolean field is not the same where I get the boolean field, or maybe the image element in the foreach is not updated.

JSF code:

<c:forEach items="#{publicGalleryImageShowController.images}" var="img">
            <h:form>
                <h:commandButton
                    action="#{img.setShowComments(true)}"
                    value="Show/Hide">
                    <f:ajax render="co-#{img.id}" />
                </h:commandButton>
            </h:form>

            <h:panelGroup id="co-#{img.id}">
                <h:outputText value="#{img.showComments}" />
            </h:panelGroup>
</c:forEach>

Java Image class with JPA annotation:

@Entity
public class Image {
    private boolean showComments;
    /*other fields*/

    @Transient
    public boolean isShowComments() {
        return showComments;
    }
    public void setShowComments(boolean showComments) {
        this.showComments = showComments;
    }   

    /*other getters and setters*/
}
1

There are 1 best solutions below

2
Simon Martinelli On

BalusC is right.

Your code is working

action="#{img.setShowComments(true)}"

I created a demo app on GitHub: https://github.com/simasch/46756639

Please check it out.