开发者

2 Mutually Exclusive InputComponents Referring to the same Field is updating the same field Twice

I have a screen with 2 JSF Input Components: inputText and inputText with suggestionBox. They are both bound to the s开发者_如何学运维ame field, but only one can be visible/rendered (mutual exclusion).

The thing is that if I write something in one and then submit, the other component which is not displayed is updating the model (the same field is updated again) with it's value (which is empty string or null). To work around this I created another field in my Class, so that the 2 components don't refer to the same field.

I don't like this, because I'm altering my model to solve a GUI problem.

How can I have 2 mutually exclusive input components referring the same value working as I want ?


The key is to use the rendered attribute to show/hide the components so that only one or the other is actually updating the model at a time. Here is a very basic example to illustrate:

<h:form id="exampleForm" prependId="false">

    <h:inputText id="test1" value="#{exampleBean.testString}" rendered="#{exampleBean.toggle}" style="border: 1px solid red;" />
    <h:inputText id="test2" value="#{exampleBean.testString}" rendered="#{!exampleBean.toggle}" style="border: 1px solid blue;" />

    <h:commandButton id="testButton" action="#{exampleBean.toggle()}" />

</h:form>

and the example bean with shared property testString:

@ManagedBean(name = "exampleBean")
@ViewScoped
public class ExampleBean {

    private String testString;

    public String getTestString() { return testString; }

    public void setTestString(String testString) { 
        this.testString = testString; 
        System.out.println(testString);
    }

    private boolean toggle;

    public boolean isToggle() { return toggle; }
    public void setToggle(boolean toggle) { this.toggle = toggle; }

    public void toggle() {
        toggle = (toggle) ? false : true;
    }

}


As I stated I can't use rendered, so in this case using readonly true with visible false gives me the behavior I need. Thanks.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜