Question

Imagine you have a table displaying a list of books (like the index does) and you want to make changes in a column called "Sold" (a checkbox for example). So once you finish "Checking" the books you have sold, you click a Button to save! How do you send back that list to the controller and update it?

So, the code is something like this, in the controller:

def aMethod(){ ... [bookInstanceList: myBookList] }

In the GSP:

    <g:each in="${bookInstanceList}" status="i" var="bookInstance">
        <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">

            <td><g:link action="show" id="${bookInstance.id}">${fieldValue(bean: bookInstance, field: "author")}</g:link></td>
            <td><g:checkBox name="sold" value="${bookInstance?.sold}" /></td>
            <td>
        </tr>
    </g:each>

The idea is with the checkbox let the user change the "Sold" value from that book, and then make a submit with a Button. How can I save my new bookInstanceList?

Thank you very much

Was it helpful?

Solution

There is a simple sample app at https://github.com/jeffbrown/books which shows one way you could do this. Run the app, open the default index page, click on the link and that will take you to a page where you can click checkboxes and update the library of books.

Files of interest are https://github.com/jeffbrown/books/blob/master/grails-app/controllers/com/demo/BookController.groovy and https://github.com/jeffbrown/books/blob/master/grails-app/views/book/index.gsp.

I hope that helps.

OTHER TIPS

I've removed some of the markup for brevity and to bring focus to the important bits. This is one way of doing it without relying on Javascript and what do you know, it is pure grails. Never say never, @rmlan.

<g:form action="updateSold" controller="book">
   <table>
      <tbody>
         <g:each in="${bookInstanceList}" status="i" var="bookInstance">
            <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
               <td><g:link action="show" id="${bookInstance.id}">${fieldValue(bean: bookInstance, field: "title")}</g:link></td>
               <td>
                   <g:checkBox name="sold" value="${bookInstance.sold}" />
                   <g:hiddenField name="id" value="${bookInstance.id}" />
               </td>
           </tr>
        </g:each>
     </tbody>
   </table>
   <g:submitButton name="updateSold" value="Update" />
</g:form>

This is the controller action:

def updateSold() {
   def solds = params.list('sold')
   def ids = params.list('id')

   ids.eachWithIndex { id, idx ->
      if (solds[idx]) {
          // the book's sold has been checked, so update it to TRUE           
      } else {
         // the books sold has not been checked, so update it to FALSE
      }
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top