数据绑定 – Grails命令对象数据绑定
Grails有一个
very good support绑定请求参数到域对象及其关联。这主要依赖于检测以.id结尾的请求参数并自动从数据库加载这些参数。
但是,不清楚如何填充命令对象的关联。请参见以下示例: class ProductCommand { String name Collection<AttributeTypeCommand> attributeTypes ProductTypeCommand productType } 此对象具有与ProductTypeCommand的单端关联以及与AttributeTypeCommand的多端关联。所有属性类型和产品类型的列表都可以从此接口的实现中获得 interface ProductAdminService { Collection<AttributeTypeCommand> listAttributeTypes(); Collection<ProductTypeCommand> getProductTypes(); } 我使用此接口填充GSP中的产品和属性类型选择列表。我也依赖注入这个接口到命令对象,并使用它来“模拟”属性类型和productType属性上的命令对象 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属性。有一个更简单的方法来填充命令对象的关联? 解决方法
你实际上需要为attributeTypes和productType属性提供子命令吗?任何原因你不使用PropertyEditorSupport绑定?例如。:
public class ProductTypeEditor extends PropertyEditorSupport { ProductAdminService productAdminService // inject somewhow void setAsText(String s) { if (s) value = productAdminService.productTypes.find { it.id == s.toLong() } } public String getAsText() { value?.id } } (和attributeType对象类似的东西),并在编辑器注册器中注册这些: import java.beans.PropertyEditorSupport public class CustomEditorRegistrar implements PropertyEditorRegistrar { public void registerCustomEditors(PropertyEditorRegistry reg) { reg.registerCustomEditor(ProductType,new ProductTypeEditor()) reg.registerCustomEditor(AttributeType,new AttributeTypeEditor()) } } 并注册在您的resources.groovy: beans = { customEditorRegistrar(CustomEditorRegistrar) } 那么在你的Cmd你只有: class ProductCommand { String name List<AttributeType> attributeTypes = [] ProductType productType } 如果你确实需要实际的子命令关联,那么我做了一些类似于@Andre Steingress建议的,结合PropertyEditorSupport绑定: // parent cmd import org.apache.commons.collections.ListUtils import org.apache.commons.collections.FactoryUtils public class DefineItemConstraintsCmd implements Serializable { List allItemConstraints = ListUtils.lazyList([],FactoryUtils.instantiateFactory(ItemConstraintsCmd)) //... } // sub cmd @Validateable class ItemConstraintsCmd implements Serializable { Item item // this has an ItemEditor for binding //... } 希望我没有误解你试图实现:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |