Grails命令对象数据绑定
|
Grails对将请求参数绑定到域对象及其关联提供了很好的支持。这在很大程度上取决于检测以“ 0”结尾的请求参数,并自动从数据库中加载这些参数。
但是,尚不清楚如何填充命令对象的关联。请看以下示例:
class ProductCommand {
String name
Collection<AttributeTypeCommand> attributeTypes
ProductTypeCommand productType
}
该对象与ProductTypeCommand
具有单端关联,与AttributeTypeCommand
具有多端关联。所有属性类型和产品类型的列表可从此接口的实现中获得
interface ProductAdminService {
Collection<AttributeTypeCommand> listAttributeTypes();
Collection<ProductTypeCommand> getProductTypes();
}
我使用此界面在GSP中填充产品和属性类型选择列表。我还将这个接口依赖注入到命令对象中,并使用它来“模拟”命令对象上的“ 5”和“ 6”属性
class ProductCommand {
ProductAdminService productAdminService
String name
List<Integer> attributeTypeIds = []
Integer productTypeId
void setProductType(ProductTypeCommand productType) {
this.productTypeId = productType.id
}
ProductTypeCommand getProductType() {
productAdminService.productTypes.find {it.id == productTypeId}
}
Collection<AttributeTypeCommand> getAttributeTypes() {
attributeTypeIds.collect {id ->
productAdminService.getAttributeType(id)
}
}
void setAttributeTypes(Collection<AttributeTypeCommand> attributeTypes) {
this.attributeTypeIds = attributeTypes.collect {it.id}
}
}
实际上发生的是attributeTypeIds
和productTypeId
属性绑定到相关的请求参数,并且getters / setters“ simulate”productType
和attributeTypes
属性。有没有更简单的方法来填充命令对象的关联?
没有找到相关结果
已邀请:
4 个回复
茬贺努充尽
(和attributeType对象类似),并在编辑器注册表中注册它们:
并在您的resources.groovy中注册:
然后在您的Cmd中,您只有:
如果确实需要实际的子命令关联,那么结合PropertyEditorSupport绑定,我可以完成类似于@Andre Steingress所建议的操作:
希望我不会误解您想要实现的目标:)
募磷
对于上面给出的示例,GSP可以引用关联索引
即使对于不存在的索引,此方法也适用,因为LazyList上的每个get(index)调用都会评估列表在该位置上是否已经有元素,如果没有,列表将自动增大大小并从指定的工厂返回一个新对象。 请注意,您也可以使用LazyMap来创建与惰性地图相似的代码: http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LazyMap.html http://commons.apache.org/collections/apidocs/org/apache/commons/collections/list/LazyList.html 更新: Groovy 2.0(尚未包括在Grails发行版中)将为懒惰和渴望的列表提供嵌入式支持。我写了一篇有关该主题的博客文章: http://blog.andresteingress.com/2012/06/29/groovy-2-0-love-for-grails-command-objects/ 更新: 随着Grails 2.2.0的发布,Groovy 2.0已成为发行版的一部分。 http://blog.andresteingress.com/2012/06/29/groovy-2-0-love-for-grails-command-objects/
貉骂
在控制器中:
希望grails的将来版本能够解决此问题,并且可能允许开发人员添加可选的params或params范围,并将其分配给每个命令对象,这可能很有用:)
社攻取墟槽
使用命令对象 接下来,您可能需要做的是将控制器中的动作接收到的数据绑定到命令对象并进行验证。