Reset value to null in primefaces autocomplete event

When you modify the text content of the AutoComplete textfield, the search method (aka. completeMethod) will be called on the backing bean. You can reset the value to null there if you get an empty string.

Backing Bean

// insert getter and setter for the device property ...

/** Search for devices by name */
public List<String> deviceComplete(String search) {
    if (StringUtils.isBlank(search)) {
        setDevice(null);  // textfield was cleared, reset device value!
        return Collections.emptyList();
    } else {
        // search for devices ...
        return deviceNames;
    }
}

Note that I used Apache Commons StringUtils.isBlank(String) to check if the string was null or did only contain whitespace characters.

JSF View

In your XHTML file you probably want to listen to any Ajax event to update your view -- or you figure out the event you need (blur, change, whatever) yourself:

<p:autoComplete ...>
    <p:ajax event="itemSelect" listener="..." update="..." />
    <p:ajax process="@this" update="..." />
</p:autocomplete>

I hope this helps.


An alternative could be something like a "clear" or "reset" button next to the search textfield to make it clear to the user that the value will be cleared.


The default autoComplete minQueryLength attribute equals 1 and your search string will be updated when you deleting it until it has lenght of 1 character.

E.g.: You entering 'foo' - and this string is provided to search method (updating after entering first character - minQueryLength = 1)

But when you delete search string - it is also updated until it will have length of 1.

Solution: set attribute minQueryLength="0"

Or:

if you need bigger value add to your autoCompleteMethod(String search) condition:

if (search.length()<={your minQueryLength attribute} )   field = null;