Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from GSP to a controller in Grails

Tags:

grails

I create a GSP page with controls depending on the rows in a database.
This depends on the value returned by the <g:each in="${Vehicles}" var="vehicle"> So, if there are 3 vehicles, 3 rows with text boxes will be generated. (The maximum can be 200)

<g:form action="update" >
      <label for="SearchTerm">${term}</label>

          <g:each in="${Vehicles}" var="vehicle">
            <tr>
                     <td> <label for="Name">${vehicle.name}</label> </td>
                     <td><g:textField name="${vehicle.id}.ModelNo" /> </td>
                     <td><g:textField name="${vehicle.id}.Year" /> </td>
            </tr>
          </g:each>
  <td> <g:submitButton name="update" value="Update"/></td>
  </g:form>

How can I basically pass this value to my controller so that I can then save/update the data to the database. or Is there any easy way to achieve this scenario?

like image 783
WaZ Avatar asked Jan 20 '26 10:01

WaZ


1 Answers

You need some code like this in the GSP

    <g:form action="update" >
          <label for="SearchTerm">${term}</label>

              <g:each in="${Vehicles}" var="vehicle" status="i">
                <tr>
                         <td> <label for="Name">${vehicle.name}</label> </td>
                         <td><g:hiddenField name="vehicle[${i}].id" value="${vehicle.id}"/>
<g:textField name="vehicle[${i}].ModelNo" value="${vehicle.ModelNo}"/> </td>
                         <td><g:textField name="vehicle[${i}].Year" value="${vehicle.Year}"/> </td>
                </tr>
              </g:each>
      <td> <g:submitButton name="update" value="Update"/></td>
    </g:form>

The Controller needs to either have a Domain with a List Property or a Command Object with a List Property ie

SearchCommand {   
  List<Vehicle> vehicle = new Arraylist<Vehicle>(3); 
}

Then in the controller (if using the command object)

def save = {SearchCommand searchCmd-> 
  searchCmd.vehicle.each {vehicle ->
     /* Process Vehicle */
  }
}

Hope that Helps

like image 173
Scott Warren Avatar answered Jan 23 '26 14:01

Scott Warren