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 want to save that in the database. 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. How can I save my new bookInstanceList?

Thank you very much

Was it helpful?

Solution

From what I see you want to dynamically update the backend as the user clicks the check box?

If so then you need an ajax call something like this would do it:

 <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}" onChange="TriggerFilter(this)" /></td>
                <td>
            </tr>
        </g:each>

<g:javascript>
function TriggerFilter(e) {
   if (e.checked==true) {
     $.get('<g:createLink action='Your_Action' controller="YourController" 
      params="[ filterbind: ''+attrs.filterbind+'',term:''+attrs.term+'' ]"/>'
      ,function(data){
         $('#FilterField').hide().html(data).fadeIn('slow');
       });
   }else{
     $('#FilterField').hide().html('').fadeIn('slow');
   }
}
</g:javascript>



<div id="FilterField" class="filterField">
{Result returned in here}
</div>

You need to fit it e.value into the params take a look at grails java script get createLink there are lots of examples in my plugin here:

https://github.com/vahidhedayati/ajaxdependancyselection/tree/master/grails-app/views

and I would suggest looking online/reading on how to use it

You may wish to change the get to :

how to use grails ${createLink} in javascript

var url = '${createLink(controller:'Books', action: 'update')}' + e.value ;
$.get(url ,function(data){
             $('#FilterField').hide().html(data).fadeIn('slow');
           });
       }else{
         $('#FilterField').hide().html('').fadeIn('slow');
       }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top