3
votes

CASE: the form contains input text for entering department name (can't be null or blank), and drop down list for selecting parent department (can be null), when entering data, and pressing clear, the clear method in backing bean works fine as expected, but when not entering data and pressing clear, the bean validation for not blank on the name works and validation message appears, and i want to disable the validation in case of clearing.

  1. View Code:


    Department Name:

    <h:outputLabel>Parent Department:</h:outputLabel>
        <ice:selectOneMenu id="parentDepartment" value="#{department.selectedParentDepartment}">               
          <f:selectItem/>
          <f:selectItems value="#{departmentBean.departmentList}" var="dept" 
           itemLabel="#{dept.name}" itemValue="#{dept.id}" />                            
        </ice:selectOneMenu> 
        <h:message for="parentDepartment" style="color:red" />        
    
    <ice:panelGroup>
        <h:commandLink value="Add New" action="#{departmentBean.addOrUpdateDepartment}" />
        <h:commandLink value="Add New" actionListener="#{departmentBean.clear}" />
    </ice:panelGroup>
    

  2. Bean Validation:

    @NotBlank(message = "{name.required}") @Size(max = 25, message = "{long.value}") @Column(name = "name", length = 25, nullable = false) private String name;

  3. Backing Bean Method:

    public void clear() { setDepartmentObj(new Department()); setSelectedParentDepartment(0); }

2

2 Answers

6
votes

You can let it refresh the entire view instead:

<h:commandLink value="Clear" action="#{bean.clear}" immediate="true" />

with

public String clear() {
    return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true";
}

The immediate="true" will skip processing (and validation) of all input components which doesn't have immediate="true".

Alternatively, a piece of JavaScript to reload the page should also do:

<h:commandLink value="Clear" onclick="window.location.reload(); return false;" />

Update as per the comments you want a partial request, then just use ajax:

<h:commandLink value="Clear" action="#{bean.clear}">
    <f:ajax execute="@this" render="@form" />
</h:commandLink>

with

public void clear() {
    field1 = null;
    field2 = null;
    // ...
}

Because the execute is set to @this (which is already the default value by the way, so you can omit it), it won't process the entire form.

0
votes

Some components have a valueChangeListener. Try to work with that one. However I'm not sure if that will trigger the validation as well.