Search code examples
grailsgsp

Grails: Add items to list and attach it to its parent object


I have a Recipe, Ingredient and RecipeIngredient domains as below:

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
}

In my recipe/Create.gsp page when I want to create a new recipe, I want to add its ingredients one by one and addto recipe instance and save them all together.

<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>

How can I achieve such thing?


Solution

  • The straight-forward way would be:

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

    Then in the controller:

    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()
    }