Grails Cookbook - A collection of tutorials and examples

Grails checkBox Tag Example

The checkBox tag (<g:checkBox>) generates an HTML checkbox form field. This can be used for many purposes, but the most common is to represent a boolean property of a domain class.
gx01

Simple Usage

This example will look like this:
gx03

Controller code is just simple display form and echo the submitted value

package asia.grails.test
class TestFormController {
	def displayForm() { }	
	def submitForm(String cbfield) {
		render "The value of cbfield is: ${cbfield}"
	}
}

View code is simple render of form using checkBox tag

<html xmlns="http://www.w3.org/1999/html">
<head>
	<meta name="layout" content="main"/>
	<title>CB</title>
</head>
<body>
	<g:form action="submitForm">
		My checkbox: <g:checkBox name="cbfield" value="HELLO" /> 
		<br/>		
		<g:submitButton name="Submit"/>
	</g:form>
</body>
</html>

When the page is displayed, since a value is supplied (HELLO) in the checkBox, it is displayed as checked. If no value or null is assigned, the checkbox is not checked.

When we submit the form with the field checked, the output is:

The value of cbfield is: HELLO

When we submit the form with the field un-checked, the output is:

The value of cbfield is: null

CRUD Form


The checkBox tag is very suitable for representing a boolean property of a domain class in a form. For example, this form:
gx01

Has this section of code in the edit view GSP

<g:form method="post" >
	...
	<div class="fieldcontain">
		<label for="available">
			<g:message code="product.available.label"/>
		</label>
		<g:checkBox name="available" value="${product?.available}" />
	</div>					
	...
</g:form>

When the value of product.available is true, the field is rendered as checked. If it is null or false, it is rendered un-checked.

Other Grails Tag Examples


Tags: checkBox, Grails Tag