Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a list of checkboxes

Tags:

grails

I have two domain classes

class Contract {
    String number
    static hasMany = [statements:Statement]
}

class Statement {
    String code
    static hasMany = [contracts:Contract]
}

I would like to show all statements available in my gsp with a checkbox next to each, allowing the user to choose which statements are applicable to the contract. So something like:

[ ] Statement Code 1
[ ] Statement Code 2
[ ] Statement Code 3

I started off with this:

<g:each in="${Statement.list()}" var="statement" status="i">
    <g:checkBox name="statements[${i}].id" value="${statement.id}" checked="${contractInstance.statements.contains(statement.id)}" />
    <label for="statements[${i}]">${statement.code}</label>
</g:each>

But i just cannot get a list of checked statements to the controller (there are null elements in the list, there are repeated statements...).

Any idea how to achieve this?

like image 346
zoran119 Avatar asked Jan 05 '12 04:01

zoran119


2 Answers

This is possible, but it does require a bit of a hack. First off, every checkbox must have the same name, "statements":

<g:each in="${org.example.Statement.list(sort: 'id', order: 'asc')}" var="statement" status="i">
    <g:checkBox name="statements" value="${statement.id}" checked="${contract.statements.contains(statement)}" />
    <label for="statements">${statement.content}</label>
</g:each>

Second, in the controller you have to remove the "_statements" property before binding:

def contract = Contract.get(params.id)
params.remove "_statements"
bindData contract, params
contract.save(failOnError: true)

The check box support hasn't been designed for this use case, hence the need for a hack. The multi-select list box is the one typically used for this type of scenario.

like image 73
Peter Ledbrook Avatar answered Sep 27 '22 19:09

Peter Ledbrook


I personally prefer to get the list of Id's in this case.

<g:each var="book" in="${books}">
    <g:checkBox name="bookIds" value="${book.id}" ...
</g:each>

Command Object:

class BookCommand {
    List<Serializable> bookIds
}

In controller action:

BookCommand bc ->
    author.books = Book.getAll(bc.bookIds)
like image 22
Wytze Avatar answered Sep 27 '22 18:09

Wytze