Grails command object data binding

前端 未结 4 614
北海茫月
北海茫月 2020-12-05 00:50

Grails has very good support for binding request parameters to a domain object and it\'s associations. This largely relies on detecting request parameters that end with

4条回答
  •  情歌与酒
    2020-12-05 01:18

    I've faced the same problem with nested command objects, so I did the following workaround:

    1. I explicitly added the other domain objects as parameters to my controller action
    2. Also, explicitly called bindData() for the nested command objects (usually, the command object that wraps the other command objects will bind its data successfully without the need to bind it explicitly, this depends on your view naming convention)
    3. Then I called .Validate() on those command objects
    4. Use these objects to check for errors with .hasErrors()
    5. To save your Domain object, assign explicitly also each nested property with it's corresponding command object

    To illustrate, here is a sample pseudo code:

    class CommandObjectBig{
    
        String name
        CommandObjectSmall details
    
        static constraints = {
          name (blank: false)
        }
    
    }
    
    
    class CommandObjectSmall{
    
        String address
    
        static constraints = {
          address (blank: false)
        }
    
    }
    

    In the controller:

    .
    .
    .
    
    def save = { CommandObjectBig cob, CommandObjectSmall cos ->
    
    //assuming cob is bounded successfully by grails, and we only need to handle cos
    
    bindData(cos, params.details)
    cos.validate()
    
    //then do you code logic depending on if cos or cob has errors
    
    if(cob.hasErrors() || cos.hasErrors())
    render(view: "create", model: [bigInstance: cob, smallInstance: cos])
    }
    else
    {
     //create the Domain object using your wrapper command object, and assign its details
     //property it's value using cos command object instance, and call the save on you
     //command object and every thing should go smoothly from there
       .
       .
       .
    
    }
    .
    .
    .
    

    • Hope future releases of grails have a fix for this problem, and maybe allow the developer to add an optional params or params scope to be assigned to each command object also, it could be useful :)

提交回复
热议问题