krystah
krystah

Reputation: 3733

JSF form value disappears on submit

When I try to submit a form, the input value is present in the validation-method, but gone in the submit-method. Why the input-property blank by the time the program reaches the submit-function?

Input: asdf


genres.xhtml

<h:form>
    <h:inputText 
        id="userGenre"
        value="#{genres.input}"
        validator="#{genres.validateLength}"
        required="true" size="3"
        />
    <h:commandButton 
        value="Add genre"
        action="#{genres.submit}" 
        />
    <h:message for="userGenre" />
</h:form>


Genres.java

@Named
@SessionScoped
public class Genres {

    static final Logger LOG = LoggerFactory.getLogger(Genres.class);

    private String input = "";

    public void validateLength(FacesContext context, UIComponent toValidate, Object value) {
        LOG.info("Validating");

        input = (String) value;
        LOG.info("name:"+input); // result: "name:asdf"

        int min = 3;
        int max = 15;
        int len = input.length();
        if (len < min || len > max) {
            ((UIInput) toValidate).setValid(false);
            FacesMessage message = new FacesMessage("Must be at least 3 and at most 15 characters.");
            context.addMessage(toValidate.getClientId(context), message);
            return;
        }
    }

    public void submit() {
        LOG.info("Submitting");
        LOG.info("name:"+input); // result: "name:"

        // process input
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

}


faces-config.xml

<managed-bean>
    <managed-bean-name>genres</managed-bean-name>
    <managed-bean-class>no.krystah.Genres</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <managed-property>
        <property-name>input</property-name>
        <property-class>java.lang.String</property-class>
        <value/>
    </managed-property>
</managed-bean>

Upvotes: 1

Views: 553

Answers (1)

void
void

Reputation: 7890

in the #{genres.submit} when you try to submit then JSF will generate a new instance of your Genres class so input is blank but if you use @ManagedBean annotation on the top of your Genres class I think the code should work well

Upvotes: 1

Related Questions