Grails: 将项目添加到列表中,并将其附加到父对象上。

问题描述 投票:0回答:1

我有一个Recipe、Ingredient和RecipeIngredient域名,如下图。

class Ingredient {
    String title
}

class Recipe {

    String title
    String description

    static hasMany = [ingredients: RecipeIngredient]
}

class RecipeIngredient {

    Ingredient ingredient

    static belongsTo = [recipe: Recipe]

    Measure measure
    Double amount
}

在我的recipeCreate.gsp页面中,当我想创建一个新的菜谱时,我想把它的成分一个一个地添加到菜谱中,然后再添加到菜谱实例中,并把它们一起保存起来。

<g:form controller="recipe" action="save" method="POST">
    **/* HERE I WANT TO BE ABLE TO ADD ALL INGREDIENTS ONE BY ONE */
    <select value="${recipe_ingredient.ingredient}">
        <g:each in="${allIngredients}" status="i" var="ingredient">
            <option>${ingredient.title}</option>
        </g:each>
    </select>
    <select name="recipe_ingredient.measure" value="${recipe_ingredient.measure}">
        <g:each in="${enums.Measure.values()}" var="m">
            <option>${m}</option>
        </g:each>
    </select>
    <input name="recipe_ingredient.amount" placeholder="Measure" value="${recipe_ingredient.amount}" />
    <g:actionSubmit value="Add" action="addIngredient" />
    /* END */**

    <div class="row">
        <input name="title" value="${instance?.title}" placeholder="Title" />
    </div>

    <div class="row">
        <input name="titleEng" value="${instance?.description}" placeholder="Description" />
    </div>

    <div class="row">
        <g:submitButton name="Create" />
    </div>
</g:form>

我怎样才能实现这样的功能呢?

grails gsp
1个回答
0
投票

直截了当的方法是。

<g:select name="rawIngredients" value="${recipe.ingredients*.ingredient*.id}"
  from="${allIngredients}" optionKey="id" optionValue="title" multiple="true"/>

然后在控制器中,

def save() {
  Recipe recipe // bind or create somehow, e.g. via command-object

  recipe.ingredients?.clear()

  Ingredient.getAll( params.list( 'rawIngredients' ) ).each{ ing ->
    recipe.addToIngredients new RecipeIngredient( ingredient:ing, amount:1, ... )
  }

  recipe.save()
}
© www.soinside.com 2019 - 2024. All rights reserved.