StrutsでFormの各要素のreadonly属性やdisabled属性をActionから制御する
例えば何かの情報の更新画面で、ログインユーザの権限や、その情報の編集停止フラグが立っているかどうかで、フォームの各項目をreadonlyにしたりしなかったりを自在に制御したい。
今のところ思いついた方法が以下。
まずはActionFormを
public class ReadOnlyForm extends ActionForm { private String text1; private String text2; /** readonlyにする項目の項目名を格納するSet */ private Set<String> readOnlySet = new HashSet<String>(); /** 全項目がreadonlyの場合にtrueにするフラグ */ private boolean flgAllReadOnly = false; public boolean isReadOnly(String name) { if (flgAllReadOnly) { return true; } else { return readOnlySet.contains(name); } } public void setReadOnly(String... names) { for (String name : names) { readOnlySet.add(name); } } public void setAllReadOnly() { flgAllReadOnly = true; } public void resetReadOnly() { readOnlySet = new HashSet<String>(); flgAllReadOnly = false; } public String getText1() {return text1;} public void setText1(String text1) {this.text1 = text1;} public String getText2() {return text2;} public void setText2(String text2) {this.text2 = text2;} }
こんな感じで用意。
Actionで、
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ReadOnlyForm f = (ReadOnlyForm) form; f.setReadOnly("text1", "text2"); return mapping.findForward("success"); }
みたいな感じで設定する。
そしてjspで
<html> <head> <style type="text/css"> .readOnly { background-color: #CCCCCC; } </style> <script type="text/javascript"> function setReadOnly() { for (var i=0; i<document.forms.length; i++) { var form = document.forms[i]; for(var j=0; j<form.elements.length; j++) { var element = form.elements[j]; if (true == element.readOnly) { element.className = "readOnly"; } } } } </script> </head> <body onload="setReadOnly();"> <bean:define id="form" name="ReadOnlyForm" type="struts_test.form.ReadOnlyForm" /> <html:form action="/readonly"> text1:<html:text property="text1" readonly='<%= form.isReadOnly("text1") %>' /><br /> text2:<html:text property="text2" readonly='<%= form.isReadOnly("text2") %>' /> <html:submit value="submit" /> </html:form> </body> </html>
みたいな感じで使う。
cssとJavaScript部分は本筋とは関係なく、readonlyの項目の背景色を灰色にして見た目を変えるために追加した。
とりあえず出来た!!もっときれいな方法ないんかな。