简体   繁体   English

如何将ID列表绑定到Grails中的命令对象?

[英]how to bind list of ids to command object in grails?

Let's say when you submit a form it sends a list of ids. 假设您提交表单时会发送ID列表。

<form action="/process">
<input type="hidden" name="ids" value="4, 6, 10, 14, 20, 56" >
<input type="submit" value="Submit">
</form>

At the controller side 在控制器端

def process(EmailCommand cmd){

   //now iterating over registrations after data binding
   cmd.ids.each {

    }
}


//Command Object
class EmailCommand {
  List<Registration> ids
}

I want to bind all the ids passed to controller to the ids list in EmailCommand command object. 我想将传递给控制器​​的所有ID绑定到EmailCommand命令对象中的ID列表。 How can i achieve it? 我该如何实现? I appreciate any help! 感谢您的帮助! Thanks! 谢谢!

It would be something like 就像

<form action="/process">
    <input type="hidden" name="ids[0].id" value="4" >
    <input type="hidden" name="ids[1].id" value="6" >
    <input type="hidden" name="ids[2].id" value="10" >
    <input type="hidden" name="ids[3].id" value="14" >
    <input type="hidden" name="ids[4].id" value="20" >
    <input type="hidden" name="ids[5].id" value="56" >
    <input type="submit" value="Submit">
</form>

Or if you want something more dynamic : 或者,如果您想要更动态的东西:

<form action="/process">
    <g:each in="[4, 6, 10, 14, 20, 56]" var="id" status="i">
        <input type="hidden" name="ids[${i}]" value="${id}" >
    </g:each>
    <input type="submit" value="Submit">
</form>

I could only get it to work after changing the command object to 我只能将命令对象更改为

class EmailCommand{

    List<Registration> ids=  ListUtils.lazyList([], { new Registration() } as Factory )

}

and view to the following as bassmartin suggested. 并按照bassmartin的建议查看以下内容。

<g:hiddenField name="ids[0].id" value="1"></g:hiddenField>
<g:hiddenField name="ids[1].id" value="2"></g:hiddenField>
<g:hiddenField name="ids[2].id" value="3"></g:hiddenField>
<g:hiddenField name="ids[3].id" value="4"></g:hiddenField>
<g:hiddenField name="ids[4].id" value="5"></g:hiddenField>


<g:submitButton name="submit" value="submit"></g:submitButton>

I am wondering why empty list in command object doesn't work. 我想知道为什么命令对象中的空列表不起作用。 Is this limitation of grails version 2.2? 这是grails 2.2版的限制吗?

You have 2 options here: 您在这里有2个选项:

Straight forward -> trick with the split comma-separated String in the "setter": 直截了当 ->在“ setter”中用逗号分隔的String欺骗:

class EmailCommand {
  List<Registration> ids
  void setIds( String val ){ ids = Registration.getAll( val.split( ', ' ) ) }
}

Correct -> use form params for that: 正确 ->为此使用表单参数:

<form action="/process">

<g:each in="[4, 6, 10, 14, 20, 56]" var="id">
  <input type="hidden" name="ids" value="${id}" >
</g:each>
<input type="submit" value="Submit">
</form>

and let grails do the binding. 让grails进行绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM