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

时间:2020-06-15 10:30:34

标签: grails gsp

我有一个Recipe,成分和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
}

在我的食谱/Create.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>

我该如何实现?

1 个答案:

答案 0 :(得分: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()
}