2014-09-12 70 views
0

我試圖執行一些命令對象的驗證沒有綁定屬性,但命令對象的一個​​屬性沒有約束它總是返回null命令對象

域類

package ni.sb 

class PurchaseOrder implements Serializable { 
    Date dateCreated 
    Date dutyDate 
    String invoiceNumber 
    BigDecimal balance 
    String typeOfPurchase 

    Date lastUpdated 

    static constraints = { 
    dutyDate nullable:false, validator: { dutyDate -> 
    def today = new Date() 

    if (dutyDate <= today) { 
     "notMatch" 
    } 
    } 
    invoiceNumber blank:false, unique:true 
    balance nullable:true 
    typeOfPurchase inList:["Contado", "Credito"], maxSize:255 
} 

}

這是命令對象

class PurchaseOrderCommand implements Serializable { 
    Date dutyDate 
    String invoiceNumber 
    String typeOfPurchase 

    static constraints = { 
    importFrom PurchaseOrder 
} 

}

這裏是控制器動作

def actName(PurchaseOrderCommand cmd) { 
    if (cmd.hasErrors()) { 
    println params.dump() 
    println cmd.dump() 

    return 
    } 
} 

dutyDate沒有約束力,之後我嘗試在PARAMS啞()和CMD我得到這個

片斷params.dump()

dutyDate: 2014年9月25日

片斷cmd.dump()

dutyDate = NULL

我希望你能幫助我

+0

您使用的是哪個版本的Grails? – 2014-09-12 23:56:39

回答

0

如果檢查cmd.errors我希望你將看到的錯誤。

如果你的約會請求參數的格式爲「2014年9月25日」和你使用的是最新的Grails的版本,那麼這樣的事情應該工作:

import org.grails.databinding.BindingFormat 

class PurchaseOrderCommand implements Serializable { 
    @BindingFormat('yyyy-MM-dd') 
    Date dutyDate 
    String invoiceNumber 
    String typeOfPurchase 
} 

另外,您可以設置「YYYY-MM -dd「作爲Config.groovy中的默認格式之一。

// grails-app/conf/Config.groovy 
grails.databinding.dateFormats = ['yyyy-MM-dd', 
            'MMddyyyy', 
            'yyyy-MM-dd HH:mm:ss.S', 
            "yyyy-MM-dd'T'hh:mm:ss'Z'"] 
// ... 

我希望有幫助。

+0

我想我們在Grails 2.3中引入了'BindingFormat'。 – 2014-09-13 03:47:43

+0

謝謝傑夫,我會盡力實施這個建議。 – user615274 2014-09-14 00:06:23

+0

這個例子不起作用(至少在grails 2.5.2中),缺少註解屬性'code',所以'@BindingFormat(code ='yyyy-MM-dd')'是正確的。 – iberck 2015-11-18 18:44:03