简体   繁体   中英

JSF/primefaces POJO Autocomplete how to send itemValue to converter

Need to use JSF/primefaces autocomplete with a POJO (say of name,id) to display data and save the information about selected object in DB.

Bean

class BackingBean{
  POJOClass obj;

  getters and setters
}

POJO class

class POJOClass{
  String name;
  int id;

  getters and setters
}

While displaying need to show name in autocomplete suggestion list but while saving need to save both id and name.

Primefaces code

<p:autocomplete value="#{backingbean.obj}" var="object" itemValue="#{object}" itemLabel="#{object.name}"/>

Converter

Class MyConverter ...
{
 public Object getAsObject(FacesContext fc, UIComponent uic, String value){
    String name=value;
    POJO myPOJO=new POJO();
    myPOJO.setName(name);
    myPOJO.setId(???)//need id information as well over here
    return myPOJO;
 }
  public String getAsString(...){
    //returns name to display
  }
}

Able to get only name in getAsObject method of the converter. Also, cannot get object from DB using only name but through id I can.

Note: Don't want to make DB call to get information.

In short aim is to either get id in converter's getAsObject or whole POJO object in converter.Not sure if there is some-other way to achieve this.

Any clues how we achieve that?

Note: I am newbie to JSF/Primefaces.

In short, you want values to persist. For that you can either use a persistent api like jpa or simply save them more globally in global objects like one used for cache whose scope is application level. I think what you are searching is the second option. This object may be initialised when the application starts.

if key found in cache, get the values else execute a db call.

If you have only just one resource like this then you can get know which one POJOClass instance is needed. You can use EL expressions in a managed environment (converters managed by the container). In this case you need just to convert the name field by the converter and access the only one ID via an EL expression:

Class MyConverter ...
{
  public Object getAsObject(FacesContext fc, UIComponent uic, String value)
  {
    String name=value;
    POJO myPOJO=new POJO();
    myPOJO.setName(name);
    myPOJO.setId( getPOJOId() );
    return myPOJO;
 }

 public String getAsString(...)
 {
    //returns name to display
  }

  protected int getPOJOId()
  {
    FacesContext context = FacesContext.getCurrentInstance();
    POJOClass pojo = context.getApplication().evaluateExpressionGet(context, "#{backingBean.obj}", POJOClass.class);
    return pojo.getId();
  }
}

If you have many POJOClass instances, store the ID in a hidden component and access its value to get the ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM