Seam Converter de Entity

20 11 2008

O Problema

Exibir apenas uma coluna de uma determinada entidade, por exemplo exibir o nome de uma pessoa.

A Solução

package br.unioeste.sgppls;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.persistence.EntityManager;

import org.jboss.seam.annotations.Name;

@Name("ConverterEntityarConhecimento")
@org.jboss.seam.annotations.faces.Converter
public class ConverterEntityarConhecimento implements Converter {

	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		try {
			EntityManager entityManager = (EntityManager) org.jboss.seam.Component
				.getInstance("entityManager", true);
			Object o = entityManager.createQuery(
				"from ArConhecimento ar WHERE ar.arCnhCodigo = :codigo")
				.setParameter("codigo", arg2).getSingleResult();
			return o;
		} catch (Exception e) {
			throw new ConverterException(e);
		}
	}

	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		try {
			ArConhecimento a = (ArConhecimento) arg2;
			return a.getArCnhCodigo();
		} catch (Exception e) {
			throw new ConverterException(e);
		}
	}
}

A Visão

Meu campo input esta ligado diretamente com o atributo que é uma outra entidade, sendo assim é necessário usar o conversor para exibir a coluna de ‘descrição’

<h:inputText value="#{projetoHome.instance.arConhecimento}" id="text" size="15" converter="ConverterEntityarConhecimento" required="true"/>




Seam Converter Boolean Sim/Não

20 11 2008

O Problema

Converter atributos do tipo Boolean em String SIM caso true e NÃO caso false.

A Solução

package br.unioeste.sgppls;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

@Name("ConverterBooleanString")
@BypassInterceptors
@org.jboss.seam.annotations.faces.Converter

public class ConverterBooleanString implements Converter {

   public Object getAsObject(FacesContext arg0, UICompon   ent arg1, String arg2) {
      try {
         if (arg2.equalsIgnoreCase("sim")) {
            return new Boolean(true);
         } else
            return new Boolean(false);
      } catch (Exception e) {
            throw new ConverterException (e);
      }
   }

   public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
      try {
         if (((Boolean)arg2) == true) {
            return "Sim";
         } else
            return "Não";
      } catch (Exception e) {
         throw new ConverterException (e);
      }
   }
}

Na Visão

projetoHome.instance.prjPago é do tipo Boolean e na visão deve aparecer a String humanizada, então:

<h:outputText value="#{projetoHome.instance.prjPago}" converter="#{ConverterBooleanString}"/>