Grails command object data binding

前端 未结 4 620
北海茫月
北海茫月 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:27

    Command Object in Grails

    In Grails, command objects are like domain classes, but don’t persist data. Using command objects in Grails is a simple way to perform data binding and validation when there is no need to create domain object.

    First thing you‘ll need to do is describe your command object. It is fine to do in the same file that contains controller that will use it. If command object will be used by more than one controller, describe it in groovy source directory.

    Declaring Command Objects

    @Validateable
    class UserProfileInfoCO {
        String name
        String addressLine1
        String addressLine2
        String city
        String state
        String zip
        String contactNo
    
        static constraints = {
            name(nullable: false, blank: false)
            addressLine1(nullable: true, blank: true)
            addressLine2(nullable: true, blank: true)
            city(nullable: true, blank: true)
            state(nullable: true, blank: true)
            zip(nullable: true, blank: true, maxSize: 6, matches: "[0-9]+")
            contactNo(blank: true, nullable: true)
        }
    }
    

    Using Command Objects

    Next thing you’ll probably want to do is bind the data, that is being received by action in your controller to the command object and validate it.

     def updateUserProfile(UserProfileInfoCO userProfileInfo) {     
      // data binding and validation
       if (!userProfileInfo.hasErrors()) {
          //do something
       } 
    
    }
    

提交回复
热议问题