How to validate two fields on the same validator
cash1981 May 11, 2009 10:19 AMHi.
I have a User table with UniqueContraint on (username, organization). Meaning that the combination of these two are unique.
However, I also have a seam validator that checks if this is unique before posting the form.
Here is a snip of the form.
<s:decorate template="/layout/definition.xhtml"> <ui:define name="label">#{messages['username']}</ui:define> <h:inputText required="true" value="#{userAdmin.currentUser.username}" rendered="#{userAdmin.currentUser.username == null}"> <f:validator validatorId="usernameValidator"/> <s:validate /> </h:inputText> <h:inputText disabled="true" value="#{userAdmin.currentUser.username}" rendered="#{userAdmin.currentUser.username != null}" /> </s:decorate> <s:div rendered="#{s:hasRole('sysadmin')}"> <s:decorate template="/layout/definition.xhtml"> <ui:define name="label">#{messages['organization']}</ui:define> <h:selectOneMenu value="#{userAdmin.currentUser.organization}" > <s:selectItems value="#{organizations}" noSelectionLabel="#{messages['organization.none']}" var="kommune" label="#{kommune.name}"/> <f:converter converterId="restrictedEntityConverter" /> </h:selectOneMenu> </s:decorate> </s:div>
My UniqueUsernameValidator
@Name("usernameValidator") @Validator @BypassInterceptors @Transactional public class UniqueUserValidator implements javax.faces.validator.Validator, Serializable { private static final long serialVersionUID = 6086572792387091314L; @SuppressWarnings("unchecked") public void validate(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException { EntityManager entityManager = (EntityManager) Component.getInstance("entityManager"); String newUsername = "" + value; ProcessUser kommuneAdmin = (ProcessUser) Component.getInstance("currentUser"); if (kommuneAdmin != null && kommuneAdmin.getOrganization() != null) { List<ProcessUser> users = entityManager.createQuery( "SELECT DISTINCT p FROM " + ProcessUser.class.getName() + " p where lower(p.username) = :name" + " AND p.organization.id = :orgId").setParameter("name", newUsername.toLowerCase()).setParameter("orgId", kommuneAdmin.getOrganization().getId()).getResultList(); if (!users.isEmpty()) { Map<String, String> messages = Messages.instance(); throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.get("admin.userexists"), messages.get("admin.userexists"))); } } } }
Now the thing is that I can in the usernameValidator recieve the username, however I don't know how to send the organization as a parameter too.
Any tips?