Search code examples
javagrailscontrollergsp

Grails edit and update database object


I am trying to create grails app not using Scaffolding to understand it's "way of thinking" better. :) I am stuck with edit/update method. On "edit" button I open the same kind input form as when creating object. All the fields are filled with info and id is passed in link.

On "Edit the msg" I want to update existing object, but all that I've got was either creating new or having error - Cannot set property 'sender' on null object

My "edit.gsp" looks like this:

    <!DOCTYPE html>
<html>
<head>
    <meta name="layout" content="main"/>


</head>
<body>
<h2>Edit this message</h2>

    <g:if test="${flash.message}">
    <div class="alert alert-error" style="display: block">${flash.message}</div>
    </g:if>
    <div class="createStuff" id ="inputs">
        <g:formRemote url="[action: 'editSave']" update="allTheMessages"
        name="updateStatusForm">
            <table>
                <tr>
                <td>Sender:</td>
                <td><g:textField name="sender" value="${message.author}"/></td>
                </tr>

                <tr>
                <td>Message</td>
                <td><g:textArea name="msg" value="${message.text}"/></td>
                </tr>
                <tr>
                <td>Some status</td>
                <td><g:textField name="status" value="${message.status}"/></td>
                </tr>
                <tr>
                <td>Wanna publish?</td>
                <td><g:select name="toPublish" from="${['Publish','Archive']}" keys="${[true,false]}"/></td>
                </tr>
            </table> 
            <g:submitButton name="Edit the msg"/>
        </g:formRemote>
    </div>

</body>
</html>

And my method in controller has varied:

  def editSave() {
        def message2save = Message.get(params.id)
        message2save = new Message(text: params.msg, author: params.sender, status: params.status, toPublish: params.toPublish).save(insert: false, update: true) //1st way - still creates new Message - obviously because of "new Message"
        message2save.sender = params.sender //part of 2nd way - in this case there appears NullPointerException mentioned above --> Cannot set property 'sender' on null object

        message2save.save()
        redirect(action:"index")

    }

What am I doing wrong? How can I update existing record? Huge thanks in advance. :)


Solution

  • GORM knows if you're updating a record when you successfully loads it from the database. This is done in your code:

    def message2save = Message.get(params.id)
    

    The problem is that you're not sending the id of your message in the forms. So you need to add:

    <g:hiddenField name="id" value="${message.id}" />