關于如何生成字段的編輯頁面;
1. 首先應該讀取domain對象,從而獲取field列表;
/**
* getDomainFields via jsp name, and should remove the super fields, like lastUpdatedBy, lastUpdatedDate
* @param name of jsp
* @return list of field
*/
public static List<Field> getDomainFields(String name) {
List<Field> ret = new ArrayList<Field>();
try {
Class clz = Class.forName(CodeEngineConfig.getDomainPackage() + "." +
CodeEngineConfig.getControllerDomain(CodeEngineConfig.getJspRef(name)));
for (Field field : clz.getDeclaredFields()) {
if(!"lastUpdateDate".equalsIgnoreCase(field.getName())
&& !"lastUpdateBy".equalsIgnoreCase(field.getName())){
ret.add(field);
// System.out.println("field.getName() + field.getType() = " + (field.getName() + field.getType()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
2. 將Field List傳遞給freemarker模板;之所以要傳遞field而不僅僅是name的原因是,因為希望在模板里根據field的type,從而生成不同的html,比如date可以生成使用js calendar的,boolean生成radio,或checkbox,其他的生成text;
a) 定義macro;
<#macro getHtml field>
<#if field.type?ends_with('Boolean')>
<input type="radio" id="${field.name}" name="${field.name}" class="inp_txt_30" size="80" value="${'$'}{${domain?uncap_first + '.' + field.name}}">
<#elseif field.type?ends_with('Date')>
<input type="text" id="${field.name}" name="${field.name}" readonly="readonly" class="inp_txt_30" size="17" value="<fmt:formatDate value="${'$'}{${domain?uncap_first + '.' + field.name}}" pattern="yyyy-MM-dd hh:mm"/>">
<button id="${field.name}Btn" class="button" >...</button>
<script type="text/javascript">
Calendar.setup(
{
inputField : "${field.name}", // id of the input field
ifFormat : "%Y-%m-%d %H:%M", // the date format
showsTime: true,
button : "${field.name}Btn" // id of the button
}
);
</script>
<#elseif field.type?ends_with('Text')>
<textarea id="${field.name}" name="${field.name}" rows="15" cols="80" style="width: 100%">${'$'}{${domain?uncap_first + '.' + field.name}}</textarea>
<#else>
<input type="text" id="${field.name}" name="${field.name}" class="inp_txt_30" size="80" value="${'$'}{${domain?uncap_first + '.' + field.name}}">
</#if>
</#macro>
b)調用macro生成html;
<#list fields! as field>
<tr>
<td class="txt_tit_s" ><spring:message code="${lbl + '.' + domain?uncap_first + '.' + field.name}"/></td>
<td><@getHtml field=field/></td>
</tr>
</#list>