Mozein
Mozein

Reputation: 807

How do I change a value of a domain class in view page

I have an admin Domain class and I am trying to change its variable pass since it is set to a default value admin123

As I was reading in Grails documentation I read about remoteField that it could change the value in a domain class, however nothing happens when I enter a new value in the text field and click enter.

Here is my Admin domain class with pass as variable and changePassword as the function that should be called in the remoteField

class Admin {
    String pass = "admin123"

    static constraints = {
        pass size: 5..15, blank: false
    }

    def changePassword() {
        def a = new Admin()
        a.pass = params.value
        a.save()
     }
}

and this is the changePassword.gsp which allows admin to change his password

<h5>Your old password is "${oldPass}"</h5>
<h3>Please input your new password</h3>
<g:remoteField action="changePassword" name="pass" value="${admin?.pass}" />

and this is the Admin controller method of changePassword to show the oldPass

def changePassword = {
    def admin = new Admin()
    def oldPass = admin.pass
    [oldPass: oldPass]  
}

Upvotes: 0

Views: 236

Answers (1)

christopher
christopher

Reputation: 27356

If you look at the docs for remoteField, you'll see that it sends an event when it changes. When this changes, it posts the value to the action changePassword. In changePassword, the default param name is value. So something like..

def admin = Admin.get(params.id);
admin.pass = params.value;
admin.save(flush: true, failOnError: true);

This will save the admin object.

NOTE

You're saving a password in plaintext. Don't do this. You should be hashing the password before storage. To do this, you can add a beforeInsert event hook into your domain object.

def beforeInsert() {
    this.pass = // You can work this out. Hash the password!
}

EDIT

From the docs.

This tag creates an input field that fires an AJAX request when its value changes (typically when the user presses return inside the field).

The event is fired when the user hits enter inside of the field, or the value changes. There is no need for a submit button. This does not submit anything. It is an AJAX POST.

Upvotes: 1

Related Questions