2013-03-20 103 views
0

试图成为一个Grails转换器我已经开始将现有的应用程序转换为Grails和Groovy。它工作得很好,但我卡在选择标签的转换。grails填充g:从查询中选择

我有一个域类:

package todo 

    class Person { 

    String ssn 
    String firstname 
    String familyname 
    String role 
    String emailname 
    String emailserver 
    ... 

当创建一个新的“待办事项”任务的所有者可以从系统中谁是开发商的人士进行分配,我得到这个工作(相当直接翻译自PHP):

<select id="owner" name="owner"> 
    <option>Noboby ...</option> 
    <g:each in="${Person.list()}"> 
    <g:if test="${it?.role=='developer'}"> 
     <option value="${it?.id}">${it?.firstname} ${it?.familyname}</option> 
    </g:if> 
    </g:each> 
</select> 

但是每一次尝试使它更加“Grails-ish”失败。它如何塑造成Grails v2.2.1代码?我花了数小时阅读,尝试,失败。

回答

1

试试这个代码:

<g:select optionKey="id" from="${Person.findAllByRole('developer')}" optionValue="${{it.fullName}}" value="${yourDomainInstance?.person?.id}" noSelection="['null':'Nobody']"></g:select> 

而在你的类:

class Person { 
.... 
String getFullName(){ 
    it?.firstname+' '+ it?.familyname 
} 

static transients = ['fullName'] 
.... 
} 

更多细节

+0

'optionValue =“it.fullName”'不起作用。你需要'optionValue =“$ {{it.fullName}}”' – 2013-03-20 18:33:50

+0

是的,你是对的。和optionValue =“fullName”?注意:保持简单(= – 2013-03-21 10:01:29

+0

这最后一个建议是我最终使用的,我的解决方案越来越像这个,所以我检查你的而不是 – serafim 2013-03-21 10:16:10

2

如果您woulkd喜欢使其更Grails的风格,您应该执行见g:select tag您在controllers \ services之内的所有逻辑都不在视图中。

假设你有文件夹personPersonController在视图createTodo,然后修改您的createTodo操作是这样的:

class PersonController { 
    def createTodo() { 
     def developers = Person.findAllWhere(role: 'developer') 
     [developers: developers, ... /* your other values */] 
    } 
} 

所以你并不需要在您的视图数据库操作来处理。

下一步是使用g:select tag这样的:

<g:select name="owner" from="${developers}" optionValue="${{'${it.firstName} ${it.familyName}'}}" noSelection="['null':'Nobody ...']" optionKey="id" value="${personInstance?.id}" /> 
+0

或者,您可以按照Cat先生的描述修改您的Person类,以简化g:select标记的optionValue部分 – aiolos 2013-03-20 10:08:04

+0

我测试了@aiolos和@“猫先生”解决方案,并在我第一次进入Grails时发现了一些其他缺陷,但我将在最终实现中混合使用这两种解决方案。一些upvotes,但我不被允许。 – serafim 2013-03-20 21:40:59

0

最后,我得到了它的工作,因为我想和它的作品(几乎)根据@解决方案“猫先生”。一个小细节,不过,“这并不在类存在,因此getFullName方法必须成为:

String getFullName(){ 
    this?.firstname+' '+ this?.familyname 
} 

向上和工作,谢谢所有帮助。