g:选择保存到grails中的数据库选定项

时间:2016-08-08 10:55:11

标签: grails

我有桌子:产品和商店。(我使用grails generate-all生成控制器)Shop hasmany products 我正在尝试做的是列出所有商店并在创建新产品时保存到数据库选择的商店。 我使用

列出了所有值
<g:form controller="product" action="save" role="form">
    <div class="form-horizontal" role="form">
        <div class="form-group">
            <label class="col-lg-3 control-label">Product Name:</label>
            <div class="col-lg-8">
                <g:textField name="productName" class="form-control" value="${product.productName}"/>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">Product Barcode</label>
            <div class="col-lg-8">
                <g:textField name="date expired" class="form-control" value="${product.productBarcode}"></g:textField>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">Product Shop</label>
            <g:select class="selectpicker" name="products.id" from="${tr.com.netiket.lkkstoreapp.Shop.list()}" value="shop?.products.id" optionValue="shopName"></g:select>
        </div>
</g:form>

当我点击“创建”按钮时,它会显示

  

类[class tr.com.nur.storeapp.Product]的属性[shop]不能为null

2 个答案:

答案 0 :(得分:0)

这个位看起来不正确:

<g:select class="selectpicker" name="products.id" from="${tr.com.netiket.lkkstoreapp.Shop.list()}" value="shop?.products.id" optionValue="shopName"></g:select>

名称应为商店的ID,值应为产品的商店ID(如果有):

<g:select class="selectpicker" name="shop.id" from="${tr.com.netiket.lkkstoreapp.Shop.list()}" value="${product?.shop?.id}" optionValue="shopName"></g:select>

答案 1 :(得分:0)

 @Transactional
def save(Shop shop) {
    //println "in shop save"
    def currentUser=(User)springSecurityService.currentUser
    shop.user=currentUser
    shop.validate()
    if (!shop) {
        //println "I have no shop"
        transactionStatus.setRollbackOnly()
        notFound()
        return
    }

    //if (shop.hasErrors()) {
     if (shop.save(flush:true)) {
       //println "shop has errors"
        transactionStatus.setRollbackOnly()
        respond shop.errors, view:'create'
        shop.errors.allErrors
        return
    }

    //shop.save flush:true
    //println "shop has saved"

    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.created.message', args: [message(code: 'shop.label', default: 'Shop'), shop.id])
             //println "redirecting"
            redirect shop
        }
        '*' { respond shop, [status: CREATED] }
    }
}

这是我的保存方法。实际上我在这里写了什么。生成域。