[size=x-large]问题的提出:[/size]
domain模型的定义如下,如何在Controller中取得domain模型的元数据
[size=x-large]问题的解决:[/size]
[size=x-large]最终效果:[/size]
[img]http://dl.iteye.com/upload/attachment/318029/a9e87cc5-46ed-32f6-9cf4-82cdd94eff29.png[/img]
[size=x-large]心得体会:[/size]
做这件事情的最初想法是希望将ConventionOverConfiguration的思想贯彻的更彻底些,将中文化的工作直接“注入”到Grails Scaffolding的过程中,但由于Scaffolding过程中加载的Domain类并非最终类,因此无法正常读取相关元数据,因此最终采用Controller读取数据,通过预先约定好的数据传递给Views的方法,终于把这个“鸟”问题的解决方案整了一个思路出来。
后续还需要完善的地方:
[list]
[*]类关系处理(1:M, M:1, M:N)
[*]通过Controller继承的方式将取Domain类元数据过程“隐藏”
[/list]
domain模型的定义如下,如何在Controller中取得domain模型的元数据
package application
class Bird {
static domain=[chinese:"鸟"]
String name
String gender
static constraints = {
name(attributes:[chinese:"名称"])
gender(attributes:[chinese:"性别"],inList:["公","母"])
}
}
[size=x-large]问题的解决:[/size]
def birdClass=grailsApplication.getArtefact("Domain","application.Bird")
def cps=birdClass.getConstrainedProperties()
def classChinese=Bird.domain.chinese
def properties=[:]
def index = {
redirect(action: "list", params: params)
}
def list = {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
println cps
println "propiety:"
birdClass.getProperties().each{
def namePropertiy=it.getName()
if(namePropertiy == 'id')
{
properties[namePropertiy]='编号'
}else if(namePropertiy == 'dateCreated')
{
properties[namePropertiy]='创建时间'
}else if(namePropertiy == 'lastUpdated')
{
properties[namePropertiy]='更新时间'
}else if(it.isPersistent()==true && cps[namePropertiy]!=null && namePropertiy!='version'){
properties[namePropertiy]=cps[namePropertiy].attributes.chinese?:namePropertiy
}else{
println "SHIT:"+namePropertiy
}
}
println classChinese
println properties
[birdInstanceList: Bird.list(params), birdInstanceTotal: Bird.count(),classChinese:classChinese,properties:properties]
}
<g:set var="entityName" value="${classChinese}" />
<div class="list">
<table>
<thead>
<tr>
<g:sortableColumn property="id" title="${properties.id}" />
<g:sortableColumn property="name" title="${properties.name}" />
<g:sortableColumn property="gender" title="${properties.gender}" />
</tr>
[size=x-large]最终效果:[/size]
[img]http://dl.iteye.com/upload/attachment/318029/a9e87cc5-46ed-32f6-9cf4-82cdd94eff29.png[/img]
[size=x-large]心得体会:[/size]
做这件事情的最初想法是希望将ConventionOverConfiguration的思想贯彻的更彻底些,将中文化的工作直接“注入”到Grails Scaffolding的过程中,但由于Scaffolding过程中加载的Domain类并非最终类,因此无法正常读取相关元数据,因此最终采用Controller读取数据,通过预先约定好的数据传递给Views的方法,终于把这个“鸟”问题的解决方案整了一个思路出来。
后续还需要完善的地方:
[list]
[*]类关系处理(1:M, M:1, M:N)
[*]通过Controller继承的方式将取Domain类元数据过程“隐藏”
[/list]