Reputation: 614
I am a bit new to grails and I'd like to get a clear understanding of how to use 'nullable' and 'blank' constraints in a grails domain class.
An example is;
static constraints = { name nullable: true }
static constraints = { name blank: true }
static constraints = { name nullable: true, blank: true }
What do each of these mean and how best can they be applied?
Upvotes: 1
Views: 3440
Reputation: 187499
All properties are not-null by default, so generally the only time you use the nullable
constraint is when you want to allow nulls, i.e. nullable: true
.
Moreover, by default Grails databinding will convert blank strings to null, which effectively means that blank: false
is applied by default (because blanks are converted to null, and nulls are prohibited).
There are some theoretical cases wherein it would be necessary to explicitly specify blank: false
, e.g. if a property is set to a blank string after databinding. However, these are very unlikely to occur in practice, so ignoring some edge cases it's reasonable to assume that blank: false, nullable: false
are applied by default.
Upvotes: 4
Reputation: 2776
Well, at first you should look into the docs.
Second:
Nullable is already set by default to false. If you want some value to be nullable, then you write name nullable: true
.
Nullable means that when creating an object, that value can be left null (nothing inputted).
Blank - when you will create i.e. form for objects param input and you left a field empty, it will save with no errors and accept empty value.
Long story short - Blank is for forms to accept empty. Nullable is for the coded object to be saved without value.
You can also see this post.
Upvotes: 1