如何在 JSF 中构建“编辑”按钮并在 h:outputText 和 h:inputText 之间切换

aku*_*kub 3 jsf edit conditional-rendering

如何创建“编辑”按钮,以便在单击该按钮时将 更改h:outputTexth:inputText

Bal*_*usC 6

使用rendered属性:

<h:outputText value="#{bean.entity.property}" rendered="#{not bean.editmode}" />
<h:inputText value="#{bean.entity.property}" rendered="#{bean.editmode}" />
...
<h:commandButton value="Edit" action="#{bean.edit}" rendered="#{not bean.editmode}" />
<h:commandButton value="Save" action="#{bean.save}" rendered="#{bean.editmode}" />
Run Code Online (Sandbox Code Playgroud)

在视图范围的 bean 中使用这个:

private boolean editmode;

public void edit() {
    editmode = true;
}

public void save() {
    entityService.save(entity);
    editmode = false;
}

public boolean isEditmode() {
    return editmode;
}

// ...
Run Code Online (Sandbox Code Playgroud)

请注意,由于此答案的第 5 点中提到的原因,处于视图范围内的 bean 很重要:commandButton/commandLink/ajax action/listener method not called or input value not updated


或者,您可以将disabled输入组件上的属性与 CSS 镜头结合使用,这基本上使它看起来像一个输出组件(通过移除边框)。

<h:inputText value="#{bean.entity.property}" disabled="#{not bean.editmode}" />
...
<h:commandButton value="Edit" action="#{bean.edit}" rendered="#{not bean.editmode}" />
<h:commandButton value="Save" action="#{bean.save}" rendered="#{bean.editmode}" />
Run Code Online (Sandbox Code Playgroud)

与例如

input[disabled] {
    border: 0;
}
Run Code Online (Sandbox Code Playgroud)

同样在这里,bean 必须是视图范围的。另请参阅如何选择正确的 bean 范围?