2010-03-06 63 views
0

我創建了一個自定義的標籤,看起來像這樣:的Groovy/Grails的驗證和hasFieldErrors問題

def textField = { attrs -> 
    def field = attrs.name.split('\\.')[-1] 
    log.error("--------- Field is ${field}") 
    if (attrs.bean && attrs.bean.errors.hasFieldErrors(field)) { 
     def className = attrs.remove('class') 
     def classStr = 'errors ' 
     if (className) { 
      classStr += className 
     } 
     attrs.put('class', classStr) 
     attrs.put('value', attrs.bean[field]) 
     attrs.remove('bean') 
    } 
    out << g.textField(attrs) 
} 

我打電話在我的GSP這樣的:

<my:textField bean="${client}" name="client.firstName"/> 
<my:textField bean="${client}" name="client.lastName"/> 
... 
<my:textField bean="${client}" name="client.workPhone"/> 

這裏是我的域類

class Client { 

    String email 
    String address 
    String city 
    String state 
    String zip 
    String firstName 
    String lastName 
    String phone 
    String workPhone 
    String mobilePhone 
    String birthCountry 
    String citizenshipCountry 
    String emergencyContactName 
    String emergencyPhone 
    String disabilities 
    String experience 

    static constraints = { 
     email(email:true, unique:true, blank:false) 
     address(blank:false) 
     city(blank:false) 
     state(blank:false) 
     zip(blank:false) 
     firstName(blank:false) 
     lastName(blank:false) 
     phone(blank:false) 
     emergencyContactName(blank:false) 
     emergencyPhone(blank:false) 

     workPhone(blank:true, nullable:true) 
     mobilePhone(blank:true, nullable:true) 
     birthCountry(blank:true, nullable:true) 
     citizenshipCountry(blank:true, nullable:true) 
     disabilities(blank:true, nullable:true) 
     experience(blank:true, nullable:true) 
    } 

    static mapping = { 
     disabilities type: 'text' 
     experience type: 'text' 
    } 

    static hasMany = [courses:ClientCourseMap] 
} 

頁面加載正常,除非我實際上有一個「客戶端」bean。它一直加載到最後一個標籤「client.workPhone」。然後我出現以下情況例外:

2010-03-06 18:32:35329 [HTTP-8080-2] ERROR view.GroovyPageView - 錯誤處理GroovyPageView:錯誤執行標籤:org.codehaus.groovy.grails .web.taglib.exceptions.GrailsTagException:執行標記時出錯:groovy.lang.MissingPropertyException:沒有這樣的屬性:類的客戶端:com.personal.Client at/Users/dean/Projects/PersonalGrails/grails-app/views /登記/ index.gsp中:98在/Users/dean/Projects/PersonalGrails/grails-app/views/registration/index.gsp:145

問題是當hasFieldErrors被稱爲對bean。它通過應該是「workPhone」的「字段」。逐個調試器顯示該字段完全是「workPhone」。但是,通過進一步檢查字段變量,它顯示字段的內部值爲「client.workPhone」,偏移量= 7,計數= 9,哈希= 0.但是,如果調用toString(),則會返回「 workPhone「,就像你期望的那樣。

我想知道Grails或者甚至Spring沒有正確地使用這個字符串?它看起來像試圖使用該字符串的真實值,而不是注意該字符串的偏移量/計數並找回目標。

有沒有人看到我做錯了什麼?或者你知道解決方法嗎?我可以給任何需要的信息,只要問......這讓我瘋狂!

回答

1

看起來你的標籤的目的是減少渲染表單時所需的樣板GSP代碼的數量。你有沒有考慮過使用bean-fields插件呢?

+0

謝謝!我是grails(來自rails)的新手,所以我不習慣一切都是插件,並且不認爲在滾動自己的插件之前先看看插件。這絕對是我想要做的。 – intargc 2010-03-11 15:42:28

+0

呃,沒關係...認爲它不能與命令對象一起工作,但似乎我錯誤地使用了它。 – intargc 2010-03-11 16:27:52