clever_bassi
clever_bassi

Reputation: 2480

Blank constraint in Grails doesn't work

I am working on blank constraint in Grails. I have a addWebsites.gsp as follows:

<g:form controller="SiteURL" action="websiteAdded">
    <label for="siteURL">ADD URL:</label>
    <g:textField name="siteURL" value="${siteURL?.siteURL}"
        style="width: 400px;height: 22px;"></g:textField>
    <br />
    <input type="submit" value="Save">
</g:form>

I want the blank constraint on the textField siteURL. The domain class is SiteURL.groovy:

class SiteURL {
    String siteURL
    static constraints = { 
        siteURL blank:false 
    }
}

My SiteURLController.groovy class is as follows:

class SiteURLController {
    def addWebsites() { }

    def websiteAdded(){

        if(request.method == 'POST') {
            def u = new SiteURL()
            u.properties ['siteURL']
            if(u.siteURL =="") {
                u.errors.rejectValue("siteURL", "cmsprofiler.siteurl.empty")
                return [siteURL:u]
            } else if(u.save()) {
                session.siteURL= u
                redirect(controller: "SiteURL", action: "websiteAdded")
            } else {
                return [siteURL:u]
            }
        }
    }

    def websiteNOTAdded(){ }
}

Despite the constraint, it does not show the error when I leave the textfield blank and still takes me to the websiteAdded viewpage. I am not able to figure out what's wrong. I want the error to be displayed in case a user tries to press submit without entering the url. Any help would be appreciated. Thanks

Upvotes: 0

Views: 181

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

You have code that looks like this:

 def u = new SiteURL()
 u.properties ['siteURL']
 if(u.siteURL =="") {
     u.errors.rejectValue("siteURL", "cmsprofiler.siteurl.empty")
     return [siteURL:u]
 }

That if condition will never be true. You are creating a new SiteURL object and never assigning a value to the siteURL property, so it will be null.

Your code is behaving exactly as I would expect it to behave.

It may be that you think u.properties ['siteURL'] is doing something meaningful, but it isn't. All that is doing is retrieving the value of the siteURL property. You are never assigning it a value.

Upvotes: 1

Related Questions