0

I am trying to make a custom JSF converter for my category model. The value I get from the field and to the converter is an category id. Should I retrieve the category by that ID, and return that object? I have tried injecting an entitymanager but that did not work, since it is not managed. I was able to find a post where a guy did it, but I don't know if it is usual to inject entitymanagers into converters.

Or should I override the toString method in the Category class, and return a string such as

2, "long description"

and then use the toString as value in the fields. When I want it back to an object I split it and use the setters on the category object. I have not worked with converters before so I don't know if this is any better?

LuckyLuke
  • 42,935
  • 77
  • 254
  • 416

1 Answers1

2

I have tried injecting an entitymanager but that did not work, since it is not managed

Not being able to inject an EntityManager (or, better, an @EJB) inside a @FacesConverter was an oversight in JSF spec and is scheduled to be fixed for upcoming JSF 2.2 which should be released by end of Q1 2012.

The workaround is to make the converter a @ManagedBean or a @Named bean instead, or to manually grab the EJB by JNDI.

Or should I override the toString method in the Category class and then use the toString as value in the fields. When I want it back to an object I split it and use the setters on the category object.

No, absolutely don't do that. You're mingling view with the model this way. Use a fullworthy Converter.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Okey, so I am not doing anything "wrong" when I inject the EJB in a converter? – LuckyLuke Dec 20 '11 at 16:11
  • No. It's going to be able "out the box" as per the upcoming JSF 2.2 anyway. See also the "see also" link for detail and another link to my blog :) – BalusC Dec 20 '11 at 16:12
  • Then I will try it. I started to read your blog post about converters some hours ago but was interupted :) – LuckyLuke Dec 20 '11 at 16:15