Reputation: 5488
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 a controller, I want to get the default value for the image property (in this case "default.jpg"). Something like this:
def productInstance = new Product(params)
productInstance.image = getProductPicturePath() ?: Product().image
getProductPicturePath returns an image path, but in case no image was submitted, the controller shall replace the null value with the default. While I could certainly write something like this:
productInstance.image = getProductPicturePath() ?: "default.jpg"
It's certainly not very DRY, and I would prefer to keep that default value in one place. How can I achieve this?
Upvotes: 3
Views: 2739
Reputation: 28059
The obvious solution is to declare it as a constant and then refer to it.
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
Even better, make getProductPicturePath()
return the default value.
Upvotes: 5
Reputation: 8855
If there is no image
key in params
def productInstance = new Product(params)
will skip this property and leave the default value defined in the domain class. So, assuming that your params doesn't contain an image
key, the simplest way would be to skip the assignment of the image
property at all for those products that have no image:
def imagePath = getProductPicturePath()
if(imagePath) {
productInstance.image = imagePath
}
Upvotes: 0