Search code examples
grailsgspradiobuttonlist

How to get id value of a selected radio button in a gsp page to grails controller/domain class


USING: grails 1.3.7 fyi.

<g:each var="name" in="${nameList}">
 <li>${name.first}</li>
 <input id="Add" type="radio" name="nameMod" value="${name.first}"/>Add
 <input id="Modify" type="radio" name="nameMod" value="${name.first}"/>Modify
 <g:hiddenField name="action" value="${nameMod.id} "/>
</g:each>

So this is what I'm trying to do: I know how to get the value of the radio buttons but, I also need to know which button was pressed. As you can see from above, I tried to set the ID of the radio button to the action (Add/Modify), but I get an error stating that .id is not a valid property. I know how to test for a radio button being selected or not in jQuery, but I'm not sure how to get the value from jQuery to a controller or domain class.

Is there another way of doing this? Basically I need to know the action and the name, so that I can update the database.

Thanks for any advice! (Is it okay for me to say this? edit away!! ;))


Solution

  • You could do that with jQuery, but this would be a good case for using a command object:

    View:

    <g:each var="name" in="${nameList}" status="i">
      <li>${name.first}</li>
      <input type="radio" name="nameAction[${i}]" value="add"/>Add
      <input type="radio" name="nameAction[${i}]" value="modify"/>Modify
      <g:hiddenField name="name[${i}]" value="${name.first} "/>
    </g:each>
    

    Command Object:

    class NameCommand {
        List<String> nameAction = []
        List<String> name = []
    }
    

    Controller:

    def theAction = { NameCommand foo ->
        foo.nameAction.eachWithIndex { val, index ->
            if (val == "add") {
                whateverService.add(foo.name[index]) 
            }
            else {
                whateverService.modify(foo.name[index])
            }
        }
    }