user3691501
user3691501

Reputation: 53

Submit empty value to bean anyway on input with required="true"

I've the below input with required="true":

<p:inputText value="#{bean.value}" required="true">
    <p:ajax event="change" listener="#{bean.change()}" />
</p:inputText>

When user changes the value, the listener is fired and I can access the changed value. When user empties the field, the listener is not fired and the empty value is not updating in my bean. I gather that this is caused by requried="true". I would like to update my bean with empty value and fire the listener anyway when the user empties the field. How can I achieve this?

Upvotes: 0

Views: 1804

Answers (2)

Tere Hommikust
Tere Hommikust

Reputation: 51

The issue is that if the user clears the required input field then 'required' validator throws an exception and bean setter will not be called. When the form is reloaded then cleared value will show up again from the bean. Here is my workaround:

public String getSomething() {
    return isFormValueEmpty("form:something") ? null : this.something;
}

private Boolean isFormValueEmpty(String formFieldName) {
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    String formValue = ec.getRequestParameterMap().get(formFieldName);
    logger.debug("Check if form value is empty: [{}] [{}]", formFieldName, formValue);
    return StringUtils.isEmpty(formValue);
}

Upvotes: 0

BalusC
BalusC

Reputation: 1109635

You can just use expression language (EL) in the required attribute too. You can then just check if the main submit button of the form has been pressed. Imagine that your form has a "Save" button like below,

<p:inputText ... required="true">
    <p:ajax ... />
</p:inputText>
...
<p:commandButton ... action="#{bean.save}" />

Then you can let the required attribute evaluate true only if the button is invoked. You can achieve that by referencing the component via binding and checking if its client ID is present in the HTTP request parameter map:

<p:inputText ... required="#{not empty param[save.clientId]}">
    <p:ajax ... />
</p:inputText>
...
<p:commandButton binding="#{save}" ... action="#{bean.save}" />

Note that #{save} is as-is and may absolutely not be bound to a backing bean, and that the variable name must be unique in the current view and EL scope.

See also:

Upvotes: 3

Related Questions