May 01, 2014 Beginner comments
HTML Forms are usually used to gather data from users. This post will show how to make use of forms to save data to the database.
This example will render a form that looks like this:
And on click of save, will save the data to the person table.
Domain Class
We will reuse the domain model from this
previous post:
package asia.grails.myapp
class Person {
String firstName
String lastName
int age
}
This will correspond to a table named "person" with columns "first_name", "last_name", and "age".
View Code
It is simpler to start view code. This is an example of a view page code (form.gsp):
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Form</title>
</head>
<body>
<g:form controller="person" action="save">
<label>First Name: </label>
<g:textField name="firstName"/><br/>
<label>Last Name: </label>
<g:textField name="lastName"/><br/>
<label>Age: </label>
<g:textField name="age"/><br/>
<g:actionSubmit value="Save"/>
</g:form>
</body>
</html>
The form tag above specifies that on submit, the data will be passed to the save method/action of the person controller (PersonController.groovy). The rest is self explanatory.
Read
this post if you are new to Grail's view technology.
Controller Code
Below is an example controller code to display the page above, and handle form submission.
package asia.grails.myapp
class PersonController {
def form() {
}
def save() {
def person = new Person(params)
person.save()
render "Success!"
}
}
The first method
form() will display form.gsp when the user accessed the url http://yourmachine:8080/yourapp/person/form
The second method will accept the submitted data from the HTML form. The code
new Person(params) will create a Person instance, and automatically map data from the form to the instance by property name. Since the form has the property firstName via the code
<g:textField name="firstName"/>, the instance returned by
new Person(params) will populate the firstName property from the data in the form. This is also true for the other fields lastName and age.
The code
person.save() will save the data to the database, while
render "Success!" will display the text to the browser as is.
If you are unfamiliar with controllers, read this
post about MVC and this
post about controllers.
Remarks
This is just a simple example to understand how data is passed from HTML, to controllers, and then to the database. The example lacks important steps like validations, which will be covered in future posts.
List of Tutorials for Beginners