Primefaces autocomplete keep selected dropdown value

I have a Primefaces autocomplete box, and have the requirement to keep the value of the dropdown list on the selected value, for example I have a list with 20 elements and I select the 10 element.

enter image description here

If I want to select another value when I select the dropdown It starts on the beginning of the list:

enter image description here

This is my primefaces code:

<p:autoComplete id="transportLAvailable" dropdown="true"
    value="#{remissionOrderReportController.selectedTLineFilter}"
    forceSelection="true" requiredMessage="Some message"
    completeMethod="#{remissionOrderReportController.searchFromTLinesList}"
    var="transportFiltered" itemLabel="#{transportFiltered.name}"
    itemValue="#{transportFiltered}" converter="#{transportLineConverter}">
        <p:ajax event="itemSelect" process="@this"
        listener="#{remissionOrderReportController.findVehicleByTL(transportFiltered)}"/>
</p:autoComplete>

I don't have problems saving the values, just with the view.

¿Is there a way to do this on an attribute of p:autoComplete or javascript?

Upvotes: 2

Views: 903

Answers (1)

Jasper de Vries
Jasper de Vries

Reputation: 20263

The trick is to simply include the current value at the top of the returned list. I do it like this:

public List<T> autoCompleteItems(final String query) {
  List<T> results = ...; // Find results for the query
  addBoundValue(Components.getCurrentComponent(), results);
  return results;
}

protected void addBoundValue(UIInput input, List<T> results) {
  if (input.getValue() != null && typeTclass.isAssignableFrom(input.getValue().getClass())) {
    T bound = typeTclass.cast(input.getValue());
    results.remove(bound); // If it's already in the list, remove it first
    results.add(0, bound); // Add the value at the top of the list
  }
}

This code comes from a generic bean which uses the type of the list as a parameter (type is set in the constructor to typeTclass).

Please note that I'm using OmniFaces to get the current component. It will get you the the p:autoComplete component, from which you can read the value.

If you can't use OmniFaces, please read How to find out the calling component in the getter method?

Upvotes: 2

Related Questions