How to access domain properties from a controller in Grails?

I have the following Grails domain class:

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)
    }
}

From the controller I want to get the default value for the image property (in this case, "default.jpg"). Something like that:

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

getProductPicturePath returns the image path, but in case the image was not sent, the controller must replace the null value with the default value. Although I could, of course, write something like this:

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

This, of course, is not very DRY, and I would prefer to keep this default value in one place. How can I achieve this?

+3
source share
2 answers

- , .

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() .

+5

params

image
def productInstance = new Product(params)

, . , , image, image , :

def imagePath = getProductPicturePath()
if(imagePath) {
    productInstance.image = imagePath
}
0

Source: https://habr.com/ru/post/1709157/


All Articles