Displaying read-only forms (values are shown as te

2019-06-06 03:14发布

问题:

I have a data entry form where user enters lots of data. When user comes to the page to view existing data, the page should be displayed in read-only mode (all values shown as text), when he clicks 'Edit' button, normal form with all input controls should be shown so that user can change and save data.

We are using JSF 2.0 with PrimeFaces library. It is easy to achieve above behavior for text box and text area but not for Checkbox, multi-select, radio,..... controls. Is there any easy way available to achieve above behavior rather than writing our own code (which may run into lot of lines thus making backing bean code ugly)

Thanks for your help...

回答1:

I'm not sure why you think that you need additional backing bean code for this. You've all the needed values in the backing bean already. Your problem is more in the presentation of those values. Just display them in the desired format by writing the view code accordingly. Perhaps you were thinking it too the hard way.

Instead of a select boolean checkbox, you could display for example a "Yes" or "No" value.

<h:selectBooleanCheckbox value="#{bean.checked}" rendered="#{bean.edit}" />
<h:outputText value="#{bean.checked ? 'Yes' : 'No'}" rendered="#{not bean.edit}" />

Instead of a select one menu/radio, you could just display the value in an output text.

<h:selectOneMenu value="#{bean.selectedItem}" rendered="#{bean.edit}">
    <f:selectItems value="#{data.availableItems}" />
</h:selectOneMenu>
<h:outputText value="#{bean.selectedItem}" rendered="#{not bean.edit}" />

Instead of a select many listbox/checkbox, you could just display for example all values comma separated in a loop.

<h:selectManyListbox value="#{bean.selectedItems}" rendered="#{bean.edit}">
    <f:selectItems value="#{data.availableItems}" />
</h:selectManyListbox>
<h:panelGroup rendered="#{not bean.edit}">
    <ui:repeat value="#{bean.selectedItems}" var="selectedItem" varStatus="loop">
        #{selectedItem}#{not loop.last ? ', ' : ''}
    </ui:repeat>
</h:panelGroup>

You could wrap it all in a tag file or a composite to minimize boilerplate and code repetition.



回答2:

I've done this in my last project using composite components which has a "preview" attribute and in the implementation I render a text when this attribute is true and the real (editing) when the attribute is false. For checkbox in preview mode you could show the checkbox itself but disabled, for radio - show the selected item.

MyFaces Tomahawk library [1] contains an extended version of the standard components that adds displayValueOnly attribute for this purpose. This might help you (I haven't used them).

[1] - http://myfaces.apache.org/tomahawk-project/tomahawk20/index.html