Search code examples
grailsgroovygrails-orm

Save multiple selected dropdown values into a single column in Grails


How to save multiple selected dropdown values into a single column in Grails? Input will look like

<g:select name="item1Price" from="${1..10}"/>
<g:select name="item2Price" from="${1..10}"/>
<g:select name="item3Price" from="${1..10}"/>

And Output Should be stored in one field

ItemPrice: 2,8,6

Solution

  • Your question is a bit vague, so hopefully a somewhat vague answer will be helpful too!

    If you have a domain object Foo:

    class Foo {
        String itemPrice
    }
    

    Then in your controller action, you can just do something like:

    def save() {
        Foo f = new Foo()
        f.itemPrice = [params.item1Price, params.item2Price, params.item3Price].join(",")
        f.save()
    }
    

    Really all you're trying to do is join your parameters from your page into one string, right?

    Now this actually seems like bad design to me. What happens if the order changes, or if nothing is selected for item 2? Or what happens if somebody wants to edit your object and you need to parse the values back out? Obviously you could split on commas...until one of the values contains a comma!

    You're better off storing one value for each field that means something different, or storing a single field as a structured value. You might want to look at encoding a Map into JSON and storing that, for example, if you really just want to have one field in your domain object.