如何建立“编辑"页面JSF中的按钮,并在h:outputText和h:inputText之间切换

如何建立“编辑

问题描述:

如何创建一个编辑"按钮,以便在单击该按钮时将h:outputText更改为h:inputText?

How can I create an "edit" button so that when the button is clicked it will change the h:outputText to h:inputText?

使用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}" />

在视图范围内的bean中使用它:

With this in a view scoped bean:

private boolean editmode;

public void edit() {
    editmode = true;
}

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

public boolean isEditmode() {
    return editmode;
}

// ...

请注意,由于此答案的第5点中提到的原因,被视图作用域化的bean很重要:

Note that the bean being view scoped is important for the reason mentioned in point 5 of this answer: commandButton/commandLink/ajax action/listener method not invoked or input value not updated.

或者,您可以在输入组件上使用disabled属性,并结合使用CSS镜头,基本上使它看起来像输出组件(通过删除边框).

Alternatively, you can use the disabled attribute on input component in combination with a shot of CSS which basically makes it look like an output component (by removing the border).

<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}" />

带有例如

input[disabled] {
    border: 0;
}

在这里,bean必须在视图范围内.另请参见如何选择正确的bean作用域?

Also here, the bean must be view scoped. See also How to choose the right bean scope?