Mapping of Dynamic fields in RestfulController POST (save) method

112 Views Asked by At

How do I enable RestfulController to auto-map or even manually map the dynamic fields to domain classes implementing MongoEntity? I have a domain class as below:

class Company implements MongoEntity<Company> {
    String id = UUID.randomUUID().toString()
    String name
    String email
    String phone
}

And I have a RestfulController setup for CRUD operations as below

class CompanyController extends RestfulController<Company> {

@Transactional
    def save(Company company) {
        if(company.hasErrors()) {
            respond company.errors
        }
        else {
            company.insert(flush:true)
            respond company, status: CREATED
        }
    }
}

When I POST a request with some additional JSON fields, how do I get them auto-mapped to gorm_dynamic_attributes ? Currently the company object does not return any information on the dynamic attributes. Another problem I am facing is that request.JSON is also null so I cannot manually map either. Any suggestions would be highly appreciated.

1

There are 1 best solutions below

0
injecteer On

I'm pretty sure, that the problem is not in data binding of your controller, but rather in persisting of the domain class instance.

I would change the domain class like so:

import grails.gorm.annotation.Entity

@Entity
class Company {
    String id
    String name
    String email
    String phone

    def beforeValidate() {
      if( !id ) setId UUID.randomUUID().toString()
    }  

    static mapping = {
      id generator:'assigned'
    }
}

to use the assigned generator. You could put your id generation either in the controller / service code, or leave it inside the domain class' beforeValidate. In the later case pay special attention to when the id shall be generated, as beforeValidate() is called pretty often. Also note, that inside beforeValidate() a setter must be called.

I tested the similar domain class of mine with save() and insert() and in both cases that works like charm.