代码之家  ›  专栏  ›  技术社区  ›  Cesar

如何从Grails中的控制器访问域属性?

  •  3
  • Cesar  · 技术社区  · 17 年前

    class Product {  
        String name  
        Float basePrice  
        Category category  
        String image = "default.jpg"  
    
        static constraints = {
            name(size:3..25, blank:false)
            basePrice(scale:2, nullable:false)
            category(inList:Category.list(), nullable:false)
            image(blank:false)
        }
    }
    

    我想从控制器中获取image属性的默认值(在本例中为“default.jpg”)。大致如下:

    def productInstance = new Product(params)
    productInstance.image = getProductPicturePath() ?: Product().image
    

    productInstance.image = getProductPicturePath() ?: "default.jpg"
    

    2 回复  |  直到 17 年前
        1
  •  5
  •   angryip Gareth Davis    10 年前

    class Product {  
        static DEFAULT_IMAGE = "default.jpg"
        String name  
        Float basePrice  
        Category category  
        String image = DEFAULT_IMAGE
    
        static constraints = {
            name(size:3..25, blank:false)
            basePrice(scale:2, nullable:false)
            category(inList:Category.list(), nullable:false)
            image(blank:false)
        }
    }
    
    productInstance.image = getProductPicturePath() ?: Product.DEFAULT_IMAGE
    

    getProductPicturePath() 返回默认值。

        2
  •  0
  •   Daniel Rinser    17 年前

    如果没有 image 输入 params

    def productInstance = new Product(params)
    

    图像 图像 对于那些没有图像的产品,完全没有属性:

    def imagePath = getProductPicturePath()
    if(imagePath) {
        productInstance.image = imagePath
    }
    
    推荐文章