3
votes

How can you specify an embedded field as nullable? In the simple example below I want the field price to be nullable, if there is no price associated with the item. However, if there is a price, both fields in the Currency are required. The following code doesn't work. When I try to save the Item, it complains about null values for the currency fields.

 class Item {
  static constraints = {
    price(nullable:true)
  }
  static embedded = ['price']
  Currency price
}

class Currency {
  Integer quantity
  String currencyType
}
1

1 Answers

1
votes

Just define a static constraints in your embedded object.

class Currency {
...
    static constraints = {
        quantity(nullable:true)
        currencyType(nullable:true,validator:{ String val, Currency obj -> 
            if ((val && !obj.quantity) || (!val && obj.quantity)) {
                return 'Currency.both.fields.required';
            }
        })
    }
}

Then, just add 'Currency.both.fields.required' to your messages.properties to display the appropriate error.