-1

I have question regarding Converter class getAsObject method

I have a service called EmployeeService employeeService

public List<Employees> getEmployees(Employees employees);

If I want to call the above method from getAsObject of Converter class which as arguments

public Object getAsObject(FacesContext facesContext, UIComponent component,
            String value)
    employeeService.getEmployees(<?>)

How do I pass employees object to getEmployees method from getAsObject?

Any help is highly appreciated.

Update 1

@Entity
public class Employees implements Serializable {

private String employeeNumber;
private String employeeName;
Jacob
  • 14,463
  • 65
  • 207
  • 320

1 Answers1

3

Use a following converter, that simply converts number (which is a String, according to your code) to Employee object:

@Named("employeeConverter")
public class EmployeeConverter implements Converter {

    @Inject
    private EmployeeService employeeService;

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if(value == null || value.equals("")) {
            return null;
        }
        Employee employee = employeeService.getEmployeeByNumber(value);//or if it is not a String, replace value with Integer.parseInt(value)
        if(employee == null) {
            throw new ConverterException(new FacesMessage("Employee with number: " + value + " not found."));
        }
        return employee;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Employee) || (value == null)) {
            return null;
        }
        return ((Employee)value).getEmployeeNumber();
    }

}

and use it in your views by converter="#{employeeConverter}".

skuntsel
  • 11,624
  • 11
  • 44
  • 67
  • Like I have mentioned method parameter is of type `Employees' `getEmployees(Employees employees)' so I have to pass employees object, not String – Jacob Feb 22 '13 at 11:22
  • 1
    But the [`Converter` interface](http://docs.oracle.com/javaee/6/api/javax/faces/convert/Converter.html) provides only for a method that uses the signature `public Object getAsObject(FacesContext context, UIComponent component, String value);`. The value is a `String` object. Nothing to do about it. You then convert this string into an object by your service class instance, like in the answer. Maybe you need *another* service that would accept the (already converted from string) object into something else? – skuntsel Feb 22 '13 at 11:49
  • @Polppan you *want* to pass an `Employee` object but **you can't**. As skuntsel says, you can only send a `String` in the `getAsObject` function that contains info to access to the `Employee` info. – Luiggi Mendoza Feb 22 '13 at 15:02