开发者

Why input (for example h:inputText) nested in h:dataTable do not update Bean model? [duplicate]

This question already has an answer here: Using <h:dataTable><h:inputText> on a List<String> doesn't update model values (1 answer) Closed 6 years ago.

I have jsf page:

....
<form jsfc="h:form" action="">
  <h:dataTable value="#{newMusician.strings}" var="preferredMusicGenre" id="musicGenresSelectTable">
    <h:column>
      <h:inputText value="#{preferredMusicGenre}" immediate="true"/>
     </h:column>
   </h:dataTable>
   <p>
      <input type="submit" jsfc="h:commandButton" value="Add" action="#{newMusician.saveNewMusician}"/>
   </p>
</form>
....

And managed bean that has ArrayList of Strings:

@ManagedBean
@ViewScoped
public class NewMusician {

    private ArrayList<String> strings = new ArrayList<String>();

    public NewMusician() {
        strings.add("olo");
    }
    public ArrayList<String> getStrings() {
        return strings;
    }
    public void saveNewMusician() {
    .....
    }
....
}

Problem: When I change text in and press save button, in saveNewMusician() method I can see that ArrayList "strings" contain the same old value "olo", but not that one I inserted in input field. The same problem if use h:selecOneMenu.

Situation is changed if use not string, but object that aggregate string and set value into string. So if I'll use some POJO and change inputText to:

<h:inputText value="#{preferredMusicGenrePojo.string}" immediate="true"/>

Everything becomes Ok.

Question: Why usage of 1 level getter <h:inputText value="#{preferredMusicGenre}"/> is incorrect开发者_运维百科, but usage of 2 level getter: <h:inputText value="#{preferredMusicGenrePojo.text}"/> is Ok?


A String is immutable. It doesn't have a setter for the value. You need to wrap this around in a bean (or POJO as you call it).

public class Musician {
    private String preferredGenre; 

    // Add/generate constructor, getter, setter, etc.
}

Then change your managed bean as follows.

@ManagedBean
@ViewScoped
public class NewMusician {

    private ArrayList<Musician> musicians = new ArrayList<Musician>();

    public NewMusician() {
        musicians.add(new Musician("olo"));
    }

    public ArrayList<Musician> getMusicians() {
        return musicians;
    }

    public void saveNewMusician() {
        // ...
    }

    // ...
}

And your datatable:

<h:dataTable value="#{newMusician.musicians}" var="musician">
    <h:column>
        <h:inputText value="#{musician.preferredGenre}" />
    </h:column>
</h:dataTable>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜