When an object from a class Foo is associated with a Bar object, we don't always want to have the association.
So when in the view we've got a select which shows all Bar instances, an empty option would be good to.
Example use case from Fred Janon:
I have an "Shift" domain class that references an "Officer" domain
class. An "Officer" can be optional assigned to a "Shift". The user can
change the date/time of the "Shift" and at some point assign an
"Officer" to the shift. By default Grails builds an "Edit" view for the
"Shift" with a "Select" referencing the "Officer" list. The problem is
that the "Select" doesn't have an empty entry for the "Officer". Even
if the user wants to change only the time of the shift, the first
officer will be selected by default and saved.
Is there a way to make the "Officer" field optional in the "Edit Shift"
view?
This is the code generate by Grails:
<g:select optionKey="id" from="${[''] + Officer.list()}"
name="officer.id" value="${shift?.officer?.id}"></g:select>
I added an empty entry in the list, it shows correctly in the HTML
page, but then Hibernate generates an exception when I save the edited
"Shift"
<g:select optionKey="id" from="${[''] + Officer.list()}"
name="officer.id" value="${shift?.officer?.id}"></g:select>
Any suggestion to do this cleanly?
Not having a blank item listed leads to false data submission where lazy/unobservant users accept the first selected setting.