Search code examples
grailsgrails-domain-classgrails-controller

Grails - if value is negative, show value as 0


Table of Asset

This is the formula code in asset.groovy

static mapping = {
    yearNow formula: 'YEAR(purchase_date)'
    yearlyValue formula: 'PURCHASE_AMOUNT / LIFE_EXPECTANCY'
    value formula: 'PURCHASE_AMOUNT / LIFE_EXPECTANCY * (LIFE_EXPECTANCY - (YEAR(NOW()) - YEAR(purchase_date)))'
}

I need to declare Value as 0 if the value resulting from value formula is -ve. How do I do this, is it in controller or domain?

I tried this in Controller

@Transactional
def value() {
    Asset asset = Asset.get(params.value)
    if (params.value <= 0) {
        params.value = 0
        return
    }
}

Solution

  • Thanks for the help, the answer is

     value formula: 'GREATEST(PURCHASE_AMOUNT / LIFE_EXPECTANCY * (LIFE_EXPECTANCY - (YEAR(NOW()) - YEAR(purchase_date))), 0)'