开发者

change value in backing bean not reflected in UI

开发者 https://www.devze.com 2023-01-29 20:50 出处:网络
The component is wired via value binding to a backing bean property. <h:inputText id=\"number\" value=\"#{backingBean.number}\" validator=\"#{backingBean.validateNumber}\" />

The component is wired via value binding to a backing bean property.

<h:inputText id="number" value="#{backingBean.number}" validator="#{backingBean.validateNumber}" />

In the validation method the number value is changed

public void validateNumber(FacesContext facesContext, UIComponent component, Object value) {
    String inputValue = (String) value;

    if (inputValue.length() == 9) {
        inputValue = "0" + inputValue;
        ((UIInput) component).setSubmittedValue(inputValue);
        ((UIInput) component).setValue(inputValue);
        setNumber(inputValue);
    }
}

While debugging I can verify that the value is in fact being changed but during the rendering phase the new value is somehow overridden by the old value. This must have something to do with me misunderstanding the JSF lifecycle, but the way I see it I am changing both the value op the property to wh开发者_StackOverflow中文版ich to component is bound in the UI and because I have a hook to the actual component I also change the component's value and submittedValue to be sure (to find the problem) and still the change isn't reflected int he UI?

Any ideas??


You're using the wrong tool for the job. You should use a Converter for this, not a Validator. A validator is to validate the value, not to change (convert) the value.

public void EnterpriseNumberConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value.length() == 9) {
            value = "0" + value;
        }
        return value;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return (String) value;
    }

}

As to why it isn't possible in a validator, this is what is basically happening:

  • Phase 2: apply request values (input is UIInput and request is HttpServletRequest)

    input.setSubmittedValue(request.getParameter(input.getClientId()));
    
  • Phase 3: validation phase.

    Object value = input.getSubmittedValue();
    try {
        value = input.getConvertedValue(facesContext, value);
    } catch (ConverterException e) {
        // ...
        return;
    }
    try {
        for (Validator validator : input.getValidators())
            validator.validate(facesContext, input, value);
        }
        input.setSubmittedValue(null);
        input.setValue(value); // You see?
    } catch (ValidatorException e) {
        // ...
    }
    
  • Phase 4: update model values phase.

    bean.setProperty(input.getValue());
    
0

精彩评论

暂无评论...
验证码 换一张
取 消