For example, let's say I have Artist and Album domain classes where Artist hasMany Albums and Album belongsTo Artist. Artist has a name property that is unique. On my create album page I want to be able to type in the artist name and have the save action in the controller automatically lookup an existing Artist instance or create a new one if it doesn't exist. Doing this I don't want to have to add or change anything in the save action itself - I could theoretically use dynamic scaffolding.
Adapting Stefan's PropertyEditor implementation I created this:
The crucial change is the
if (!value)block which creates the new instance and populates the relevant property.
To make everything work I just need to:
- Add the PropertyEditorRegistrar and place it in resources.groovy as per Stefan's post.
- Have a text input or autocompleter with the name "artist" in my create album form.
artist cascade: "save-update"to the mapping block in Album so that when the Album is saved the new Album will get saved as well.