Berrisford
Berrisford

Reputation: 126

How to retrieve Primefaces autocomplete pogo selected item in backing bean

I'm attempting to learn Primfaces. I'm curently using the autocomplete control (with Pojo). The display works fine. What I've been struggling with is retrieving the selected object and accessing any of it properties. Whenever I attemp to access the selected object's properties in the bean, I get a nullPointerException. Can anybody help me with this (please)? My code is based on the Primefaces simple pojo example at: (http://www.primefaces.org/showcase-labs/ui/autoCompletePojo.jsf). My web page looks like so:

<h:form id="form">
<p:growl id="msg" showDetail="false"/>
<p:panel header="Test Form" toggleable="true">
        <h:outputLabel value="Player(s): " for="basicPojo" />
        <p:autoComplete value="#{autoCompleteBean.selectedPlayers}" 
                    id="basicPojo" completeMethod="#{autoCompleteBean.completePlayer}"
                    var="p" itemLabel="#{p.name}" itemValue="#{p}" converter="player" forceSelection="true" multiple="true">
            <p:ajax event="itemUnselect" listener="#{autoCompleteBean.handleUnselect}" />
            <f:facet name="itemtip">
                <h:panelGrid  columns="2" cellpadding="5">
                    <h:outputText value="eScholarId: " />
                    <h:outputText id="id-output" value="#{p.name}" />

                    <h:outputText value="Name: " />
                    <h:outputText id="name-output" value="#{p.number}" />

                    <h:outputText value="Email: " />
                    <h:outputText id="email-output" value="#{p.position}"/>
                </h:panelGrid>
            </f:facet>
        </p:autoComplete>

        <p:commandButton value="Submit" update="msg" action="#{autoCompleteBean.doMessage}"></p:commandButton>

</p:panel>

and I've edited the Primefaces autoCompleteBean to add the following method:

    public void doMessage(){
    String txt = "dummy text";
    txt = this.selectedPlayers.get(0).getName();
    FacesMessage msg = new FacesMessage(txt);
    FacesContext.getCurrentInstance().addMessage(null, msg);
}

I've added in the converter in the faces.config file as normal.

Upvotes: 1

Views: 2419

Answers (1)

djmj
djmj

Reputation: 5544

It seems you bind a collection to the value of the autocomplete.

<p:autoComplete value="#{autoCompleteBean.selectedPlayers}"/>

But you should bind a single instance to the value attribute.

private Player selectedPlayer;

// getter and setter

<p:autoComplete value="#{autoCompleteBean.selectedPlayer}"/>

In your method invoked by the submit button you can simply access it via this.selectedPlayer.

Upvotes: 1

Related Questions