【问题标题】:How to get a list of checked boxes in grails如何获取grails中的复选框列表
【发布时间】:2016-03-29 23:38:05
【问题描述】:

在 grails 中,我试图获取选中复选框的列表。 我有复选框列表,但我的问题有两个:

1) 当我单击列表中的单个项目并单击提交时 - 我只得到“开”的值。如果我单击多个复选框项目,我会得到如下信息:

[Ljava.lang.String;@5a37f9f7

2)。我没有得到检查项目的列表或名称。

这是我的 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>   

这是控制器代码(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)
        }
}

我尝试将 id 绑定到复选框,但我不断收到异常错误。

您能提供的任何帮助我都非常感激;我是 grails 的新手。

铁螳螂7x

【问题讨论】:

  • 更新:我将 render params.list('fileName') 添加到控制器,它现在列出了所有选中的复选框 - 但只有状态。我仍然需要真实姓名。
  • 点击多个复选框时,您将获得一组值。所以你不应该使用 String 类型的变量来进行自动数据绑定。要了解您从请求中收到的所有参数,您可以在控制器操作中使用param.keySet() 进行检查。

标签: list grails checkbox groovy


【解决方案1】:

您可以为此使用漂亮的命令对象。为此,首先创建一个具有布尔字段的类 RequestCO。

class RequestCO {
  boolean isChecked;
  String name;
}

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

现在您只需在操作中将所有请求绑定到 RequestParentCO:

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

这将为您提供所有选中的复选框结果。

普惠制

<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"/>

【讨论】:

    【解决方案2】:

    这样,

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

    【讨论】:

    • 我猜你需要使用 name="${ 'fileName'}" 而不是 name="fileName"
    【解决方案3】:

    您可以使用 request.getParameterValues("fileName") 方法,这将在字符串数组中给出选中的复选框

    【讨论】:

    • 是用在控制器还是视图(gsp)中?
    • 用于控制器
    • hmmm ...我试过了,它没有返回任何值。我的语法是:render request.getParameterValues("fileName")。那是正确的吗(它编译并运行时没有编译错误 - 但结果是一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多