Marko Ćilimković
Marko Ćilimković

Reputation: 753

Concating values from multiple output and input components

I have 2 outputText fields, 1 required field and 1 optional field. How can I concat, or append all of the values and set it as a single model property?

<h:outputText value="AT-" />
<h:outputText value="#{yearOfDate}"/>
<p:inputMask value="#{requiredRefNo}" required="true" mask="9999"/>
<p:inputMask value="#{optionalRefNo}" mask="aa"/>

In the given example I have for example the string AT-2012-6060-VI. How can I append all of the values and set it as a single model property?

Upvotes: 1

Views: 311

Answers (1)

BalusC
BalusC

Reputation: 1108632

For you it would probably be the easiest to create a composite component for this with a backing component which extends UIInput and wherein the desired format is returned by UIInput#getSubmittedValue().

Here's a kickoff example in its simplest form:

/resources/components/refNo.xhtml

<ui:component
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:cc="http://java.sun.com/jsf/composite"
    xmlns:p="http://primefaces.org/ui"
>
    <cc:interface componentType="refNoComposite" />
    <cc:implementation>    
        AT-#{cc.year}-<p:inputMask id="ref1" required="true" mask="9999"/>-<p:inputMask id="ref2" mask="aa"/>
    </cc:implementation>
</ui:component>

com.example.RefNoComposite

@FacesComponent("refNoComposite")
public class RefNoComposite extends UIInput implements NamingContainer {

    public RefNoComposite() {
        getStateHelper().put("year", new SimpleDateFormat("yyyy").format(new Date()));
    }

    @Override
    public String getFamily() {
        return UINamingContainer.COMPONENT_FAMILY;
    }

    @Override
    public Object getSubmittedValue() {
        return new StringBuilder()
            .append("AT")
            .append('-')
            .append(getYear())
            .append('-')
            .append(((UIInput) findComponent("ref1")).getSubmittedValue())
            .append('-')
            .append(((UIInput) findComponent("ref2")).getSubmittedValue())
            .toString();
    }

    public String getYear() {
        return (String) getStateHelper().eval("year");
    }

}

Usage example in a random Facelets page:

xmlns:cc="http://java.sun.com/jsf/composite/components"
...
<h:form>
    <cc:refNo value="#{bean.value}" />
    <p:commandButton value="submit" action="#{bean.submit}" />
</h:form>

Note: if you'd like to validate the value as well, you'd like to override the UIInput#validateValue() method in the backing component. The 2nd argument is by the way exactly the getSubmittedValue().

Upvotes: 1

Related Questions