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.

Simple Usage

This example will look like this:

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="">
	<meta name="layout" content="main"/>
	<g:form action="submitForm">
		My checkbox: <g:checkBox name="cbfield" value="HELLO" /> 
		<g:submitButton name="Submit"/>

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


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

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"/>
		<g:checkBox name="available" value="${product?.available}" />

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