Cesar
Cesar

Reputation: 5488

Validation errors not rendered in the view

I'm having a hard time figuring this validation problem. I have one parent domain class defined as follows:

class Person {
    String fullName
    List telephones = []

    static hasMany = [telephones : Telephone]

    static constraints = {
        fullName(size:3..50, blank:false, nullable:false)
    }
}

Then a sublcass:

class SalesAdvisor extends Person{
    Float comission //In percentage
    Portfolio customerPortfolio
    Inventory inventory

    static constraints = {
        comission(range:0..100, scale:2, nullable:false)
        customerPortfolio(nullable:false) 
        inventory(nullable:false)
    }
}

In the SalesAdvisorController I save SalesAdvisor instances:

def save = {
    def portfolio = new Portfolio()
    def inventory = new Inventory(name:'${params.fullName}Inventory', description:"${params.fullName}'s Inventory")
    params.customerPortfolio = portfolio
    params.inventory = inventory
    def salesAdvisor = new SalesAdvisor(params)

    if(!salesAdvisor.hasErrors() && salesAdvisor.save()){
        log.info("New instance of SalesAdvisor saved.")
        redirect(action:show, id:salesAdvisor.id)
    }else{
        log.error("There was an error saving the sales advisor.")
        salesAdvisor.errors.allErrors.each{
        println it.code
    }
    render(view:'create', model:[salesAdvisor:SalesAdvisor])
  }
}

In order to display any errors, in the 'create' view I have:

<g:hasErrors bean="${salesAdvisor}">
    <div class="errors">
        <g:renderErrors bean="${salesAdvisor}" as="list" />
    </div>
</g:hasErrors>

Validation seems to be working fine. However if I submit a string instead of a float for the comission field, in logs I can see "typeMismatch" but the view renders nothing! The message.properties file has a default entry for typeMismatch. Same thing for the fullName field, in logs I can see "nullable" and "blank" errors, but the view renders nothing.

I'm guessing it's more the view's fault than the controller or the domain, since unit tests behave like they should.

Upvotes: 1

Views: 1299

Answers (1)

Daniel Rinser
Daniel Rinser

Reputation: 8855

I'd say the problem is a simple typo in your model-passing code:

render(view:'create', model:[salesAdvisor:SalesAdvisor])

(note the uppercase SalesAdvisor value). Try

render(view:'create', model:[salesAdvisor:salesAdvisor])

As a side note, there is a bug in your Inventory constructing code:

name:'${params.fullName}Inventory'

You should use double-quotes here (GString).

Upvotes: 2

Related Questions