Aliuk
Aliuk

Reputation: 1377

Pass a parameter to dropzone save method using JSF

I have written the question about how to use dropzone.js with JSF (Use dropzone with JSF) and it was correctly answered by BalusC.

However I want to pass a parameter to the save() method and I am not able to do it. I have the dropzone component in a page similar to this: http://localhost:8080/application/image-album.xhtml?albumId=1

And in that page I have:

<h:form id="uploadForm" enctype="multipart/form-data" styleClass="dropzone">
            <div class="fallback">
                <h:inputFile id="file" value="#{uploadImageController.part}"/>
                <h:commandButton id="submit" value="submit" />
            </div>
        </h:form>

And in the UploadImageController I have:

@PostConstruct
public void init() {
  ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
  albumId = Long.valueOf(externalContext.getRequestParameterMap().get("albumId"));
}

So theoretically I could use the albumId in the save() method. However the init() method is being called three times, the first time with the value 1 and the other two with the value null so it fails by NullPointerException.

Any workaround to this?

Upvotes: 1

Views: 390

Answers (1)

BalusC
BalusC

Reputation: 1109635

GET request parameters can be set as bean property using <f:viewParam>.

<f:metadata>
    <f:viewParam name="albumId" value="#{bean.albumId}" />
</f:metadata>

If you're using a @ViewScoped bean, then this will be remembered across all JSF POST form submits (postbacks) on the same view. If you're however using a @RequestScoped bean, then bean properties can be retained across postbacks using <h:inputHidden>.

<h:form ...>
    <h:inputHidden value="#{bean.albumId}" />
    ...
</h:form>

This only doesn't work properly when there's a conversion/validation failure on the form. If you're using conversion/validation on the very same form, then better use plain HTML <input type="hidden">.

<h:form ...>
    <input type="hidden" name="albumId" value="#{bean.albumId}" />
    ...
</h:form>

The <f:viewParam> will take care that the bean property is properly set. There's no need to manually fiddle with getRequestParameterMap() the old fashioned JSF 1.x way.

See also:

Upvotes: 2

Related Questions