Illep
Illep

Reputation: 16851

How to enter a hard-coded value to the database?

I have a few fields in my User.groovy model class

fName
lName
userName
pwd
yourTel

The user will be entering the first 4 fields shown above. The 5th field yourTel will be hardcoded.

def create() {
   [userInstance: new User(params)]
}

How can I do it ?

This is what I already tried:

def create() {
    userInstance.yourTel = "2323232"
    params = userInstance.yourTe
    [userInstance: new User(params)] 
}

SAVE

def save() {
        def userInstance = new User(params)
        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])

            return
        }else  {
            def userRole = Role.findOrSaveWhere(authority:'ROLE_USER')
            if(!userInstance.authorities.contains(userRole)){
                UserRole.create(userInstance, userRole, true)
            }
            redirect(controller:"login", action : "auth")
        }
    }

MODEL

static constraints = {
...
        yourTel blank:true , nullable: false

Upvotes: 2

Views: 81

Answers (2)

Alidad
Alidad

Reputation: 5538

Your approach works too with a bit of tweak:

def create() {
    def instance = new User(params)
    instance.yourTel="2323232"
    [userInstance: instance]

}

The [userInstance: instance] the left is the key that will be used by your models, the right hand side is what you are passing to it. Here you first create the new User(params) then bind it with params and then you can tweak it and pass it back to your model.

def save() {
        def userInstance = new User(params)
        // set the yourTel to some value
        userInstance.yourTel="2323232" 

        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])

Upvotes: 1

MKB
MKB

Reputation: 7619

params is a map, so put your data like

params.yourTel="2323232"

or

params.put("yourTel","2323232")

Now your code becomes:

def create() {
    params.yourTel="2323232"
    [userInstance: new User(params)]
}

Upvotes: 1

Related Questions