Search code examples
data-bindinggrailsgroovygrails-domain-classgrails-controller

How to mix multiple domain objects in a single form?


I have 3 domains : - EligibilityInclusion - EligibilityExclusion - EligibilitySummary

I build also eligibility.gsp (mix use of 3 templates : _inclusion, _exclusion, _summary ; and I'm also using JQueryUI tab to render each domain in one tab).

Everything fine for viewing, but now I would like to use only one controller to create, edit, list and show.
How can I handle 3 domains via only one controller?
(for example, I would like to use EligibilityController to handle my 3 domains)

What is the best usage:
- binding multiple objets? - use command objects?


Solution

  • Unfortunately command objects don't help with the input model for a view, they are specifically designed to aide the output model for the binding and validation of request parameters. However you can roll your own View Model based on a command object if you are prepared to delve into some meta programming to to achieve the data binding for the creation of the view model.
    Here's a basic approach. The following code constructs the Command Object which you can then pass as the model to the view in the controller:

    class ItemCommand {
     // attribute declarations ...
    
    public void bindData(def domainInstance){
        domainInstance.properties.keySet().each { prop ->
            if(prop == "class"){
                // not needed
            } else if(prop == "metaClass") {
                // not needed
            } else if(this.properties.containsKey(prop)){
                this."${prop}" = domainInstance."${prop}"
            }
        }
    }
    

    This will allow you to bind the data from different domain objects by calling bindData for each of the domain objects.

    This is the essence of the solution I use. You will need to store the ids of the different domain objects (and the version attribute) as hidden fields if you intend to do updates to the domain objects.