ironmantis7x
ironmantis7x

Reputation: 827

How to get a list of checked boxes in grails

In grails, I am trying to get a list of checked check boxes. I have the list of check boxes, but my issues are two:

1) when I click on a single item in the list and click submit - I only get the value "on". If I click more than one check box item, I get something like this:

[Ljava.lang.String;@5a37f9f7

2). I do not get a list or the name of the item checked.

Here is my code for the check boxes in the gsp:

<g:form action="submitForm">
    <ul class="columns3">
        <g:each in="${name}" var="fileName" >
            <g:checkBox value="${false}" name="${ 'fileName'}" /> ${fileName.replaceFirst(~/\.[^\.]+$/, '')}<br>
        </g:each> 
    </ul>
    <br>
    <br>
    <g:submitButton name="Submit"/>
</g:form>   

and here is the controller code (groovy):

class Read_dirController {

    def index() { 

        def list = []

        def dir = new File("/home/ironmantis/Documents/business/test_files")
        dir.eachFileRecurse (FileType.FILES) { file ->
          list << file
        }

        list.each {
            println it.name.replaceFirst(~/\.[^\.]+$/, '')
          }

        render(view: "index",  model: [name:list.name])

        params.list('fileName')

    }

        def displayForm() { }

        def submitForm(String fileName) {
            render fileName
            //render(view: "tests_checked", fileName)
        }
}

I tried to bind an id to the check boxes, but I keep getting an exception error.

Any help you can give I truly appreciate it; I am new to grails.

ironmantis7x

Upvotes: 1

Views: 1782

Answers (3)

Jeevesh pandey
Jeevesh pandey

Reputation: 69

You can use the beautiful command object for this. For this ,first make a class RequestCO having the boolean fields.

class RequestCO {
  boolean isChecked;
  String name;
}

And

class RequestParentCO {
List<RequestCO> requestCOs = [].withLazyDefault { new RequestCO() }
}

Now you just simply bind all your request to RequestParentCO in your action:

def submitForm(RequestParentCO parentCO) {
    println parentCO.requestCOs.findAll { it.isChecked }
}

This will give you all the checked checkboxes results.

GSP

<g:form action="process">
<ul class="columns3">
    <g:each in="${["one", "two", "three"]}" var="fileName" status="i">
        <g:hiddenField name="requestCOs[${i}].name" value="${fileName}"/>
        <g:checkBox name="requestCOs[${i}].isChecked"/> ${fileName}<br>
    </g:each>
</ul>
<g:submitButton name="Submit"/>

Upvotes: 2

hemantgp
hemantgp

Reputation: 362

This way,

def submitForm() { 
def values = request.getParameterValues("fileName") 
//here values contains string array which are selected in checkbox
} 

Upvotes: 1

hemantgp
hemantgp

Reputation: 362

you can use request.getParameterValues("fileName") method, this will give selected checkbox in string array

Upvotes: 0

Related Questions