294
COMMAND LINE USAGE Grails incorporates the powerful build system Gant, which is a Groovy wrapper around Apache Ant. bootstrap The basic usage scenario is: grails [environment]* [command name] Grails will search for Gant scripts that match the given name in the following locations: o USER_HOME/.grails/scripts o PROJECT_HOME/scripts o PROJECT_HOME/plugins/*/scripts o GRAILS_HOME/scripts If Grails discovers multiple commands matching the name entered it will offer you a choice as to which one to execute. To specify an alternative environment to execute a particular command within you can specify an optional environment parameter either with one of the built in environments: grails dev run-app grails prod run-app Or using an argument grails -Dgrails.env=uat run-app Refer to the user guide section on The Command Line for more information.

grails command main

  • Upload
    nikcool

  • View
    739

  • Download
    0

Embed Size (px)

Citation preview

Page 1: grails command main

COMMAND LINE USAGE

Grails incorporates the powerful build system Gant, which is a Groovy wrapper around Apache Ant. bootstrap

The basic usage scenario is:

grails [environment]* [command name]

Grails will search for Gant scripts that match the given name in the following locations:

o USER_HOME/.grails/scripts o PROJECT_HOME/scripts o PROJECT_HOME/plugins/*/scripts o GRAILS_HOME/scripts

If Grails discovers multiple commands matching the name entered it will offer you a choice as to which one to execute.

To specify an alternative environment to execute a particular command within you can specify an optional environment parameter either with one of the built in environments:

grails dev run-app

grails prod run-app

Or using an argument

grails -Dgrails.env=uat run-app

Refer to the user guide section on The Command Line for more information.

Page 2: grails command main

ADD-PROXY

Purpose

Adds a proxy configuration that Grails can use when communicating over the internet such as with the install-plugin command.

The proxy configuration can be activated with the set-proxy command.

Examples

grails add-proxy client --host=proxy-server --port=4300 --username=guest --

password=guest

Description

Usage:

grails add-proxy [name] --host=[server] --port=[port] --

username=[username]* --password=[password]*

Arguments:

o name - The name of the proxy configuration

o host - The server host

o port - The server port

o username (optional) - The server username

o password (optional) - The server password

Page 3: grails command main

BOOTSTRAP

Purpose

The bootstrap command is mainly intended to be used by other scripts and enables the ability to bootstrap a Grails application instance outside of the container for usage in tools that require a reference to Grails' ApplicationContext

Examples of its usage include Grails' shell and console

Examples

When used as an include you need to supply the following at the top of your Gant script:

includeTargets << new File ( "${grailsHome}/scripts/Bootstrap.groovy" )

Once this is in place you can bootstrap Grails using two distinct methods:

o loadApp - Loads and creates the GrailsApplication instance

o configureApp - Loads all the Grails plug-ins and creates the Spring ApplicationContext

The loadApp command will create a grailsApp variable which you can the evaluate:

loadApp()

grailsApp.allClasses.each { println it }

The configureApp command will create pluginManager and appCtx variables

representing the GrailsPluginManager instance and the Spring ApplicationContext

configureApp()

Connection c = appCtx.getBean('dataSource').getConnection()

// do something with connection

Description

Usage:

grails bootstrap

Page 4: grails command main

BUG REPORT

Purpose

The bug-report command will package up only the sources of your application (excluding jars, static resources etc.) into a zip file with a timestamp appended. This is useful for reporting issues to the Grails JIRA installation

Examples

grails bug-report

Description

Usage:

grails bug-report

Page 5: grails command main

CLEAN

Purpose

The clean command will delete all compiled resources from the current Grails

application. Since Groovy is a compiled language, as with Java, this is sometimes useful to clear old instances of classes out and ensure correct compilation

Examples

grails clean

Description

Usage:

grails clean

Page 6: grails command main

CLEAR PROXY

Purpose

Clears the current proxy configuration Grails should use when communicating over the internet such as with the install-plugin command.

Proxy configurations are defined using the add-proxy command

Examples

grails clear-proxy

Description

Usage:

grails clear-proxy

Page 7: grails command main

COMPILE

Purpose

The compile command will execute the compile phase of the Grails pre-packaging

process, which pre-compiles Groovy and Java sources.

Examples

grails compile

Description

Usage:

grails compile

You can enable verbose compilation for any Grails task by passing the flag -

verboseCompile to the task (e.g. grails run-app -verboseCompile), or by setting

theverboseCompile Grails build setting.

Fired Events:

o CompileStart - Before compilation begins

o CompileEnd - After compilation completes

Page 8: grails command main

CONSOLE

Purpose

Starts an instance of the Swing graphical Groovy console with an initialized Grails runtime.

Examples

grails console

Description

Starts the Grails console, which is an extended version of the regular Groovy console. Within the binding of the console there are a couple of useful variables:

o ctx - The Spring ApplicationContext instance

o grailsApplication - The GrailsApplication instance

These are useful as they allow access to the conventions within Grails and interesting beans in the context.

Usage:

grails [environment]* console

Fired Events:

o StatusFinal - When the console is loaded

Screenshot:

Page 9: grails command main

CREATE - APP

Purpose

The starting point for Grails. This command creates a Grails application and requires the user to specify the application name. A subdirectory within the directory the command was executed from is then created based on the entered application name.

Examples

grails create-app bookstore

cd bookstore

Description

Usage:

grails create-app [name]

Page 10: grails command main

CREATE CONTROLLER

Purpose

The create-controller command will create a controller and associated integration

test for the given base name.

Examples

grails create-controller book

Description

Creates a controller for the given base name. For example for a base name "book" a

controller called BookController will be created in the grails-

app/controllers directory.

A controller is responsible for dealing with incoming web request and performing actions such as redirects, rendering views and so on. For more information on controllers refer to the section onControllers

Note that this command is merely for convenience and you can also create controllers in your favourite text editor or IDE if you choose.

Usage:

grails create-controller [name]

Fired Events:

o CreatedFile - When the controller is created

Page 11: grails command main

CREATE DOMAIN CLASS

Purpose

The create-domain-class command will create a domain and associated integration

test for the given base name.

Examples

grails create-domain-class book

Description

Creates a domain class for the given base name. For example for a base name "book" a domain class called Book will be created in the grails-app/domain directory.

A domain class represents the core model behind in your application and is typically mapped onto database tables. For more information on domain models in Grails refer to the chapter on GORMin the user guide.

Note that this command is merely for convenience and you can also create domain classes in your favourite text editor or IDE if you choose.

Usage:

grails create-domain-class [name]

Fired Events:

o CreatedFile - When the domain class is created

Page 12: grails command main

CREATE FILTERS

Purpose

The create-filters command will create a Grails filters class for the given base name.

Examples

grails create-filters logging

Description

Creates a filters class for the give base name. For example for a base name logging a

filters class called LoggingFilters will be created in the grails-app/conf directory.

Note that this command is merely for convenience and you can also create filters in your favorite text editor or IDE if you choose.

Usage:

grails create-filters [name]

Fired Events:

o CreatedFile - When the filters class has been created

Page 13: grails command main

CREATE HIBERNATE CFG XML

Purpose

The create-hibernate-cfg-xml command will create a hibernate.cfg.xml file for

custom Hibernate mappings.

Examples

grails create-hibernate-cfg-xml

Description

Creates a hibernate.cfg.xml file in the grails-app/conf/hibernate directory. You

can add <mapping> elements there to reference annotated Java domain classes, classes

mapped by hbm.xml files, or hbm.xml files containing <database-object> elements

defining custom DDL that's not supported by GORM.

Usage:

grails create-hibernate-cfg-xml

Fired Events:

o CreatedFile - When the file is created

Page 14: grails command main

CREATE INTEGRATION TEST

Purpose

The create-integration-test command will create an integration test for the given

base name.

Examples

grails create-integration-test book

Description

Creates an integration test for the given base name. For example for a base name

"book" an integration test called BookTests will be created in

the test/integration directory.

An integration test differs from a unit test in that the Grails environment is loaded for each test execution. Refer to the section on Unit Testing of the user guide for information on unit vs. integration testing.

Note that this command is merely for convenience and you can also create integration tests in your favourite text editor or IDE if you choose.

Usage:

grails create-integration-test [name]

Fired Events:

o CreatedFile - When the integration test is created

Page 15: grails command main

CREATE PLUGIN

Purpose

The create-plugin command will create a Grails plug-in project.

Examples

grails create-plugin simple

Description

Creates a Grails plug-in project. A Grails plug-in project is just like a regular Grails project except it contains a plug-in descriptor and can be packaged up as a plug-in and installed into other applications.

Plug-ins are not just useful for plug-in developers, but also as a way to modularize large Grails applications. Refer to the section on Plug-in Development in the user guide for more information on developing plug-ins for Grails.

Usage:

grails create-plugin [name]

Fired Events:

o StatusFinal - When the plug-in has been created

Page 16: grails command main

CREATE SCRIPT

Purpose

The create-script command will create a new Grails executable script that can be run

with the grails command from a terminal window.

Examples

The command:

grails create-script execute-report

Creates a script called scripts/ExecuteReport.groovy such as:

target('default': "The description of the script goes here!") {

doStuff()

}

target(doStuff: "The implementation task") {

// logic here

}

The command can then be run with:

grails execute-report

Description

The command will translate lower case command names, separated by hyphens into a

valid Groovy class name with camel case. For example create-controller would

become a script calledscripts/CreateController.groovy.

The script generated is a Gant script which can use Gant's capabilities to depend on other scripts from Grails core. Refer to the section on Command Line Scripting in the user guide.

Usage:

grails create-script [name]

Fired Events:

o CreatedFile - When the script has been created

Page 17: grails command main

CREATE SERVICE

Purpose

The create-service command will create a Grails service class for the given base

name.

Examples

grails create-service book

Description

Creates a service for the give base name. For example for a base name book a service

called BookService will be created in the grails-app/services directory.

A service class encapsulates business logic and is delegated to by controllers to perform the core logic of a Grails application. For more information on tags refer to the section on Services in the user guide.

Note that this command is merely for convenience and you can also create services in your favorite text editor or IDE if you choose.

Usage:

grails create-service [name]

Fired Events:

o CreatedFile - When the service has been created

Page 18: grails command main

CREATE TAG LIB

Purpose

The create-tag-lib command will create a tag library and associated integration test

for the given base name.

Examples

grails create-tag-lib book

Description

Creates a tag library for the give base name. For example for a base name book a tag

library called BookTagLib will be created in the grails-app/taglib directory.

A tag library is a "view helper" that in MVC terms helps the view with rendering by providing a set of re-usable tags. For more information on tags refer to the section on Tag Libraries in the user guide.

Note that this command is merely for convenience and you can also create controllers in your favourite text editor or IDE if you choose.

Usage:

grails create-tag-lib [name]

Fired Events:

o CreatedFile - When the tag library has been created

Page 19: grails command main

CREATE UNIT TEST

Purpose

The create-unit-test command will create an unit test for the given base name.

Examples

grails create-unit-test book

Description

Creates a unit test for the given base name. For example for a base name book an unit

test called BookTests will be created in the test/unit directory.

An unit test differs from an integration test in that the Grails environment is not loaded for each test execution and it is left up to you to perform the appropriate Mocking using GroovyMock or a Mock library such as EasyMock

Refer to the section on Unit Testing of the user guide for information on unit vs. integration testing.

Note that this command is merely for convenience and you can also create integration tests in your favourite text editor or IDE if you choose.

Usage:

grails create-unit-test [name]

Fired Events:

o CreatedFile - When the unit test is created

Page 20: grails command main

DEPENDECY REPORT

Purpose

The dependency-report command will output an Ivy report showing the JAR

dependencies required by the application.

Examples

grails dependency-report

grails dependency-report runtime

Description

Usage:

grails dependency-report [configuraiton]

Page 21: grails command main

DOC

Purpose

Generates javadoc and groovydoc documentation from the current Grails project.

Examples

grails doc

Description

Since Grails is a mixed source framework it is useful to have both Java and Groovy documentation to cover the system. The doc command generates javadoc (the standard format for Java documentation) and groovydoc comments.

The documentation itself is generated into the following directories:

o docs/api - Location of javadoc comments

o docs/gapi - Location of groovydoc comments

Usage:

grails doc

Fired Events:

o DocStart - Before documentation generation begins

o DocEnd - After documentation generation completes

Page 22: grails command main

GENERATE ALL

Purpose

Generates a controller and views for the given domain class

Examples

grails generate-all Book

grails generate-all *

Description

Grails supports a feature known as scaffolding which involves the generation of a CRUD (Create/Read/Update/Delete) interface for a given domain class.

The generate-all command allows you to generate an implementation of CRUD including

a controller and views for the given domain class. So for a domain class Book a

controller in grails-app/controllers/BookController.groovy and views in grails-

app/views/book will be generated.

Usage:

grails generate-all [domain class name or wildcard]

Fired Events:

o StatusUpdate - When generation begins

o StatusFinal - When generation completes

Page 23: grails command main

GENERATE CONTROLLER

Purpose

Generates a controller for the given domain class

Examples

grails generate-controller Book

Description

Grails supports a feature known as scaffolding which involves the generation of a CRUD (Create/Read/Update/Delete) interface for a given domain class.

The generate-controller command allows you to generate a controller that implements

CRUD for the given domain class. So for a domain class Book a controller in grails-

app/controllers/BookController.groovy will be generated.

Usage:

grails generate-controller [domain class name]

Fired Events:

o StatusUpdate - When generation begins

o StatusFinal - When generation completes

Page 24: grails command main

GENEARATE VIEWS

Purpose

Generates a set if views for the given domain class

Examples

grails generate-views Book

Description

Grails supports a feature known as scaffolding which involves the generation of a CRUD (Create/Read/Update/Delete) interface for a given domain class.

The generate-views command allows you to generate a set of views that implement

CRUD for the given domain class. So for a domain class Book views in grails-

app/views/book will be generated.

Usage:

grails generate-views [domain class name]

Fired Events:

o StatusUpdate - When generation begins

o StatusFinal - When generation completes

Page 25: grails command main

HELP

Purpose

Displays Grails command line help

Examples

grails help

grails help run-app

Description

Usage:

grails help [command name]*

Page 26: grails command main

INIT

Purpose

The init command initialises the appropriate directory structure for a Grails application

and set some common variables that can be used by plug-ins and other scripts. It is typically used as an include.

Examples

Command line:

grails init

As an include:

includeTargets << new File ( "${grailsHome}/scripts/Init.groovy" )

Page 27: grails command main

INSTALL DEPENDENCY

Purpose

Installs a JAR dependency, making it available to Grails dependency resolution mechanism.

Examples

grails install-dependency mysql:mysql-connector-java:5.1.5

grails install-dependency mysql:mysql-connector-java:5.1.5 --dir=lib

grails install-dependency --group=mysql --name=mysql-connector-java --

version=5.1.5

Description

Usage:

grails install-dependency [dependency]

Arguments:

o group - The group of the dependency

o name - The name of the dependency

o version - The version of the dependency

o repository - The repository to resolve from

o dir - The target directory to resolve JAR files to

The install-dependency command allows the installation of a JAR dependency into the

Ivy cache so that it can be resolved locally (without needing to configure a repository explicitly).

In its most simple form you can pass a single argument that defines the dependency in the form "group:name:version":

grails install-dependency mysql:mysql-connector-java:5.1.5

Grails has some built in common public Maven repositories that will be used to resolve the dependency. If the dependency is not found you can specify your own repository

using the repositoryargument:

grails install-dependency mysql:mysql-connector-java:5.1.5 --

repository=http://download.java.net/maven/2

By default the JARs will be resolved to your local Ivy cache

(typically USER_HOME/.ivy2/cache), if you wish the JAR files to be placed in an

alternative directory you can use the dir argument:

grails install-dependency mysql:mysql-connector-java:5.1.5 --dir=lib

Page 28: grails command main

INSTALL PLUGIN

Purpose

Installs a plug-in from a file, URL or the Grails central SVN repository

Examples

grails install-plugin http://foo.com/grails-bar-1.0.zip

grails install-plugin ../grails-bar-1.0.zip

grails install-plugin jsecurity

grails install-plugin jsecurity 0.1

Description

Usage:

grails install-plugin [URL/File]

grails install-plugin [name] [version]*

Fired Events:

o StatusUpdate - Fired at various points during the plug-in installation

o StatusError - When an error occurs during plug-in installation

o StatusFinal - When the plug-in is installed successfully

o PluginInstalled - When the plug-in is installed successfully

The install-plugin command is a versatile command that allows the installation of

plug-ins from a remote URL, a local file or from the Grails central SVN repository at http://plugins.grails.org

To install from a URL, simply specify the absolute URL to the plug-in package:

grails install-plugin http://foo.com/grails-bar-1.0.zip

To install from a local file, specify the absolute or relative path to the file:

grails install-plugin ../grails-bar-1.0.zip

You can also install plug-ins provided via the remote central repository. To find out what plug-ins are available use list-plugins

If you want to install a plug-in, say the "jsecurity" plug-in, you can use the install-plugin command followed by the plugin name:

grails install-plugin jsecurity

This will install the latest version of the plug-in. If you need to install a specific version you can use:

grails install-plugin jsecurity 0.1

Page 29: grails command main

INSTALL TEMPLATES

Purpose

Installs the templates used by Grails during code generation

Examples

grails install-templates

Description

Usage:

grails install-templates

Fired Events:

o StatusUpdate - When the templates are successfully installed

The install-templates command will install the set of templates Grails uses for all

code generation activities to the src/templates directory. The templates installed are

as follows:

src

templates

artifacts

scaffolding

war

The artifacts directory contains the templates used by the create-* commands.

The scaffolding directory contains templates used by the generate-* commands.

The war directory contains the web.xml template used to generate the deployment

descriptor.

Page 30: grails command main

INTEGRATE WITH

Purpose

The integrate-with command allows Grails to be integrated with a variety of IDEs and

build systems.

Examples

grails integrate-with --eclipse --intellij --textmate --ant

Description

Usage:

grails integrate-with [ARGUMENTS]

The integrate-with command will integrate Grails with different IDEs and build

systems based on the arguments provided. For example the eclipse command will

produce Eclipse project andclasspath for use with SpringSource STS.

The command is however extensible. For example if you want to provide

a myide command you can do so by creating an _Events.groovy file and handling

the IntegrateWithStart event:

eventIntegrateWithStart = {

binding.integrateMyide = {

// your code here

}

}

Fired Events:

o IntegrateWithStart - Fired when the script is first run

o IntegrateNAMEStart - Fired when each integration starts (eg. IntegrateEclipseStart)

o IntegrateNAMEEnd - Fired when each integration ends (eg. IntegrateIntellijEnd)

o IntegrateWithEnd - Fired when the script finishes

Page 31: grails command main

INTERACTIVE

Purpose

The interactive command starts the Grails CLI in interactive mode.

Example

grails interactive

Description

Usage:

grails [environment]* interactive

Starts the Grails CLI (script runner) in interactive mode. Interactive mode behaves the same as running Grails commands from the command line, but keeps the JVM running in between scripts. A simple command shell allows running and re-running grails commands.

By keeping the JVM running, interactive mode avoids the (costly) JVM startup time for running successive Grails commands. It also allows the JVM JIT compiler to optimize Grails scripts, so repeated commands will execute more quickly after the initial run. This significantly speeds up repeated runs of unit tests for example.

See also shell and console commands for ways to interact with a running grails

app.

Page 32: grails command main

LIST PLUGIN UPDATES

Purpose

Lists the versions of updated plugins available from the Grails standard repository

Description

Usage:

grails list-plugin-updates

Lists the plugins that are updateable in the Grails standard repository. Note: This command can take a while to execute depending on your internet connectivity. Typical output looks like this:

Plugins with available updates are listed below:

-------------------------------------------------------------

<Plugin> <Current> <Available>

acegi 0.4 0.5.2

console 0.1 0.2.2

The first column contains the plugin name, the second the installed version and the last the current version. If you require more info about a plugin you can use the plugin-info command. If you wish to update a plugin you can use the plugin name and/or version in combination with the install-plugin.

Note: If you are behind a proxy you may want to consider using the set-

proxy command prior to running this command.

Page 33: grails command main

LIST PLUGINS

Purpose

Lists the plug-ins available from the Grails standard repository

Examples

grails list-plugins

Description

Usage: grails list-plugins

grails list-plugins -repository=myRepository

grails list-plugins –installed

Fired Events:

o StatusUpdate - When the plug-in list is being refreshed

o StatusError - When there was an error updating the plug-in list

Arguments:

o repository - The name of the repository used to produce the list of available plugins,

otherwise all known repositories will be scanned. See the section on Plugin repositories in the user guide.

o installed - List only the plugins that are installed into the current Grails application.

Lists the plug-ins that are installable via the Grails standard repository. Note: This command can take a while to execute depending in your internet connectivity. Typical output looks like this:

Plug-ins available in the Grails repository are listed below:

-------------------------------------------------------------

acegi <no releases> -- No description available

aop <no releases> -- No description available

autorest <no releases> -- No description available

cache <no releases> -- No description available

cas-client <0.2> -- This plugin provides client

integrat…

converters <0.3> -- Provides JSON and XML Conversion

for…

dbmapper <0.1.5> -- Database relation to domain

object…

dbmigrate <0.1.2> -- Database migration tasks

The first column contains the plugin name, the second the version and the last the description. If you require more info about a plug-in you can use the plugin-info command. If you wish to install a plug-in you can use the plug-in name and/or version in combination with the install-plugin.

Note: If you are behind a proxy you may want to consider using the set-proxy command prior to running this command.

Page 34: grails command main

PACKAGE PLUGIN

Purpose

Packages a plug-in as a zip archive which can then be installed into another application

Examples

grails package-plugin

Description

Usage:

grails package-plugin

Fired Events:

o StatusError - When there was an error during packaging

The plug-in archive will be named with the convention grails-name-version.zip. The

name and version are obtained from the plug-in descriptor (the Groovy class ending

with the conventionGrailsPlugin.groovy) in the root of the plug-in directory. For

example the following plug-in:

class SimpleGrailsPlugin {

def version = 0.1

}

Will result in a zip archive called grails-simple-0.1.zip, which can then be installed

into an application with the install-plugin command.

Page 35: grails command main

PACKAGE

Purpose

Runs the packaging phase of Grails' runtime. This is mainly useful when used by other scripts.

Examples

As an include:

includeTargets << new File ( "${grailsHome}/scripts/Package.groovy" )

As a command:

grails package

Description

Usage:

grails package

When used as an include you need to supply the following at the top of your Gant script:

includeTargets << new File ( "${grailsHome}/scripts/Package.groovy" )

Once this is in place there are a number of useful commands that can be re-used:

o loadPlugins - Loads all of the Grails plug-ins and creates the GrailsPluginManager

instance

o generateWebXml - Generates the Grails web.xml deployment descriptor

o generateLog4j - Generates the Grails log4j properties file

o packageApp - Calls all of the above 3 targets in the appropriate order

Typically packageApp is the most useful as it performs all the necessary packaging steps

Page 36: grails command main

PLUGIN INFO

Purpose

Displays detailed info about a given plug-in

Examples

grails plugin-info jsecurity

Description

Usage:

grails plugin-info [name]

This command will display more detailed info about a given plug-in such as the author, location of documentation and so on. An example of the output of the JSecurity plug-in can be seen below:

--------------------------------------------------------------------------

Information about Grails plugin

--------------------------------------------------------------------------

Name: jsecurity | Latest release: 0.1.1

--------------------------------------------------------------------------

Security support via the JSecurity framework.

--------------------------------------------------------------------------

Author: Peter Ledbrook

--------------------------------------------------------------------------

Find more info here: http://grails.codehaus.org/JSecurity+Plugin

--------------------------------------------------------------------------

Adds a security layer to your Grails application, allowing you to

protect pages based on a user's roles and/or permissions.

Page 37: grails command main

RELEASE PLUGIN

Purpose

Tags and releases a Grails plug-in to the Grails plug-in repository

Examples

grails release-plugin

Description

Usage: grails release-plugin

grails release-plugin -repository=myRepository

grails release-plugin -pluginlist

This command is for users who have access to the Grails standard plug-in repository at http://plugins.grails.org

The command allows Grails to manage the release process for you by integrating SVN

with Grails. The release-plugin command supports the following arguments:

o repository - The name of the repository to publish to. See the section on Plugin

repositories in the user guide.

o pluginlist - Publish only an updated plugin list and not the plugin itself

o zipOnly - Use this flag if you want to only publish the plugin zip files and metadata and

not the sources

o skipMetadata - Skips the generation of plugin behavior metadata (used to inform IDEs

of new methods etc.)

o skipDocs - Skips the generation of groovydoc and plugin reference documentation

o snapshot - Creates a snapshot release that will not replace the 'latest' release but can

be installed by specifying the version number

o username - The username to use

o password - The password to use

o message - The commit message to use

If you require access to repository and wish to release your plug-in there contact a member of the Grails development team.

The command will check whether the plug-in currently exists in the repository and if not will check-in the plug-in and create a release. The command will automatically upload

the plugin to a location such as http://plugins.grails.org/grails-name. It will also

automatically create the following structure:

grails-[name]

tags

LATEST_RELEASE

RELEASE_XY

trunk

Page 38: grails command main

The trunk directory contains the current latest sources. The tags directory contains

tagged versions of each release and a LATEST_RELEASE tag that indicates the current

latest release.

If the plug-in already exists in the repository Grails will update first, then commit the latest change and finally tag the release.

Either way the plug-in will then automatically be available via the list-plugins command.

Page 39: grails command main

REMOVE PROXY

Purpose

Removes a proxy configuration that Grails can use when communicating over the internet such as with the install-plugin command.

Proxy configurations can be added with the add-proxy command.

Examples

grails remove-proxy client

Description

Usage:

grails remove-proxy [name]

Arguments:

o name - The name of the proxy configuration

Page 40: grails command main

RUN APP

Purpose

Runs Grails using the installed container on port 8080

Examples grails run-app

grails run-app -https // with HTTPS

grails test run-app

grails -Dserver.port=8090 -Denable.jndi=true -Ddisable.auto.recompile=true

run-app

Description

Usage: grails [env]* run-app

Arguments:

o https - Start an HTTPS server (on port 8443 by default) alongside the main server. Just

to be clear, the application will be accessible via HTTPS and HTTP.

Supported system properties:

o disable.auto.recompile - Disables auto-recompilation of Java sources, which can be

processor intensive (defaults to false)

o recompile.frequency - Specifies how frequently (in seconds) Grails checks for changes

to Java and Groovy sources in your project (defaults to 3).

o grails.server.port.http/server.port - Specifies the HTTP port to run the server on

(defaults to 8080)

o grails.server.port.https - Specifies the HTTPS port to run the server on (defaults to

8443)

o grails.server.host/server.host - Specifies the host name to run the server on

(defaults to localhost)

Fired Events:

o StatusFinal - When the container has been started

o StatusUpdate - When the container is reloading

This command will start Grails up in an embedded servlet container that can serve HTTP requests. The default container used is Tomcat However, alternative containers are supported via the plugin system. For example to run Grails with Jetty run the following two commands: grails uninstall-plugin tomcat

grails install-plugin jetty

This target is not intended for deployment as the container in development mode is configured to auto-reload changes at runtime which has an overhead attached to it and will not scale well.

Page 41: grails command main

RUN SCRIPT

Purpose

Runs one or more custom Groovy scripts, bootstrapping the Grails application first. Gant scripts can't directly call application classes since they aren't on the classpath when the script is compiled. You can load them dynamically but this complicates the scripts.

This script configures the Grails environment, so the Spring application context and Hibernate/GORM are available and you can access the database using domain classes, call service methods, etc.

In addition, the script(s) run in the context of a Hibernate Session to avoid lazy loading exceptions.

Examples

// run a single script in the dev environment

grails run-script userScripts/createBook.groovy

// run multiple scripts in the dev environment

grails run-script userScripts/someScript.groovy

userScripts/otherScript.groovy

// run a single script in the prod environment

grails prod run-script userScripts/updateDatabase.groovy

Also see Ted Naleid's Blog for more usage examples.

Description

Usage:

grails [environment] run-script [scriptName]

Arguments:

o environment - The environment containing the database configuration to use (dev,

prod, etc...).

o scriptName - one or more paths to scripts to run

Page 42: grails command main

RUN WAR

Purpose

Packages the current Grails application into a Web Application Archive (WAR) file and

runs the application in a Tomcat container on port 8080.

Examples

grails run-war

grails run-war -https // with HTTPS

grails run-war -restart // restarts without rebuilding the war

grails prod run-war

grails -Dserver.port=8090 run-war

Description

Usage:

grails [env]* run-war

Arguments:

o https - Start an HTTPS server (on port 8443 by default) alongside the main

server. Just to be clear, the application will be accessible via HTTPS and HTTP.

o restart - Does not rebuild an already existing WAR.

Supported system properties:

o grails.server.port.http/server.port - Specifies the HTTP port to run the

server on (defaults to 8080)

o grails.server.port.https - Specifies the HTTPS port to run the server on

(defaults to 8443)

o grails.server.host/server.host - Specifies the host name to run the server

on (defaults to localhost)

o grails.tomcat.jvmArgs - A list of JVM arguments to be used for the forked

JVM, e.g. ["-Xms128m", "-Xmx512m"] (defaults to ["-Xmx512m"])

Fired Events:

o StatusFinal - When the container has been started

o StatusUpdate - When the container is reloading

This command will package Grails inside a WAR file and then run it with the installed container. Useful for quick deployment and/or testing. However, unlike run-app this command does not support reloading as a Grails WAR archive does not ship with Groovy sources, but only compiled byte code.

Page 43: grails command main

SCHEMA EXPORT

Purpose

Uses Hibernate's SchemaExport tool to generate DDL or export the schema.

Examples

grails schema-export

grails prod schema-export

grails dev schema-export

grails prod schema-export export

grails prod schema-export stdout

Description

Usage:

grails [environment] schema-export [action] ['stdout'] [filename]

Arguments:

o environment - The environment containing the database configuration to use (dev,

prod, etc...).

o action - Either 'generate' or 'export'. The default is 'generate'. Specifying 'export' will

execute the script against the specified environment's database instead of just generating the ddl file.

o stdout - Passing 'stdout' will cause the script to dump the ddl to stdout.

o filename - The name of the file to write the ddl to. The default is ddl.sql in the project's

'target' folder.

Page 44: grails command main

SET PROXY

Purpose

Activates a proxy configuration Grails should use when communicating over the internet such as with the install-plugin command.

Proxy configurations are defined using the add-proxy command

Examples

grails add-proxy client --host=proxy-server --port=4300 --username=guest --

password=guest

grails set-proxy client

Description

Usage:

grails set-proxy [configuration]

Arguments:

o configuration - The proxy configuration name

Page 45: grails command main

SET VERSION

Purpose

Sets the current application version inside the application metadata file

(application.properties)

Examples

grails set-version 0.6

Description

Usage:

grails set-version [number]

o StatusFinal - When the version has been set

When executing Grails retains metadata about the currently executing application inside the GrailsApplication object. The version of the application is one such item of metadata. The version is used by the Grails war command to produce a versioned WAR archive and can also be used by the application at runtime to validate application state.

Page 46: grails command main

SHELL

Purpose

Starts an instance of the Groovy terminal shell with an initialized Grails runtime.

Examples

grails shell

Description

Usage:

grails [environment]* shell

Starts the Grails shell, which is an extended version of the regular Groovy shell. Within the binding of the shell there are a couple of useful variables:

o ctx - The Spring ApplicationContext instance

o grailsApplication - The GrailsApplication instance

These are useful as they allow access to the conventions within Grails and interesting beans in the context.

Fired Events:

o StatusFinal - When the shell is loaded

Example Shell:

Groovy Shell (1.1-rc-1, JVM: 1.5.0_07-87)

Type 'go' to execute statements; Type 'help' for more information.

groovy> Book.list()

groovy> go

Page 47: grails command main

STATS

Purpose

Outputs basic statistics about the current Grails application, including number of files, line count and so on

Examples

> grails stats

+----------------------+-------+-------+

| Name | Files | LOC |

+----------------------+-------+-------+

| Controllers | 1 | 66 |

| Domain Classes | 1 | 3 |

| Integration Tests | 2 | 8 |

+----------------------+-------+-------+

| Totals | 4 | 77 |

+----------------------+-------+-------+

Page 48: grails command main

TEST APP

Purpose

Runs all Grails unit and integration tests and outputs reports. The command will return appropriate response codes for embedding with continuous integration servers.

Examples

grails test-app

grails test-app Foo

grails test-app Foo Bar

Description

Usage:

grails [environment]* test-app [names]*

Fired Events:

o StatusFinal - When the test cycle completes

Executes the Grails unit and integration tests located in

the test/unit and test/integration directories. By default all tests are executed, but

you can specify the names of the tests (without the "Tests" or other test type suffix) as argument to the command:

grails test-app Foo

grails test-app Foo Bar

The first example will execute a test called FooTests.groovy whilst the second will

execute FooTests.groovy and BarTests.groovy if they exist.

As of Grails 1.2.2, tests can also use the suffix of Test instead of Tests.

You can also choose to only run the unit or integration tests:

grails test-app unit:

grails test-app integration:

If you only wish to re-run failed tests use the -rerun flag

grails test-app -rerun

See the Testing section for examples on how to combine the different options to target tests.

Page 49: grails command main

UNINSTALL PLUGIN

Purpose

Uninstalls a installed plug-in from the current Grails application.

Examples

grails uninstall-plugin jsecurity

Description

Usage:

grails uninstall-plugin [name]

This target will perform a clean and then uninstall the plugin for the given name if it is already installed. The command will remove any metadata referring to the plugin from

theapplication.properties file and executed the scripts/_Uninstall.groovy file

contained within the plugin.

Page 50: grails command main

UPGRADE

Purpose

The upgrade command will upgrade the current Grails application to currently installed

version of Grails if possible.

Examples

grails upgrade

Description

Usage:

grails upgrade

Fired Events:

o StatusUpdate - During the upgrade process

o StatusFinal - After the upgrade completes

Page 51: grails command main

WAR

Purpose

The war command will create a Web Application Archive (WAR) file which can be

deployed on any Java EE compliant application server

Examples

grails war

grails test war

grails -Dgrails.env=foo war

Description

Usage:

grails [environment]* war [arguments]*

Arguments:

o nojars - Packages the WAR with no jar files. Used for shared deployment

Fired Events:

o StatusFinal - When the WAR file has been created

The war command will create a web application archive (WAR) file using the application

name and version number. By default a war file deployable to the production environment will be created, but the environment can be specified using Grails standard convention:

grails test war

grails dev war

grails prod war

grails war /foo/bar/mywar.war

grails war --nojars

You can also specify a custom environment:

grails -Dgrails.env=UAT war

Once the WAR has been created you should follow the instructions that relate to the container which you are using to complete deployment

Page 52: grails command main

Constraints Usage

Constraints provide Grails with a declarative DSL for defining validation rules, schema generation and CRUD generation meta data. An example of a set of constraints applied to a domain class are as follows:

class User {

...

static constraints = {

login(size:5..15, blank:false, unique:true)

password(size:5..15, blank:false)

email(email:true, blank:false)

age(min:18, nullable:false)

}

}

Refer to the user guide topic on Constraints for more information.

Global Constraints

You can apply constraints globally inside grails-app/conf/Config.groovy as follows:

grails.gorm.default.constraints = {

'*'(nullable:true, size:1..20)

}

The wildcard signifies that the constraints apply to all properties. You can also define shared constraints:

grails.gorm.default.constraints = {

myShared(nullable:true, size:1..20)

}

That can be reused in your class:

class User {

...

static constraints = {

login(shared:"myShared")

}

Page 53: grails command main

}

Quick reference

Constraint Description Example

blank To validate that a String value is not blank login(blank:false)

creditCard To validate that a String value is a valid credit

card number cardNumber(creditCard:true)

email To validate that a String value is a valid email

address. homeEmail(email:true)

inList To validate that a value is within a range or

collection of constrained values. name(inList:"Joe", "Fred",

"Bob" )

matches To validate that a String value matches a given

regular expression. login(matches:”a-zA-Z+”)

max Ensures a value does not exceed the given

maximum value.

age(max:new

Date()) price(max:999F)

maxSize Ensures a value’s size does not exceed the

given maximum value. children(maxSize:25)

min Ensures a value does not fall below the given

minimum value.

age(min:new

Date()) price(min:0F)

minSize Ensures a value’s size does not fall below the

given minimum value. children(minSize:25)

notEqual Ensures that a property is not equal to the

specified value login(notEqual:”Bob”)

nullable Allows a property to be set to null - defaults

to false for domain class properties. age(nullable:true)

range

Uses a Groovy range to ensure that a

property’s value occurs within a specified

range

age(range:18..65)

Page 54: grails command main

scale

Set to the desired scale for floating point

numbers (i.e., the number of digits to the right

of the decimal point).

salary(scale:2)

size Uses a Groovy range to restrict the size of a

collection or number or the length of a String. children(size:5..15)

unique Constraints a property as unique at the

database level login(unique:true)

url To validate that a String value is a valid URL. homePage(url:true)

validator Adds custom validation to a field. See documentation

Scaffolding

Some constraints affect (and only affect) the scaffolding. It's not usually good practice to include UI information in your domain, but it's a great convenience if you use Grails' scaffolding extensively.

Constraint Description

display Boolean that determines whether the property is displayed in the scaffolding views or

not. If true (the default), the property is displayed.

editable Boolean that determines whether the property can be edited from the scaffolding views.

If false, the associated form fields are displayed in read-only mode.

format Specify a display format for types that accept one, such as dates. For example, 'yyyy-

MM-dd'.

password Boolean indicating whether this is property should be displayed with a password field or

not. Only works on fields that would normally be displayed with a text field.

widget Controls what widget is used to display the property. For example, 'textArea' will force

the scaffolding to use a <textArea> tag.

Page 55: grails command main

BLANK

Purpose

To validate that a String value is not blank

Examples

login(blank:false)

Description

Set to false if a string value cannot be blank

Error Code: className.propertyName.blank

Page 56: grails command main

CREDIT CARD

Purpose

To validate that a String value is a valid credit card number

Examples

cardNumber(creditCard:true)

Description

Set to true if a string should be a credit card number. Internally uses

the org.apache.commons.validator.CreditCardValidator class.

Error Code: className.propertyName.creditCard.invalid

Page 57: grails command main

EMAIL

Purpose

To validate that a String value is a valid email address.

Examples

homeEmail(email:true)

Description

Set to true if a string value is an email address. Internally uses

the org.apache.commons.validator.EmailValidator class.

Error Code: className.propertyName.email.invalid

Page 58: grails command main

INLIST

Purpose

To validate that a value is within a range or collection of constrained values.

Examples

name(inList:["Joe", "Fred", "Bob"] )

Description

Constrains a value so that it must be contained within the given list. This constraint influences schema generation.

Error Code: className.propertyName.not.inList

Page 59: grails command main

MATCHES

Purpose

To validate that a String value matches a given regular expression.

Examples

login(matches:"[a-zA-Z]+")

Description

Applies a regular expression against a string value.

Error Code: className.propertyName.matches.invalid

Page 60: grails command main

MAX

Purpose

Ensures a value does not exceed the given maximum value.

Examples

age(max:new Date())

price(max:999F)

Description

Sets the maximum value of a class that implements java.lang.Comparable. The same type needs to be used as the property itself. This constraint influences schema generation.

Error Code: className.propertyName.max.exceeded

Page 61: grails command main

MAX SIZE

Purpose

Ensures a value's size does not exceed the given maximum value.

Examples

children(maxSize:25)

Description

This constraint influences schema generation.

Error Code: className.propertyName.maxSize.exceeded

Page 62: grails command main

MIN

Purpose

Ensures a value does not fall below the given minimum value.

Examples

age(min:new Date())

price(min:0F)

Description

Sets the minimum value of a class that implements java.lang.Comparable. The same type needs to be used as the property itself. This constraint influences schema generation.

Error Code: className.propertyName.min.notmet

Page 63: grails command main

MINSIZE

Purpose

Ensures a value's size does not fall below the given minimum value.

Examples

children(minSize:25)

Description

Sets the minimum size of a collection or number property. This constraint influences schema generation.

Error Code: className.propertyName.minSize.notmet

Page 64: grails command main

NOT EQUAL

Purpose

Ensures that a property is not equal to the specified value

Examples

login(notEqual:"Bob")

Description

Error Code: className.propertyName.notEqual

Page 65: grails command main

NULLABLE

Purpose

Allows a property to be set to null. By default Grails does not allow null values for

properties.

Examples

age(nullable:true)

Description

Set to true if the property allows null values. This constraint influences schema

generation.

An empty form field will appear in the request parameters as an empty string, not as

null. Keep this in mind when setting domain fields directly from request parameters.

Error Code: className.propertyName.nullable

Page 66: grails command main

RANGE

Purpose

Uses a Groovy range to ensure that a property's value occurs within a specified range

Examples

age(range:18..65)

Description

Set to a Groovy range which can contain numbers in the form of an IntRange, dates or

any object that implements Comparable and provides next and previous methods for

navigation. This constraint influences schema generation.

Error

Code: className.propertyName.range.toosmall or className.propertyName.range.toobig

Page 67: grails command main

SCALE

Purpose

Set to the desired scale for floating point numbers (i.e., the number of digits to the right of the decimal point).

Examples

salary(scale:2)

Description

Set to the desired scale for floating point numbers (i.e., the number of digits to the right of the decimal point). This constraint is applicable for properties of the following

types: java.lang.Float,java.lang.Double, and java.math.BigDecimal (and its

subclasses). When validation is invoked, this constraint determines if the number includes more nonzero decimal places than the scale permits. If so, it automatically rounds the number to the maximum number of decimal places allowed by the scale. This constraint does not generate validation error messages.

This constraint influences schema generation.

Error Code: N/A

Page 68: grails command main

SIZE

Purpose

Uses a Groovy range to restrict the size of a collection or number or the length of a String.

Examples

children(size:5..15)

Description

Sets the size of a collection or number property or String length.

Currently this constraint cannot be used in addition to blank or nullable, a custom

validator may be added to perform this kind of constraints.

This constraint influences schema generation.

Error

Code: className.propertyName.size.toosmall or className.propertyName.size.toobig

Page 69: grails command main

UNIQUE

Purpose

Constraints a property as unique at the database level

Examples

login(unique:true)

Description

Set to true if the property must be unique (this is a persistent call and will query the database)

Be aware that it's possible (though uncommon in practice) for a uniqueness constraint validation to pass but a subsequent save of the data to fail due to a uniqueness constraint enforced at the database level. The only way to prevent this would be to use

the SERIALIZABLE transaction isolation level (bad for performance) or just be prepared

to get an exception to this effect at some point.

Scope of unique constraint can be specified by specifying the name of another property

of the same class, or list of such names. The semantics in these cases is: pair of constrained property value and scope property value must be unique (or combination of constrained property value and all scope property values must be unique).

Example:

group(unique:'department')

In the above example group name must be unique in one department but there might

be groups with same name in different departments.

Another example:

login(unique:['group','department'])

In this example login must be unique in group and department. There might be same

logins in different groups or different departments.

This constraint influences schema generation.

Error Code: className.propertyName.unique

Page 70: grails command main

URL

Purpose

To validate that a String value is a valid URL.

Examples

homePage(url:true)

Description

Set to true if a string value is a URL. Internally uses

the org.apache.commons.validator.UrlValidator class.

Error Code: className.propertyName.url.invalid

Page 71: grails command main

VALIDATOR

Purpose

Adds custom validation to a field.

Examples

even( validator: {

return (it % 2) == 0

})

password1( validator: {

val, obj ->

obj.properties['password2'] == val

})

magicNumber( validator:

someClosureWithTwoParameters)

// This one assumes you have an error message defined like:

// classname.propertyName.custom.error=My error shows arguments {3} and {4}

for value {0}

otherProperty( validator: { return ['custom.error', arg1, arg2] } )

// The following example does not use custom validation.

// A custom message may be defined in messages.properties:

// user.login.blank=Please enter a login

// which will be used instead of default.blank.message

class User {

String login

static constraints = {

login(blank:false)

}

}

// In the following example, custom validation is used:

// user.login.validator.invalid=Please enter a login

Page 72: grails command main

class User {

String login

static constraints = {

login(validator: {

return (it.length != 0)

})

}

}

// The following might define the error message as:

// user.login.invalid.bountyhunter=Invalid bounty hunter ({2}) tried to log

in. (Class name = {1}. Property name = {0})

class User {

String login

static constraints = {

login(validator: {

if (!it.startsWith('boba')) return ['invalid.bountyhunter']

})

}

}

Description

Set to a closure or block to use for custom validation. A single or no parameter block receives the value, a two-parameter block receives the value and object reference.

A three-parameter Closure receives the value, object reference and the errors object.

The closure can return:

o null or true to indicate that the value is valid

o false to indicate an invalid value and use the default message code

o a string to indicate the error code to append to the "classname.propertName." string used to resolve the error message. If a field specific message cannot be resolved, the error code itself will be resolved allowing for global error messages.

Page 73: grails command main

o a list containing a string as above, and then any number of arguments following it, which can be used as formatted message arguments indexed at 3 onwards.

See grails-app/i18n/message.properties to see how the default error message

codes use the arguments.

If the closure is a three-parameter closure the return value is ignored and the closure is expected to populate the errors object.

The closure also has access to the name of the field that the constraint applies to

via propertyName:

myField(validator: { val, obj -> return propertyName == "myField" })

Error Code: className.propertyName.validator.error

Page 74: grails command main

CONTROLLER USAGE

A controller fulfills the C in the Model View Controller (MVC) pattern and is responsible for handling web requests. In Grails a controller is a class that ends in the convention

"Controller" and lives in the grails-app/controllers directory. A controller can be

created with the create-controller command:

grails create-controller hello

Or via your favourite IDE or text editor.

class HelloController {

def world = {

render "Hello World!"

}

}

Each action in the controller is a callable block (for example the world action above)

that has access to a number of implicit variables and methods which are covered in this reference documentation.

Refer to the user guide topic on Controllers for more information.

Page 75: grails command main

ACTION NAME

Purpose

Returns the name of the currently executing action.

Examples

class BookController {

def list = {

log.info "Executing action $actionName"

render(view:actionName)

}

}

Description

Returns the name of the currently executing action which is dictated by the URL mappings

Page 76: grails command main

AFTER INTERCEPTOR

Purpose

Allows interception of actions after they have executed, but before the view has rendered at the controller level.

Examples

Using a block:

class BookController {

def afterInterceptor = { model ->

model.foo = "bar"

}

}

In the above example the first argument to block is model (a map of key value pairs passed to the view)

Using a map with a method reference:

class BookController {

def afterInterceptor = [action:this.&invokeMe, only:['list']]

def invokeMe(model) {

model.foo = "bar"

}

def list = {

[bookList:Book.list()]

}

}

In this example we use the map syntax to constraint the {{afterInterceptor}} to execute only for the {{list}} action.

Description

To define an interceptor that is executed after an action use

the afterInterceptor property:

def afterInterceptor = { model ->

println "Tracing action ${actionUri}"

}

The after interceptor takes the resulting model as an argument and can hence perform post manipulation of the model or response.

An afterInterceptor may also modify the Spring MVC ModelAndView object prior to

rendering. In this case, the above example becomes:

def afterInterceptor = { model, modelAndView ->

println "Current view is ${modelAndView.viewName}"

Page 77: grails command main

if(model.someVar) modelAndView.viewName =

"/mycontroller/someotherview"

println "View is now ${modelAndView.viewName}"

}

This allows the view to be changed based on the model returned by the current action.

Note that the modelAndView may be null if the action being intercepted called redirect or

render.

Page 78: grails command main

ALLOWED METHODS

Purpose

To limit access to controller actions based on the HTTP request method.

Examples

class PersonController {

// action1 may be invoked via a POST

// action2 has no restrictions

// action3 may be invoked via a POST or DELETE

static allowedMethods = [action1:'POST',

action3:['POST', 'DELETE']]

def action1 = { … }

def action2 = { … }

def action3 = { … }

}

Description

The request method may be inspected inside of a controller action and the application may respond however is appropriate. The code below is a way to prevent the delete action from being invoked using an HTTP-GET.

class PersonController {

def delete = {

if(request.method == 'GET') {

// redirect to the list action

redirect(action:list)

} else {

// the rest of the delete action goes here

}

}

}

Instead of redirecting to some other action the application may want to return a 405 (Method Not Allowed) error code like this:

class PersonController {

def delete = {

if(request.method == 'GET') {

response.sendError(405)

} else {

Page 79: grails command main

// the rest of the delete action goes here

}

}

}

A problem with inspecting the request method inside of the controller action is that this code ends up being repeated in a lot of actions within a controller, in many controllers in an application and in many applications. For specialized application specific handling of invalid requests this may make sense but for the general case the Grails framework provides a simple declarative syntax to help with this problem.

Grails provides a simple declarative syntax to help limit access to controller actions

based on the HTTP request method. The optional allowedMethods property may be

added to a controller to let the framework know which HTTP methods are allowed for controller actions. By default, all request methods are allowed for all controller actions.

The allowedMethods property only needs to be defined if the controller contains actions

that need to be restricted to certain request methods.

The allowedMethods property should be assigned a value that is a Map. The keys in the

map should be the names of actions that need to be restricted. The value associated with each of those keys may be either a String or a List of Strings. If the value is a String, that String represents the only request method that may be used to invoke that action. If the value is a List of Strings the List represents all of the request methods that may be used to invoke that action. If the specified restrictions are violated then a 405 will be returned in the response.

Page 80: grails command main

BEFORE INTERCEPTOR

Purpose

Allows the interception of an action before it is executed. A beforeInterceptor can

optionally halt execution of the action all together.

Examples

Simply tracing interceptor:

def beforeInterceptor = {

println "Tracing action ${actionUri}"

}

A security interceptor to implement login functionality:

def beforeInterceptor = [action:this.&auth,except:'login']

// defined as a regular method so its private

def auth() {

if(!session.user) {

redirect(action:'login')

return false

}

}

def login = {

// display login page

}

Description

The beforeInterceptor intercepts processing before the action is executed. If it

returns false then the action will not be executed. The interceptor can be defined for

all actions in a controller as follows:

def beforeInterceptor = {

println "Tracing action ${actionUri}"

}

The above is declared inside the body of the controller definition. It will be executed before all actions and does not interfere with processing. A common use case is however for authentication:

def beforeInterceptor = [action:this.&auth,except:'login']

// defined as a regular method so its private

def auth() {

if(!session.user) {

redirect(action:'login')

return false

}

}

def login = {

// display login page

}

Page 81: grails command main

The above code defines a method called 'auth'. A method is used so that it is not exposed as an action to the outside world (i.e. it is private). The 'beforeInterceptor' then defines an interceptor that is used on all actions 'except' the login action and is told to execute the 'auth' method. The 'auth' method is referenced using Groovy's method pointer syntax, within the method itself it detects whether there is a user in the session otherwise it redirects to the login action and returns false, instruction the intercepted action not to be processed.

Page 82: grails command main

BIND DATA

Purpose

Allows fine grained control of binding request parameters from strings onto objects and the necessary types (data binding).

Examples

// binds request parameters to a target object

bindData(target, params)

// exclude firstName and lastName (since 0.4)

bindData(target, params, ['firstName', 'lastName'])

// only use parameters starting with "author." e.g. author.email (since

0.5.5)

bindData(target, this.params, "author")

bindData(target, this.params, ['firstName', 'lastName'], "author")

// using inclusive map

bindData(target, this.params, [include:['firstName', 'lastName']],

"author")

// using exclusive map

bindData(target, this.params, [exclude:['firstName', 'lastName']],

"author")

Description

Usage: bindData(target, params, excludes, prefix)

Arguments:

o target - The target object to bind to

o params - The source parameters, can be either a map or the params object

o excludes - The parameters to exclude

o prefix - A string representing a prefix to use to filter parameters. A prefix separator of

"." is assumed

The underlying implementation uses Spring's Data Binding framework. If the target is a

domain class type conversion errors are stored in the errors property of the domain

class.

Refer to the section on Data Binding in the user guide for more information.

Page 83: grails command main

CHAIN

Purpose

Uses flash storage to implicitly retain the model following an HTTP redirect from one action to another.

Examples

chain(action:"details",model:book:new Book(title:'The Shawshank

Redemption'))

Description

Usage: chain(controller*, action, id*, model, params*)

Arguments:

o uri - The full uri to redirect to (example /book/list, book/show/2)

o controller (optional) - The controller to redirect to, defaults to the current controller if

not specified

o action - The action to redirect to, either a string name or a reference to an action

within the current controller

o id (optional) - The id to use in redirection

o model - The model to chain to the next action

o params (optional) - Parameters to pass to the action chained to.

The chain method stores the passed model in flash scope and then performs an HTTP redirect. The model is then restored for the next request. The model that will eventually be passed to the view will be created by starting with the model that was passed to the chain method and then adding to that all of the data that is in the model returned by the next action, which may replace some of the data that was in the model originally passed to the chain method. As an example: def one = {

chain action: 'two', model: [name: 'Tony', town: 'Birmingham']

}

def two = {

[name: 'Anthony', country: 'England']

}

If a request is sent to the one action, that action chains to the two action which returns

a model. The model that is passed to the view would contain [name: 'Anthony', town: 'Birmingham', country: 'England']

The chain method requires either a URI to redirect to or a controller/action/id name combination

Page 84: grails command main

CONTROLLER NAME

Purpose

Returns the name of the currently executing controller.

Examples

class BookController {

def list = {

log.info "Executing within controller $controllerName"

render(view:actionName)

}

}

Description

Returns the name of the currently executing controller which is dictated by the URL mappings

Page 85: grails command main

DEFAULT ACTION

Purpose

Allows you to explicitly specify the default action that should be executed if no action is specified in the URI.

Examples

class BookController {

static defaultAction = "list"

def list = {

[books:Book.list()]

}

}

Page 86: grails command main

FLASH

Purpose

A temporary storage map that stores objects within the session for the next request and the next request only, automatically clearing our the objects held there after the next request completes.

Examples

class BookController {

def index = {

flash.message = "Welcome!"

redirect(action:home)

}

def home = {}

}

Description

The flash object is essentially a map (a hash) which you can use to store key value pairs. These values are transparently stored inside the session and then cleared at the end of the next request.

This pattern allows you to use HTTP redirects (which is useful for redirect after post and retain values that can retrieved from the flash object.

Page 87: grails command main

FORWARD

Purpose

Forwards a request from one controller to the next without issuing an HTTP redirect.

Examples

forward(action:"show")

forward(controller:"book",action:"list")

forward(action:"show",id:4, params:[author:"Stephen King"])

forward(controller: "book", action: "show")

Description

Forwards the current action to another action, optionally passing parameters and/or errors.

Parameters

o controller - The controller to redirect to, defaults to the current controller if not

specified

o action - The action to redirect to, either a string name or a reference to an action

within the current controller

o id - The id to use in redirection

o params - Parameters to pass to the action redirected to.

Page 88: grails command main

GRAILS APPLICATION

Purpose

An instance of the org.codehaus.groovy.grails.commons.GrailsApplication class.

Examples

class BookController {

def list = {

def bookClass =

grailsApplication.classLoader.loadClass("Book")

[book:bookClass.newInstance()]

}

}

Description

The GrailsApplication class provides information about the conventions within Grails

and access to metadata, config and the ClassLoader

Page 89: grails command main

PARAMS

Purpose

A mutable multi-dimensional map (hash) of request (CGI) parameters.

Examples

To obtain a request parameter called id:

class BookController {

def show {

def book = Book.get(params.id)

}

}

To perform data binding (see Data Binding in the user guide):

def save = {

def book = new Book(params) // bind request parameters onto

properties of book

}

Description

The standard Servlet API provides access to parameters via

the HttpServletRequest object. Although Grails provides the same capability through

the request object, it goes a bit further by providing a mutable map of request

parameters called params.

The params object can be indexed into via de-refrencing so given the

URL /hello?foo=bar you can obtain the value of foo as follows:

println params.foo

The params object can also be used to bind request parameters onto the properties of a domain class using either the constructor or the properties property:

def book = new Book(params)

book = Book.get(1)

book.properties = params

For further reading see Data Binding in the user guide.

Page 90: grails command main

REDIRECT

Purpose

To redirect flow from one action to the next using an HTTP redirect.

Examples

redirect(uri:"book/list")

redirect(url:"http://www.blogjava.net/BlueSUN")

redirect(action:"show")

redirect(controller:"book",action:"list")

redirect(action:"show",id:4, params:[author:"Stephen King"])

redirect(controller: "book", action: "show", fragment: "profile")

Description

Redirects the current action to another action, optionally passing parameters and/or errors.

Parameters

o uri - The full uri to redirect to (example /book/list, book/show/2)

o url - The absolute url to redirect to (example: "http://www.blogjava.net/BlueSUN")

o controller - The controller to redirect to, defaults to the current controller if not

specified

o action - The action to redirect to, either a string name or a reference to an action

within the current controller

o id - The id to use in redirection

o params - Parameters to pass to the action redirected to. You can include 'id' in this map,

but if the 'id' argument is also provided that takes precedence.

o fragment - A URI fragment to append to the end of the target URI, as in

".../show#profile". The value for this parameter should not include the '#'.

Page 91: grails command main

RENDER

Purpose

To render different forms of responses from simple text responses, to view and templates.

Examples

// renders text to response

render "some text"

// renders text for a specified content-type/encoding

render(text:"<xml>some xml</xml>",contentType:"text/xml",encoding:"UTF-8")

// render a template to the response for the specified model

render(template:"book",model:[book:new Book(title:'The

Shining',author:'Stephen King')])

// render each item in the collection using the specified template

render(template:"book",collection:[b1, b2, b3])

// render a template to the response for the specified bean

render(template:"book",bean:new Book(title:'The Shining',author:'Stephen

King'))

// render the view with the specified model

render(view:"viewName",model:[book:new Book(author:'Stephen King')])

// render the view with the controller as the model

render(view:"viewName")

// render some markup to the response

render {

div(id:"myDiv", "some text inside the div")

}

// render some XML markup to the response

render(contentType:"text/xml") {

books {

Page 92: grails command main

for(b in books) {

book(title:b.title,author:b.author)

}

}

}

// render a JSON ( http://www.json.org ) response with the builder

attribute:

render(contentType:"text/json") {

book(title:b.title,author:b.author)

}

// render with status code

render(status: 503, text: 'Failed to update book ${b.id}')

// Automatic marshalling of XML and JSON

import grails.converters.*

render Book.list(params) as JSON

render Book.get(params.id) as XML

Description

A multi-purpose method for rendering responses to the client which is best illustrated with a few examples! Warning, as of Grails 0.5, this method does not always support multiple parameters. For example, if you specify both collection and model, the model parameter will be ignored. Parameters

Parameters:

o text (optional) - The text to render

o builder (optional) - The builder to use when rendering markup

o view (optional) - The view to delegate the rendering to

o template (optional) - The template to render

o var (optional) - The name of the variable to be passed into a template, defaults to the

groovy default argument 'it' if not specified

o bean (optional) - The beanto use in rendering

o model (optional) - The model to use in rendering

o collection (optional) - For rendering a template against each item in a collection

o contentType (optional) - The contentType of the response

Page 93: grails command main

o encoding (optional) - The encoding of the response

o converter (as single non-named first parameter) - A Converter that should be rendered

as Response

o plugin (optional) - The plug-in to look for the template in

o status (optional) - The HTTP status code to use

Page 94: grails command main

REQUEST

Purpose

The request object is an instance of the Servlet API's HttpServletRequest class.

Examples

class BookController {

def list = {

log.info "User agent: " + request.getHeader("User-Agent")

render(view:actionName)

}

}

Description

The HttpServletRequest class is useful for, amongst other things, obtaining request headers, storing request scoped attributes and establishing information about the client. Refer to the Servlet API's javadocs for further information.

The additional methods added to the request object are documented in the Grails Servlet API reference guide

Page 95: grails command main

RESPONSE

Purpose

The response object is an instance of the Servlet API's HttpServletResponse class.

Examples

class BookController {

def downloadFile = {

byte[] bytes = // read bytes

response.outputStream << bytes

}

}

Description

The Servlet API's HttpServletResponse class can be used within Grails to perform all

typical activities such as writing out binary data, writing directly to the response and sending error response codes to name but a few. Refer to the documentation on the HttpServletResponse class in the Servlet API for more information.

The additional methods added to the response object are documented in the Grails Servlet API reference guide

Page 96: grails command main

SESSION

Purpose

The session object is an instance of the Servlet API's HttpSession class.

Examples

class UserController {

def logout = {

log.info "User agent: " + request.getHeader("User-Agent")

session.invalidate()

redirect(action:"login")

}

def login = {

}

}

Description

The HttpSession class is useful for associated session data with a client.

The additional methods added to the session object are documented in the Grails

Servlet API reference guide

Page 97: grails command main

SERVLET CONTEXT

Purpose

The servletContext object is an instance of the Servlet API's ServletContext class.

Examples

class BookController {

def doSomething = {

def input

try {

input = servletContext.getResourceAsStream("/WEB-

INF/myscript.groovy")

def result = new GroovyShell().evaluate(input.text)

render result

}

finally {

input.close()

}

}

}

Description

The Servlet API's ServletContext is useful for, amongst other things, storing global application attributes, reading local server resources and establishing information about the servlet container.

Grails adds additional methods to the standard Servlet API's servletContext object. See

link for details.

Page 98: grails command main

WITH FORM

Purpose

Used to handle duplicate form submissions.

Examples

withForm {

// good request

}.invalidToken {

// bad request

}

Description

The withForm method requires the use of the useToken attribute in a form

<g:form useToken="true" ...>

Then in your controller code you can use the withForm method to handle valid and

invalid requests:

withForm {

// good request

}.invalidToken {

// bad request

}

See Handling Duplicate Form Submissions for more information.

Page 99: grails command main

WITH FORMAT

Purpose

Used to execute different responses based on the incoming request Accept header,

format parameter or URI extension. See content negotiation for more information.

Examples

import grails.converters.*

class BookController {

def books

def list = {

this.books = Book.list()

withFormat {

html bookList:books

js { render "alert('hello')" }

xml { render books as XML }

}

}

}

Description

The withFormat method takes a block within the scope of which you can execute

different methods whose names match the content type you want to respond to. For example:

withFormat {

html bookList:books

js { render "alert('hello')" }

xml { render books as XML }

}

Here we invoke three methods called html, js and xml that use mime type names

configured in grails-app/conf/Config.groovy (See content negotiation for more

information). The call to htmlaccepts a model (a map) which is passed on to the view.

Grails will first search for a view called grails-app/views/book/list.html.gsp and if

that is not found fallback to grails-app/views/book/list.gsp.

Page 100: grails command main

Note that the order of the types is significant if either the request format is "all" or more than one content type has the same "q" rating in the accept header. In the former case, the first type handler in the block is executed ("html" in the short example above). The latter case is more confusing because it only holds if there is more than one content type with the highest "q" rating for which you have a type handler and you have more than one type handler matching that "q" rating. For example, say the request has "text/html" and "application/xml" with a "q" rating of 1.0, then this code:

withFormat {

xml { … }

html { … }

}

will use the "xml" type handler for the request.

If you require the model to be lazily executed you can pass a closure or block instead of a map:

withFormat {

html { [bookList:Book.list()] }

}

The block will only get executed if the html format is matched.

Page 101: grails command main

DATABASE MAPPING USAGE

Domain classes in Grails by default dictate the way they are mapped to the database using sensible defaults. You can customize these with the ORM Mapping DSL. For

example create a Bookdomain:

grails create-domain-class Book

And then you can use the mapping block to customize the ORM mapping behavior.

class Book {

String title

Date releaseDate

Author author

static mapping = {

table "books"

author column:"auth_id"

}

}

Refer to the user guide section on ORM Mapping for more information.

Global Database Mapping

You can configure mapping globally in grails-app/conf/Config.groovy as follows:

grails.gorm.default.mapping = {

cache true

id generator:'sequence'

'user-type'( type:org.hibernate.type.YesNoType, class:Boolean )

}

Page 102: grails command main

AUTO TIMESTAMP

Purpose

Disables auto timestamping when set to false

Examples class Book {

static mapping = {

autoTimestamp false

}

}

Description

Usage: autoTimestamp(boolean)

By default when you have properties called dateCreated and lastUpdated in a domain

class, Grails will automatically maintain the state of these in the database. If you don't

want this to happen then you can set autoTimestamp to false:

static mapping = {

autoTimestamp false

}

Page 103: grails command main

BATCH SIZE

Purpose

Customizes how many results are fetching during lazy loading.

Examples class Book {

static mapping = {

batchSize 10

}

}

Description

Usage: batchSize(integer)

Given a lazy association where an Author has many Books, GORM will perform one

query to get a hold of the Author and then an additional query for each

associated Book. This is what is known as the N+1 problem and can often be worked

around by using a join query. However, joins can be expensive.

Batch fetching is an optimization of lazy loading so that if, for example, you set

a batchSize of 10 and you have an Author that has written 30 books, instead of 31

queries you get 4 (1 to fetch the Author and then three batches of 10):

static mapping = {

batchSize 10

}

You can also configure batchSize on a per association basis:

class Author {

static hasMany = [books:Book]

static mapping = {

books batchSize: 10

}

}

Page 104: grails command main

CACHE

Purpose

Enables the configuration of the Hibernate second-level cache.

Examples class Book {

static mapping = {

cache true

}

}

Description

Usage: cache(boolean/string/map)

Arguments:

o usage - The cache usage. Can be read-only, read-write, nonstrict-read-

write or transactional

o include (optional) - Whether to include non-lazy associations. Can be all or non-lazy

In order to take advantage of the Hibernate second-level cache you explicitly need to enable caching per domain class. For example:

static mapping = {

cache true

}

This will configure the domain class to use a 'read-write' cache, but you can configure whatever cache policy is appropriate:

static mapping = {

cache 'transactional'

}

Or static mapping = {

cache usage:'read-only', include:'non-lazy'

}

You can also configure the cache policy on a per association basis:

class Author {

static hasMany = [books:Book]

static mapping = {

books cache: true // or 'read-write' etc.

}

}

For more information see the section on Caching in the user guide.

Page 105: grails command main

CASCADE

Purpose

Configures the cascading behavior of an association.

Examples class Author {

static hasMany = [books:Book]

static mapping = {

books cascade:'all-delete-orphan'

}

}

Description

Usage: association_name(cascade:string)

Arguments:

o cascade - The cascading behavior to define. Can be one or more (comma-separated)

of all, merge, save-update, delete, lock, refresh, evict, replicate or all-delete-

orphan (one-to-many associations only).

By default GORM configures a cascading policy of "all" in the case where one entity "belongs to" another. For example:

class Book {

static belongsTo = [author:Author]

}

class Author {

static hasMany = [books:Book]

}

Here all persistence operations will cascade from the Author domain to

the Book domain. So when a Author is deleted so will all his books.

If the association doesn't define an owner (a "belong to" relationship):

class Book {

}

class Author {

static hasMany = [books:Book]

}

Then GORM uses a cascading policy of "save-update" by default. So if an Author is

deleted the Book domains associated with the Author won't be deleted. If you wish to

customize this behavior you can use the cascade argument on an association: class Author {

static hasMany = [books:Book]

static mapping = {

books cascade:'all-delete-orphan'

}

}

Here a Book will also be deleted if it is removed (orphaned) from the books association.

Page 106: grails command main

COLUMN

Purpose

Customizes a column definition

Examples static mapping = {

currency column: "currency", sqlType: "char", length: 3

}

Description

Usage: property_name(map)

Arguments:

o column - The name of the column as a String

o sqlType (optional) - The underlying SQL type

o enumType (optional) - The enum type in for type-safe Enum properties.

Either ordinal or string.

o index (optional) - The index name

o unique (optional) - Whether it is unique or not

o length (optional) - The length of the column

o precision (optional) - The precision of the column

o scale (optional) - The scale of the column

By default GORM uses the property name and type to automatically work out a how to map a particular domain property onto the database. For example a String property is typically mapped onto a varchar(255) column. You can customize these using a method that matches the property name and passing the necessary column configuration arguments:

static mapping = {

currency column: "currency", sqlType: "char", length: 3

}

If you are using a Hibernate type that requires multiple column definitions you can use

the column method to define each column:

static mapping = {

amount type: MonetaryUserType, {

column name: "value"

column name: "currency", sqlType: "char", length: 3

}

}

Page 107: grails command main

DISCRIMINATOR

Purpose

Customizes the discriminator value used in table-per-subclass inheritance mapping.

Examples class Content {

}

class PodCast extends Content {

static mapping = {

discriminator "audio"

}

}

Description

Usage: discriminator(string/map)

Arguments:

o column (optional) - The column name to store the discriminator

o value - The value to use for the discriminator

o formula (optional) - an SQL expression that is executed to evaluate the type of class.

Use this or column but not both

o type (optional defaults to string) - the Hibernate type, used for the where clause

condition to know if it needs to wrap it with ' or not

By default when mapping inheritance Grails uses a single-table model so that all subclasses share the same table. A discriminator column is then used to help Grails tell what type a particular row is. By default the class name is stored as the value of this

column. You can use the discriminator method to customize the value stored:

class Content {

}

class PodCast extends Content {

static mapping = {

discriminator "audio"

}

}

You can also customize the discriminator column name:

class Content {

static mapping = {

discriminator column:"content_type"

}

}

class PodCast extends Content {

static mapping = {

discriminator value: "audio"

}

}

Page 108: grails command main

Or you can use a formula:

class Content {

static mapping = {

discriminator value: "1", formula="case when CLASS_TYPE in ('a',

'b', 'c') then 0 else 1 end", type="integer"

}

}

class PodCast extends Content{

static mapping = {

discriminator value: "0"

}

}

Page 109: grails command main

DYNAMIC INSERT

Purpose

Whether to dynamically build INSERT queries

Examples class Book {

static mapping = {

dynamicInsert true

}

}

Description

Usage: dynamicInsert(boolean)

By default Hibernate will build all queries at start-up time and cache them, which represents a significant performance gain as queries don't have to be dynamically generated at runtime. However, there are certain circumstances where dynamic queries are useful.

For example if you were using custom UserType to hash passwords, every time an

UPDATE occurred, the password would get re-hashed. The dynamicInsert method

allows you to turn of the dynamic creation of queries that uses only the properties that are needed to perform the insert.

Page 110: grails command main

DYNAMIC UPDATE

Purpose

Whether to dynamically build UPDATE queries

Examples class Book {

static mapping = {

dynamicUpdate true

}

}

Description

Usage: dynamicUpdate(boolean)

By default Hibernate will build all queries at start-up time and cache them, which represents a significant performance gain as queries don't have to be dynamically generated at runtime. However, there are certain circumstances where dynamic queries are useful.

For example if you were using custom UserType to hash passwords, every time an

UPDATE occurred, the password would get re-hashed. The dynamicUpdate method

allows you to turn of the dynamic creation of queries that uses only the properties that are needed to perform the update.

Page 111: grails command main

FETCH

Purpose

Configures the fetching behavior of an association.

Examples class Author {

static hasMany = [books:Book]

static mapping = {

books fetch:'join'

}

}

Description

Usage: association_name(fetch:string)

Arguments:

o fetchStrategy - The fetching strategy to use. Either join or select.

By default GORM assumes fetching of associations is done using a SELECT when the

association is accessed. If you prefer the association is fetched eagerly at the same time as object then you can override the fetch behavior:

class Author {

static hasMany = [books:Book]

static mapping = {

books fetch:'join'

}

}

Here the books association will be fetching using a join at the same time a particular

author is looked up such as:

def author = Author.get(1)

Note that excessive use joins can be a performance bottleneck. See the section on Eager vs Lazing Fetching in the user guide.

Page 112: grails command main

ID

Purpose

Customizes the way to identifier for a domain class is generated

Examples class Book {

static mapping = {

id generator:'hilo',

params:[table:'hi_value',column:'next_value',max_lo:100]

}

}

Description

Usage: id(map)

Arguments:

o generator (optional) - The name of the generator to use. Can

be increment, identity, sequence, hilo, seqhilo, uuid, guid, native, assigned, sel

ect, foreign or sequence-identity. SeeHibernate reference documentation for more

information.

o composite (optional) - Takes a list of property names to use that form the composite

identifier

o name (optional) - The property name to use as the identifier

o params (optional) - Any parameters to pass to the defined identity generator

o column (optional) - The column name to map the identifier to. The

remaining column definition properties are also available.

By default GORM uses the native strategy to generate a database identifier for each

entity. You can alter this with the id methods generator argument:

static mapping = {

id generator:'hilo',

params:[table:'hi_value',column:'next_value',max_lo:100]

}

You can also use the same method to define a composite identifier:

static mapping = {

id composite:['title', 'author']

}

Or change the name of the property that defines the identifier:

static mapping = {

id name:'title'

}

You can also alter the column definition:

static mapping = {

id column:'book_id', type:'integer'

}

See the section on Custom Database Identity in the user guide for more information.

Page 113: grails command main

INDEX COLUMN

Purpose

Customizes the index column definition of an indexed collection such as a List or Map

Examples class Neo {

static hasMany = [matrix:Integer]

static mapping = {

matrix indexColumn:[name:"the_matrix", type:Integer]

}

}

def neo = new Neo()

neo.matrix = [ (1): 30,

(2): 42,

(3): 23 ]

neo.save(flush:true)

Description

Usage: association_name(indexColumn:map)

Arguments:

o name - The name of the column as a String

o type (optional) - The Hibernate type.

o sqlType (optional) - The underlying SQL type

o enumType (optional) - The enum type in for type-safe Enum properties.

Either ordinal or string.

o index (optional) - The index name

o unique (optional) - Whether it is unique or not

o length (optional) - The length of the column

o precision (optional) - The precision of the column

o scale (optional) - The scale of the column

By default when mapping an indexed collection such as a Map or List the index is

stored in a column called association_name_idx which is an integer type in the case

of lists and a String in the case of maps. You can alter how the index column is mapped

using the indexColumn argument:

static mapping = {

matrix indexColumn:[name:"the_matrix", type:Integer]

}

Page 114: grails command main

INSERTABLE

Purpose

Determines whether a property's database column is set when a new instance is persisted.

Examples class Book {

String title

static belongsTo = [author: Author]

static mapping = {

author insertable: false

author updateable: false

}

}

Description

Usage: association_name(insertable: boolean)

Useful in general where you don't want to set an initial value (or include the column in

the generated SQL) during a save().

In particular this is useful for one-to-many relationships. For example when you store the foreign key in the 'child' table, it's often efficient to save the child using only the foreign key of the parent. You do this by setting the parent object (and the parent foreign key) in the 'child' entity. Setting the attributes insertable:false and updateable:false for the 'belongsTo' parent object allows you to insert and update using only the foreign key.

static mapping = {

author insertable: false

}

Page 115: grails command main

JOIN TABLE

Purpose

Customizes the join table used for undirectional one-to-many, many-to-many and primitive collection types.

Examples

Basic collection type:

class Book {

static hasMany = [chapterPageCounts:Integer]

static mapping = {

chapterPageCounts indexColumn:[name:"chapter_number",

type:Integer],

joinTable:[column:"page_count"]

}

Enum collection types:

enum VehicleStatus { OFF, IDLING, ACCELERATING, DECELERATING }

class Truck {

static hasMany = [states:VehicleStatus]

static mapping = {

states joinTable:[name:'VEHICLE_STATUS_LOG', key:'TRUCK_ID',

column:'STATUS']

}

}

Many-to-many:

class Book {

String title

static belongsTo = Author

static hasMany = [authors:Author]

static mapping = {

authors joinTable:[name:"mm_author_books", key:'mm_book_id' ]

}

}

class Author {

String name

static hasMany = [books:Book]

static mapping = {

books joinTable:[name:"mm_author_books", key:'mm_author_id']

}

}

Unidirectional One-to-many:

class Employee {

static hasMany = [projects: Project]

static mapping = {

Page 116: grails command main

projects joinTable: [name: 'EMP_PROJ', column: 'PROJECT_ID', key:

'EMPLOYEE_ID']

}

}

class Project { }

Description

Usage: association_name(joinTable:map)

Arguments:

o name - The table name

o key (optional) - The foreign key

o column (optional) - The inverse column

GORM has various strategies for mapping association types. Some of them, such as basic collection types and many-to-many associations, require the use of a join table.

You can customize how this join table is created using the joinTable argument.

Page 117: grails command main

LAZY

Purpose

Configures whether to use lazy proxies for one-to-one and many-to-one associations.

Examples class Book {

static belongsTo = [author:Author]

static mapping = {

author lazy:false

}

}

Description

Usage: association_name(lazy:boolean)

By default GORM single-ended associations are lazy in that when you load a domain instance an associated domain is not loaded until accessed. Hibernate creates a dynamic proxy by automatically subclassing a domain instance and proxying all methods and property access.

This can have some strange side effects (see this page on proxies on the Hibernate site) particularly in relation to inheritance. You can tell Hibernate not use proxies for single-

ended associations by using the lazy argument:

static mapping = {

author lazy:false

}

See the section on Eager vs Lazing Fetching in the user guide.

Page 118: grails command main

ORDER

Purpose

Customizes the default sort order of query results.

Examples class Book {

static mapping = {

order "desc"

}

}

Description

Usage: order(string)

Arguments:

o direction - Either "desc" or "asc" for descending and ascending respectively.

By defaults results are sorted in ascending order, with the order method you can alter

results to be sorted in descending order. See also the sort method.

Page 119: grails command main

SORT

Purpose

Customizes the default property to sort by for query results.

Examples class Book {

static mapping = {

sort "releaseDate"

}

}

Description

Usage: sort(string/map)

By default results are sorted by creation date, you can of course order these in a query:

def results = Book.list(sort:"title")

However, you can also configure the default sort property:

static mapping = {

sort "title"

}

In which case the sort argument is no longer needed. You can also control the sort

order:

static mapping = {

sort title:"desc"

}

Page 120: grails command main

TABLE

Purpose

Customizes the name of the table to map to

Examples class Book {

static mapping = {

table "book_catalog"

}

}

Description

Usage: table(string/map)

Arguments:

o name - The table name

o schema (optional) - The table schema

o catalog (optional) - The table catalog

By default the table that Grails maps a domain class is based on the class name. Grails will take a class name and convert Java style camel case names into underscores. So for

exampleProductReview will become product_review. You can change this with

the table method:

static mapping = {

table "book_catalog"

}

You can also specify a schema and catalog as follows:

static mapping = {

table name:"book_catalog", schema:"dbo", catalog:"CRM"

}

Page 121: grails command main

TYPE

Purpose

Configures the Hibernate type for a particular property.

Examples

Changing to a text type (CLOB or TEXT depending on database dialect).

class Book {

String title

static mapping = {

title type:"text"

}

}

User types with multiple columns:

class Book {

MonetaryAmount amount

static mapping = {

amount type: MonetaryUserType, {

column name: "value"

column name: "currency", sqlType: "char", length: 3

}

}

}

Description

Usage: association_name(type:string/class)

Hibernate will attempt to automatically select the appropriate type based from a

properties java.lang.Class. However, this choice is not always appropriate. For

example String values are by default mapped to varchar(255) columns. If you want to

store larger String values you can use a text type instead:

static mapping = {

title type:"text"

}

Hibernate also has the concept of custom UserType implementations. In this case you

need to specify the UserType class. If the UserType maps to multiple columns you may

need to specify mapping for each column:

static mapping = {

amount type: MonetaryUserType, {

column name: "value"

column name: "currency", sqlType: "char", length: 3

}

}

Page 122: grails command main

UPDATEABLE

Purpose

Determines whether a property's database column is updated when persistent instances are updated.

Examples class Book {

String title

static belongsTo = [author: Author]

static mapping = {

author insertable: false

author updateable: false

}

}

Description

Usage: association_name(updateable: boolean)

Useful in general where you don't want to update a value (or include the column in the

generated SQL) during a save().

In particular this is useful for one-to-many relationships. For example when you store the foreign key in the 'child' table, it's often efficient to save the child using only the foreign key of the parent. You do this by setting the parent object (and the parent foreign key) in the 'child' entity. Setting the attributes insertable:false and updateable:false for the 'belongsTo' parent object allows you to insert and update using only the foreign key.

static mapping = {

author updateable: false

}

Page 123: grails command main

VERSION

Purpose

Used to disable optimistic locking or change the column that holds the version.

Examples class Book {

static mapping = {

version false

}

}

Description

Usage: version(string/boolean)

By default GORM is configured with optimistic locking enabled. You can disable

optimistic locking by calling the version method with an argument of false:

static mapping = {

version false

}

Alternatively if you simply want to change the column used to store the version you can pass the name of the column:

static mapping = {

version 'revision_number'

}

Page 124: grails command main

DOMAIN CLASS USAGE

A domain class fulfills the M in the Model View Controller (MVC) pattern and represents a persistent entity that is mapped onto an underlying database table. In Grails a domain

is a class that lives in the grails-app/domain directory. A domain class can be created

with the create-domain-class command:

grails create-domain-class Book

Or via your favourite IDE or text editor.

class Book {

String title

Date releaseDate

Author author

}

The class name, by default, is mapped to the table name in lower case and separated by underscores instead of camel case. Whilst each property maps to individual columns.

Refer to the user guide section on GORM for more information.

Page 125: grails command main

ADDTO*

Purpose

Adds a domain class relationship for one-to-many or many-to-many relationship, where the relationship is indicated by the property used as the suffix to the method.

Examples def fictBook = new Book(title:"IT")

def nonFictBook = new Book(title:"On Writing: A Memoir of the Craft")

def a = new Author(name:"Stephen King")

.addToFiction(fictBook) // 'fiction' is name of

relationship property

.addToNonFiction(nonFictBook) // 'nonFiction' is name of

relationship property

.save()

Description

The addTo* method is a dynamic method that uses an association to automatically add

instances to the association. It also automatically configures bi-directional relationship so that both sides o the relationship have been set.

The method expects an instance of the associated class:

def fictBook = new Book(title:"IT")

def nonFictBook = new Book(title:"On Writing: A Memoir of the Craft")

def a = new Author(name:"Stephen King")

.addToFiction(fictBook) // 'fiction' is name of

relationship property

.addToNonFiction(nonFictBook) // 'nonFiction' is name of

relationship property

.save()

Or a map, in which case it auto-instantiates an instance of the associated class:

def a = new Author(name:"Stephen King")

.addToFiction(title:"IT")

.addToNonFiction(title:"On Writing: A Memoir of the Craft")

.save()

Page 126: grails command main

ATTACH

Purpose

Attaches a detached domain instance to the Hibernate session bound to the current thread

Examples def b = Book.get(1)

b.title = "Blah"

b.save(flush:true)

b.discard()

if(!b.isAttached()) {

b.attach()

}

Description

Grails uses Hibernate which manages each persistent object in a persistence session. A new session is created per request and is closed at the end of the request. If an object is read from the session and placed into a web scope such as the HttpSession it is seen as detached, since the persistence session has been closed. You can use the attach() method to re-attach an existing persistent instance to the persistence session of the current request.

Page 127: grails command main

BELONGSTO

Purpose

Defines a "belongs to" relationship where the class specified by belongsTo assumes

ownership of the relationship. This has the effect of controlling how saves and deletes cascade. The exact behaviour depends on the type of relationship you have:

o Many-to-one/one-to-one: saves and deletes cascade from the owner to the dependant

(the class with the belongsTo).

o One-to-many: saves always cascade from the one side to the many side, but if the many

side has belongsTo, then deletes also cascade in that direction.

o Many-to-many: only saves cascade from the "owner" to the "dependant", not deletes.

Examples class Book {

String title

static belongsTo = [author:Author]

}

In this example the Book class specifies that it belongs to the Author class, hence when

an Author instance is deleted so are all the Book instances associated with the Author

Description

The belongsTo property serves to abstract the nature of the cascading behaviour in

Hibernate. If you want one class to belong to another but not have a back reference, then you can specify a class or a list of classes as the value:

class Book {

static belongsTo = Author

}

or:

class Book {

static belongsTo = [ Author, Library ]

}

Back references, i.e. properties linking back to the owner, can be added in one of two ways:

class Book {

Author author

static belongsTo = Author

} OR

class Book {

static belongsTo = [ author: Author ]

}

In the above examples, both techniques create a property called author of type Author.

Also, the map property can specify multiple properties and types if the class belongs to more than one owner.

The belongsTo property is simple and means you don't have to worry about the

Hibernate cascading strategies, but if you need more control over cascading you can take advantage of theORM DSL. This allows fine grained control of cascading updates and deletes.

Page 128: grails command main

CLEAR ERRORS

Purpose

Clear the list of errors on a domain class. This may be useful if a domain class contains errors because of binding problems or validation problems. The errors may be corrected programatically. Validation may continue to fail unless the errors are cleared.

Examples def b = new Book(title:"The Shining")

b.validate()

if(b.hasErrors()) {

// clear the list of errors

b.clearErrors()

// fix the validation issues

b.author = "Stephen King"

// re-validate

b.validate()

}

Page 129: grails command main

CONSTRAINTS

Purpose

Allows the definition of declarative validation constraints. See Validation in the user guide.

Examples class Book {

String title

Author author

static constraints = {

title(blank:false, nullable:false, size:5..150)

author(nullable:false)

}

}

Description

Constraints are defined using the declarative constraints DSL as described in the Validation section of the user guide. Once evaluated validation can be applied through the use of the validatemethod:

def b = new Book()

assert !b.validate()

A list of ConstrainedProperty instances applied against the domain class by

the constraints property is available at runtime:

b.constraints.each {

println it.name

println it.maxSize

}

Page 130: grails command main

COUNT

Purpose

Counts the number of instances in the database and returns the result

Examples def noOfBooks = Book.count()

Page 131: grails command main

COUNTBY*

Purpose

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that count the number of records returned

Examples

Given the domain class Book:

class Book {

Long id

Long version

String title

Date releaseDate

String author

}

The following are all possible:

def c = Book.countByTitle("The Shining")

c = Book.countByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")

c = Book.countByReleaseDateBetween(firstDate, new Date())

c = Book.countByReleaseDateGreaterThanEquals(firstDate)

c = Book.countByTitleLike("%Hobbit%")

c = Book.countByTitleNotEqual("Harry Potter")

c = Book.countByReleaseDateIsNull()

c = Book.countByReleaseDateIsNotNull()

Description

GORM supports the notion of Dynamic Finders. The countBy* method counts the

number of records for the given expression and returns the result.

The following operator names can be used within the respective dynamic methods:

o LessThan

o LessThanEquals

o GreaterThan

o GreaterThanEquals

o Between

o Like

o Ilike (i.e. ignorecase like)

o IsNotNull

o IsNull

o Not

o Equal

o NotEqual

o And

o Or

The above operator names can be considered keywords, and you will run into problems when querying domain classes that have one of these names used as property names. For more information on dynamic finders refer to the user guide.

Page 132: grails command main

CREATE CRITERIA

Purpose

Creates and returns an instance of Grails' HibernateCriteriaBuilder that can be used to construct criteria queries.

Examples def c = Account.createCriteria()

def results = c.list {

like("holderFirstName", "Fred%")

and {

between("balance", 500, 1000)

eq("branch", "London")

}

maxResults(10)

order("holderLastName", "desc")

}

In order to use pagination you would have to make another query to retrieve the total number of matching results. A better way is to pass the necessary pagination values as arguments to the criteria method as shown below:

def c = Account.createCriteria()

def results = c.list (max: 10, offset: 10) {

like("holderFirstName", "Fred%")

and {

between("balance", 500, 1000)

eq("branch", "London")

}

order("holderLastName", "desc")

}

This will return a PagedResultList which has a getTotalCount() method to return the total number of matching records for pagination.

println "Rendering ${results.size()} Accounts of ${results.totalCount}"

Description

Criteria queries are a type safe, advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better alternative to using StringBuffer. Refer to the user guide section on Criteria for usage instructions.

Method reference:

Method Description

list This is the default method. It returns all matching rows.

get

Returns a unique result set, i.e. just one row. The criteria has to be formed that way,

that it only queries one row. This method is not to be confused with a limit to just the

first row.

scroll Returns a scrollable result set

Page 133: grails command main

listDistinct

If subqueries or associations are used, one may end up with the same row multiple

times in the result set. In Hibernate one would do a

"CriteriaSpecification.DISTINCT_ROOT_ENTITY". In grails one can do it even simpler by

just using this method.

If you invoke the builder with no method name like so

c { … }

the list() method will be invoked automatically. In other words, it's the equivalent of

c.list { … }

Below is a node reference for each criterion method:

Node Description Example

between

Where the

property value is

between to

distinct values

between("balance", 500, 1000)

eq

Where a property

equals a particular

value. eq("branch", "London")

eq (case-

insensitive)

A version

of eq that

supports an

optional 3rd Map

parameter to

specify that the

query be case-

insensitive.

eq("branch", "london", [ignoreCase: true])

eqProperty

Where one

property must

equal another eqProperty("lastTransaction","firstTransaction")

gt

Where a property

is greater than a

particular value gt("balance",1000)

gtProperty

Where a one

property must be

greater than

another

gtProperty("balance","overdraft")

Page 134: grails command main

ge

Where a property

is greater than or

equal to a

particular value

ge("balance",1000)

geProperty

Where a one

property must be

greater than or

equal to another

geProperty("balance","overdraft")

idEq

Where an objects

id equals the

specified value idEq(1)

ilike A case-insensitive

'like' expression ilike("holderFirstName","Steph%")

in

Where a one

property is

contained within

the specified list

of values note: 'in'

is a groovy

reserve word, we

must escape it by

quotes.

'in'("holderAge",[18..65])

isEmpty

Where a

collection

property is empty isEmpty("transactions")

isNotEmpty

Where a

collection

property is not

empty

isNotEmpty("transactions")

isNull Where a property

is null isNull("holderGender")

isNotNull Where a property

is not null isNotNull("holderGender")

lt Where a property lt("balance",1000)

Page 135: grails command main

is less than a

particular value

ltProperty

Where a one

property must be

less than another ltProperty("balance","overdraft")

le

Where a property

is less than or

equal to a

particular value

le("balance",1000)

leProperty

Where a one

property must be

less than or equal

to another

leProperty("balance","overdraft")

like Equivalent to SQL

like expression like("holderFirstName","Steph%")

ne

Where a property

does not equals a

particular value ne("branch", "London")

neProperty

Where one

property does not

equal another neProperty("lastTransaction","firstTransaction")

order

Order the results

by a particular

property order("holderLastName", "desc")

rlike

Similar to like, but

uses a regex. Only

supported on

Oracle and

MySQL.

rlike("holderFirstName",/Steph.+/)

sizeEq

Where a

collection

property's size

equals a particular

value

sizeEq("transactions", 10)

Page 136: grails command main

sizeGt

Where a

collection

property's size is

greater than a

particular value

sizeGt("transactions", 10)

sizeGe

Where a

collection

property's size is

greater than or

equal to a

particular value

sizeGe("transactions", 10)

sizeLt

Where a

collection

property's size is

less than a

particular value

sizeLt("transactions", 10)

sizeLe

Where a

collection

property's size is

less than or equal

to a particular

value

sizeLe("transactions", 10)

sizeNe

Where a

collection

property's size is

not equal to a

particular value

sizeNe("transactions", 10)

sqlRestriction

Use arbitrary SQL

to modify the

resultset sqlRestriction "char_length( first_name ) = 4"

With dynamic finders, you have access to options such as 'max', 'sort', etc. These are available to criteria queries as well, but they are named differently:

Name Description Example

order(string,

string)

Specifies both the sort column (the first argument) and

the sort order (either 'asc' or 'desc'). order "age",

"desc"

Page 137: grails command main

firstResult(int) Specifies the offset for the results. A value of 0 will return

all records up to the maximum specified. firstResult 20

maxResults(int) Specifies the maximum number of records to return. maxResults 10

cache(boolean) Tells Hibernate whether to cache the query or not (if the

query cache is enabled). cache true

Criteria also support the notion of projections. A projection is used to change the nature of the results. For example the following query using a projection to count the number

of distinct branchnames there are for each Account:

def c = Account.createCriteria()

def branchCount = c.get {

projections {

countDistinct "branch"

}

}

The following table summarizes the different projections and what they do:

Name Description Example

property Returns the given property in

the returned results property("firstName")

distinct

Returns results using a single or

collection of distinct property

names

distinct("lastName") or

distinct(['firstName', 'lastName'])

avg Returns the average value of

the given property avg("age")

count Returns the count of the given

property name count("branch")

countDistinct Returns the distinct count of

the given property name countDistinct("branch")

groupProperty Groups the results by the given

property groupProperty("lastName")

max Returns the maximum value of

the given property max("age")

min Returns the minimum value of min("age")

Page 138: grails command main

the given property

sum Returns the sum of the given

property sum("balance")

rowCount Returns count of the number of

rows returned rowCount()

Page 139: grails command main

DELETE

Purpose

Indicates that a persistent instance should be deleted.

Examples def book = Book.get(1)

book.delete()

Description

The delete method informs the persistence context that a persistent instance should be

deleted. Equivalent to the Hibernate delete method.

Calling delete on a transient instance will result in an error

Parameters:

o flush - If set to true persistent context will be flushed resulting in the instance being

deleted immediately. Example:

def book = Book.get(1)

book.delete(flush:true)

Page 140: grails command main

DISCARD

Purpose

Discards any changes that have been made during an update.

Examples def b = Book.get(1)

b.title = "Blah"

b.discard() // changes won't be applied now

Description

The discard method informs the persistence context that an instance should not be

saved. The discard method is equivalent to using Hibernate's evict method.

Note that this method will not clean or reset the object with the original values it will

just prevent it from being automatically saved by Grails.

Page 141: grails command main

ERRORS

Purpose

An instance of the Spring Errors interface that contains data binding and/or validation errors.

Examples def user = new User(params)

if(user.validate()) {

// do something with user

}

else {

user.errors.allErrors.each {

println it

}

}

Description

The errors property is an instance of Spring's Errors interface which is used by Grails

during Data Binding to store type conversion errors and during Validation when calling the validate or savemethods.

You can create your own errors using the reject and rejectValue methods:

if (params.password != params.confirm_password) {

user.errors.reject('user.password.doesnotmatch',

// Error code within the grails-app/i18n/message.properties

['password', 'class User'] as Object[],

// Groovy list cast to Object[]

'[Property [{0}] of class [{1}] does not match

confirmation]') // Default mapping string

// The following helps with field highlighting in your view

user.errors.rejectValue('password',

// Field in view to highlight using <g:hasErrors> tag

'user.password.doesnotmatch')

// i18n error code

render(view:'signup', model:[user:user])

}

Page 142: grails command main

EXECUTEQUERY

Purpose

Allows the execution of HQL queries against a domain class

Examples // simple query

Account.executeQuery( "select distinct a.number from Account a" );

// using with list of parameters

Account.executeQuery( "select distinct a.number from Account a where

a.branch = ? and a.created > ?", ['London',lastMonth] );

// using with a single parameter and pagination params (since 0.5)

Account.executeQuery( "select distinct a.number from Account a where

a.branch = ?", ['London'], [max:10,offset:5] );

// using with Map of named parameters (since 0.5)

Account.executeQuery( "select distinct a.number from Account a where

a.branch = :branch", [branch:'London'] );

// using with Map of named parameters and pagination params (since 0.5)

Account.executeQuery( "select distinct a.number from Account a where

a.branch = :branch", [branch:'London', max:10, offset:5] );

// same as previous

Account.executeQuery( "select distinct a.number from Account a where

a.branch = :branch", [branch:'London'], [max:10, offset:5] );

Description

The executeQuery method allows the execution of arbitrary HQL queries that don't

necessary return instances of a domain class. This is useful if you only want a subset of data instead of the whole object hierarchy. The basic syntax is:

Book.executeQuery( String query )

Book.executeQuery( String query, Collection positionalParams )

Book.executeQuery( String query, Collection positionalParams, Map

paginateParams )

Book.executeQuery( String query, Map namedParams )

Book.executeQuery( String query, Map namedParams, Map paginateParams )

Parameters:

o query - An HQL query

o positionalParams - A List of parameters for a positional parametrized HQL query

o namedParams - A Map of named parameters a HQL query

o paginateParams - A Map containing parameters 'max' or/and 'offset' (see examples

below)

Page 143: grails command main

EXECUTEUPDATE

Purpose

Allows updating a database with DML-style operation

Examples Account.executeUpdate("delete Book b where b.pages > 100")

Account.executeUpdate("delete Book b where b.title like ?", ['Groovy In

Action'])

Account.executeUpdate("delete Book b where b.author=?", [Author.get(1)])

Account.executeUpdate("update Book b set b.title='Groovy In Action' where

b.title='GINA'")

Description

GORM does not provide a deleteAll method as deleting data is to be done with

caution. If you really need to delete data you can use executeUpdate. The basic syntax

is:

Book.executeUpdate( String query )

Book.executeUpdate( String query, Collection positionalParams )

Parameters:

o query - An HQL query with DML-style operations

o positionalParams - A List of parameters for a positional parameterized HQL query

Page 144: grails command main

EXISTS

Purpose

Checks whether an instance exists for the specified id and returns true if it does

Examples if(Account.exists(1)) {

// do something

}

Description

Parameters:

o id - The id of the object

Page 145: grails command main

FETCHMODE

Purpose

Allows the configuration of an associations fetch strategy ('eager' or 'lazy')

Examples class Author {

String name

static hasMany = [books:Book]

static fetchMode = [books:'eager']

}

In this example the fetchMode static property specifies that the book association should

be fetching eagerly

Description

By default associations in Grails are fetched lazily (each record is read from the database only when its first accessed from the collection). This makes sense for most cases, however in the case where you have a small number of records to fetch and/or are repeatedly required to load lazy associations (resulting in N+1) it makes sense to use eager fetching.

In the case of eager fetching and a one-to-many association, the instance as well as the association will be initialized when they are loaded (eagerly). However, caution should be observed when using eager fetching, being too eager can result in your entire database being loaded into memory!

Page 146: grails command main

FIND

Purpose

Finds and returns the first result for the given query or null if no instance was found

Examples // Dan brown's first book

Book.find("from Book as b where b.author='Dan Brown'")

// with a positional parameter

Book.find("from Book as b where b.author=?",['Dan Brown'])

// with a named parameter (since 0.5)

Book.find("from Book as b where b.author=:author",[author:'Dan Brown'])

// use the query cache

Book.find("from Book as b where b.author='Dan Brown'", [cache: true])

Book.find("from Book as b where b.author=:author",[author:'Dan Brown'],

[cache: true])

// query by example

def b = new Book(author:"Dan Brown")

Book.find(b)

Description

The find method allows querying with Hibernate's query language HQL and querying by

example. The basic syntax is:

Book.find( String query )

Book.find( String query, Collection positionalParams )

Book.find( String query, Map namedParams )

Book.find( Book example )

Parameters:

o query - An HQL query

o positionalParams - A List of parameters for a positional parametrized HQL query

o namedParams - A Map of named parameters a HQL query

o queryParams - A Map of query parameters. Currently, only cache is supported

o example - An instance of the domain class for query by example

Page 147: grails command main

FINDALL

Purpose

Finds all of the domain class instances for the specified query

Examples // everything

Book.findAll()

// with a positional parameter

Book.findAll("from Book as b where b.author=?",['Dan Brown'])

// 10 books from Dan Brown staring from 5th book ordered by release date

Book.findAll("from Book as b where b.author=? order by b.releaseDate",['Dan

Brown'],[max:10,offset:5])

// examples with max/offset usage

def query = "from Book as b where b.author='Dan Brown' order by

b.releaseDate"

// first 10 books

Book.findAll(query,[max:10])

// 10 books starting from 5th

Book.findAll(query,[max:10,offset:5])

// examples with named parameters (since 0.5)

Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'])

Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'],

[max:10, offset:5])

Book.findAll("from Book as b where b.author in (:authors)", [authors:['Dan

Brown','Jack London']])

// examples with tables join

Book.findAll("from Book as b where not exists (from Borrow as br where

br.book = b)")

// query by example

def b = new Book(author:"Dan Brown")

Book.findAll(b)

Description

The findAll method allows querying with Hibernate's query language HQL and

querying by example for a collection of matching instances. Pagination can be controlled via the max and offset parameters appended to the end:

Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'],

[max:10, offset:5])

The findAll method supports the 2nd level cache:

Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'],

[max:10, offset:5, cache: true])

The basic syntax for the method is:

Book.findAll()

Book.findAll(String query)

Book.findAll(String query, Collection positionalParams)

Book.findAll(String query, Collection positionalParams, Map queryParams)

Book.findAll(String query, Map namedParams)

Book.findAll(String query, Map namedParams, Map queryParams)

Page 148: grails command main

Book.findAll(Book example)

If you have a join in your HQL, the method will return a List of Arrays containing

domain class instances. You may wish to use executeQuery in this case so you have

more flexibility in specifying what gets returned.

Parameters:

o query - An HQL query

o positionalParams - A List of parameters for a positional parametrized HQL query

o namedParams - A Map of named parameters a HQL query

o queryParams - A Map containing parameters 'max', and/or 'offset' and/or 'cache'

o example - An instance of the domain class for query by example

Page 149: grails command main

FINDALLBY*

Purpose

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return all instances of the domain class

Examples

Given the domain class Book:

class Book {

Long id

Long version

String title

Date releaseDate

String author

Boolean paperback

}

The following are all possible:

def results = Book.findAllByTitle("The Shining", [max:10, sort:"title",

order:"desc", offset:100] )

results = Book.findAllByTitleAndAuthor("The Sum of All Fears", "Tom

Clancy")

results = Book.findAllByReleaseDateBetween(firstDate, new Date())

results = Book.findAllByReleaseDateGreaterThanEquals(firstDate)

results = Book.findAllByTitleLike("%Hobbit%")

results = Book.findAllByTitleIlike("%Hobbit%") // (since 0.5) - ignorecase

results = Book.findAllByTitleNotEqual("Harry Potter")

results = Book.findAllByReleaseDateIsNull()

results = Book.findAllByReleaseDateIsNotNull()

results = Book.findAllPaperbackByAuthor("Douglas Adams")

results = Book.findAllNotPaperbackByAuthor("Douglas Adams")

results = Book.findAllByAuthorInList(["Douglas Adams", "Hunter S.

Thompson"])

Description

GORM supports the notion of Dynamic Finders. The findAllBy* method finds all the

results for the given method expression.

Parameters:

o paginateParams - A Map containing parameters max, order, offset and sort

Pagination and sorting parameters can be used as the last argument to a dynamic method:

def results = Book.findAllByTitle("The Shining", [max:10, sort:"title",

order:"desc", offset:100] )

The following operator names can be used within the respective dynamic methods:

o LessThan

o LessThanEquals

o GreaterThan

o GreaterThanEquals

o Between

o Like

Page 150: grails command main

o Ilike (i.e. ignorecase like)

o IsNotNull

o IsNull

o Not

o NotEqual

o And

o Or

o InList

The above operator names can be considered keywords, and you will run into problems when querying domain classes that have one of these names used as property names. For more information on dynamic finders refer to the user guide.

Page 151: grails command main

FINDALLWHERE

Purpose

Uses named arguments that match the property names of the domain class to produce a query that returns all of the matching results.

Examples

Given the domain class:

class Book {

String title

Date releaseDate

String author

static constraints = {

releaseDate nullable: true

}

}

You can query in the form:

def books = Book.findAllWhere(author:"Stephen King", title:"The Stand")

def unreleasedBooks = Book.findAllWhere(releaseDate: null)

Description

Parameters:

o queryParams - A map of key value pairs to be used in the query

Page 152: grails command main

FINDBY*

Purpose

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return the first result of the query

Examples

Given the domain class Book:

class Book {

Long id

Long version

String title

Date releaseDate

String author

Boolean paperback

}

The following are all possible:

def b = Book.findByTitle("The Shining")

b = Book.findByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")

b = Book.findByReleaseDateBetween(firstDate, new Date())

b = Book.findByReleaseDateGreaterThanEquals(firstDate)

b = Book.findByReleaseDateLessThanEquals(firstDate)

b = Book.findByTitleLike("%Hobbit%")

b = Book.findByTitleIlike("%Hobbit%") // (since 0.5) - ignorecase

b = Book.findByTitleNotEqual("Harry Potter")

b = Book.findByReleaseDateIsNull()

b = Book.findByReleaseDateIsNotNull()

b = Book.findPaperbackByAuthor("Douglas Adams")

b = Book.findNotPaperbackByAuthor("Douglas Adams")

b = Book.findByAuthorInList(["Douglas Adams", "Hunter S. Thompson"])

Description

GORM supports the notion of Dynamic Finders. The findBy* method finds the first

result for the given method expression.

The following operator names can be used within the respective dynamic methods:

o LessThan

o LessThanEquals

o GreaterThan

o GreaterThanEquals

o Between

o Like

o Ilike (i.e. ignorecase like)

o IsNotNull

o IsNull

o Not

o NotEqual

o And

o Or

o InList

Page 153: grails command main

The above operator names can be considered keywords, and you will run into problems when querying domain classes that have one of these names used as property names. For more information on dynamic finders refer to the user guide.

Page 154: grails command main

FINDWHERE

Purpose

Uses named arguments that match the property names of the domain class to produce a query that returns the first result.

Examples

Given the domain class:

class Book {

String title

Date releaseDate

String author

static constraints = {

releaseDate nullable: true

}

}

You can query in the form:

def book = Book.findWhere(author:"Stephen King", title:"The Stand")

boolean isReleased = Book.findWhere(author:"Stephen King", title:"The

Stand", releaseDate: null) != null

Description

Parameters:

o queryParams - A map of key value pairs to be used in the query

Page 155: grails command main

GET

Purpose

Retrieves an instance of the domain class for the specified id, otherwise returns null

Examples def b = Book.get(1)

Description

Parameters:

o id - The id of the object to retrieve

Page 156: grails command main

GETALL

Purpose

Retrieves an instances of the domain class for the specified ids and returns a list of these instances, ordered by the original ids list. If some of provided ids are null or there are no instances with these ids, then result list will contain null values on corresponding positions.

Examples // get a list which contains Book instances with ids 2, 1, 3 respectively

def bookList = Book.getAll(2,1,3)

// can take a list of ids as only argument, extremely useful when ids list

calculated in code

def bookList = Book.getAll([1,2,3])

// when called without arguments returns list of all objects

def bookList = Book.getAll()

Description

Parameters:

o varargs* - A variable argument list of ids

o ids* - A list of ids

Page 157: grails command main

GETDIRTYPROPERTYNAMES

Purpose

Retrieve the names of modified fields in a domain class instance.

Examples def b = Book.get(1)

someMethodThatMightModifyTheInstance(b)

def names = b.dirtyPropertyNames

for (name in names) {

def originalValue = b.getPersistentValue(name)

}

Description

This method is useful mostly for audit logging or other work done in a beforeUpdate event callback. Hibernate caches the original state of all loaded instances for dirty checking during a flush and this method exposes the names of modified fields so you can compare them with the current state.

Page 158: grails command main

GETPERSISTENTVALUE

Purpose

Retrieve the original value of a field for a domain class instance.

Examples def b = Book.get(1)

someMethodThatMightModifyTheInstance(b)

if (b.isDirty('name')) {

def currentName = b.name

def originalName = b.getPersistentValue('name')

if (currentName != originalName) {

}

}

Description

This method is useful mostly for audit logging or other work done in a beforeUpdate event callback. Hibernate caches the original state of all loaded instances for dirty checking during a flush and this method exposes that data so you can compare it with the current state.

Page 159: grails command main

HASERRORS

Purpose

True if the domain class instance has errors following a call to validate or save or following Data Binding

Examples def b = new Book(title:"The Shining")

b.validate()

if(b.hasErrors()) {

b.errors.each {

println it

}

}

Page 160: grails command main

HASMANY

Purpose

Defines a one-to-many association between two classes.

Examples class Author {

String name

static hasMany = [books:Book]

}

In this example we define a one-to-many relationship between the Author class and

the Book class (one Author has many books)

Description

By default GORM will create a property of type java.util.Set using the key inside the

definition of the hasMany map. For example consider this definition:

static hasMany = [books:Book]

Here a property of type java.util.Set called books will be created within the defining

class. These can then be iterated over and manipulated:

def a = Author.get(1)

a.books.each { println it.title }

Page 161: grails command main

HASONE

Purpose

Defines a bidirectional one-to-one association between two classes where the foreign key is in the child.

Examples class Face {

..

static hasOne = [nose:Nose]

}

class Nose {

Face face

}

In this example we define a one-to-one relationship between the Face class and

the Nose class

Description

A hasOne association should be used in the case where you want to store the foreign

key reference in child table instead of the parent in a bidirectional one-to-one. The example presented above will generate the following table structure:

create table face (id bigint generated by default as identity (start with

1),

version bigint not null,

name varchar(255) not null,

primary key (id))

create table nose (id bigint generated by default as identity (start with

1),

version bigint not null,

face_id bigint not null,

shape varchar(255) not null,

primary key (id))

Notice that the foreign key face_id is stored in the nose table instead of the face table

as with a normal one-to-one definition without belongsTo.

Page 162: grails command main

IDENT

Purpose

Returns the value of the identity property of the domain class regardless of the name of the identity property itself

Examples def b = new Book(title:"The Shining")

b.save()

println b.ident()

Page 163: grails command main

INSTANCEOF

Purpose

Determines if a domain class instance is an instance of the specified class, resolving the actual class if the instance is a proxy.

Examples

Given the domain classes:

class Container {

static hasMany = [children: Child]

}

class Child {

String name

static belongsTo = [container: Container]

}

class Thing extends Child {}

class Other extends Child {}

Then you can determine the type of the elements in a Container's children collection

using

def container = Container.get(id)

for (child in container.children) {

if (child.instanceOf(Thing)) {

// process Thing

}

else if (child.instanceOf(Other)) {

// process Other

}

else {

// handle unexpected type

}

}

Description

Parameters:

o clazz - the type to check

Page 164: grails command main

ISATTACHED

Purpose

Returns whether the domain instance is attached to a currently active session or not. This method is often used on conjunction with the merge or attach methods.

Examples Book b = session.book

if(!b.isAttached()) {

b.attach()

}

Description

Grails uses Hibernate which manages each persistent object in a persistence session. A new session is created per request and is closed at the end of the request. If an object is read from the session and placed into a web scope such as the HttpSession it is seen as detached, since the persistence session has been closed. You can use the attach method to re-attach an existing persistent instance to the persistence session of the current request.

Page 165: grails command main

ISDIRTY

Purpose

Checks to see if a domain class instance has been modified.

Examples def b = Book.get(1)

someMethodThatMightModifyTheInstance(b)

// when called without arguments returns true if any field was changed

if (b.isDirty()) {

// can also check if one field has changed

if (b.isDirty('title')) {

}

}

Description

Parameters:

o fieldName - The name of a field to check

Page 166: grails command main

LIST

Purpose

Lists all of the instances of the domain class.

Examples // list everything

def results = Book.list()

// list 10 results

def results = Book.list(max:10)

// list 10 results, offset by 100

def results = Book.list(max:10, offset:100)

// list 10 results, offset by 100, orderd by title in descending order

def results = Book.list(max:10, offset:100, sort:"title", order:"desc")

// list all books, eagerly fetching the authors association

def results = Book.list(fetch:[authors:"eager"])

Description

Parameters:

o max - The maximum number to list

o offset - The offset from the first result to list from

o order - The order to list by, either "desc" or "asc"

o sort - The property name to sort by

o ignoreCase - Whether to ignore the case when sorting. Default is true.

o fetch - The fetch policy for the object's associations as a Map

Page 167: grails command main

LISTORDERBY*

Purpose

Lists all of the instances of the domain class ordered by the property in the method expression

Examples def results = Book.listOrderByAuthor() // everything

def results = Book.listOrderByTitle(max:10) // 10 results

def results = Book.listOrderByTitle(max:10, offset:100, order:"desc") // 10

results, offset from 100

Description

Parameters:

o max - The maximum number to list

o offset - The offset from the first result to list from

o order - The order to list by, either "desc" or "asc"

Page 168: grails command main

LOAD

Purpose

Returns a persistent instance of the domain class for the given identifier.

Usually returns a proxy for the instance that is initialized on-demand, when a method other than getId() is invoked. load() only returns null if the provided id is null, so you cannot use it to test for existence. If you provide an id for an instance that doesn't exist, a proxy will be returned and an exception will be thrown only when you call any instance method other than getId().

If there is an existing instance with the same id in the Hibernate session or 2nd-level cache, load() will return that instance instead of a proxy.

Examples // load a single instance

def b = Book.load(1)

// delete an instance without retrieving it

Book.load(1).delete()

Description

Parameters:

o id - The id of the object to retrieve

Page 169: grails command main

LOCK

Purpose

The lock method obtains a pessimistic lock using an SQL select … for update.

Examples def book = Book.get(1)

book.lock()

Description

The lock method will obtain a pessimistic lock on an instance, essentially locking a row

in the database with select … for update. The lock method is equivalent to using

Hibernate'sLockMode.UPGRADE in combination with the lock method.

The lock will automatically be released when the transaction is committed. In Grails this is typically after an action has finished executing.

Refer to the section on Optimistic and Pessimistic locking in the user guide for info.

Page 170: grails command main

MAPPEDBY

Purpose

The mappedBy static property adds the ability to change how a bidirectional associations

is linked

Examples class Airport {

static mappedBy = [outgoingFlights:'departureAirport',

incomingFlights:'destinationAirport']

static hasMany = [outgoingFlights:Route,

incomingFlights: Rout]

}

class Route {

Airport departureAirport

Airport destinationAirport

}

In this example the Airport class defines two bidirectional one-to-many associations.

Without defining mappedBy this is impossible as GORM cannot differentiate which of the

two properties on the other end of the association

(either departureAirport or destinationAirport in the Route class) each one-to-

many should be associated one.

The solution is to define mappedBy which tells the Airport class how each association

relates to the other side.

Page 171: grails command main

MAPPING

Purpose

The mapping static property is used to allow how GORM maps to the underlying

database. See the section on the ORM DSL in the user guide for more information.

Examples class Person {

String firstName

static hasMany = [addresses:Address]

static mapping = {

table 'people'

version false

id column:'person_id'

firstName column:'First_Name'

addresses lazy:false

}

}

Uses the ORM DSL to map the Person class onto a table called people

Page 172: grails command main

MERGE

Purpose

Merges a domain class instance back into the current persistent context and returns a new merged instance.

Examples def b = new Book(title:"The Shining")

b = b.merge()

Description

The merge method is similar in function to the save method, but not in behaviour.

The merge allows the merging of "detached" instances such as those stored in the

HTTP session. Essentially, each persistent instance is associated with a persistence context. A new persistence context is created for each request. The result is objects stored in the session lose their persistent context on subsequent requests. In this case you can't simply call save as the domain class is not associated with a current context.

The merge method on the other hand allows you to merge a detached objects state

back into the current session. Unlike the save method this method returns a new

instance of the class representing the re-attached object. In other words you must write code like the below:

book = book.merge()

If you don't use the return value of the merge method then you still have access to the

original detached instance and you will get errors such as lazy initialization exceptions.

The merge method is defined in the Hibernate documentation as follows:

Copy the state of the given object onto the persistent object with the same identifier. If there is no

persistent instance currently associated with the session, it will be loaded. If the given instance is

unsaved, save a copy of and return it as a newly persistent instance.

The merge method is equivalent to the Hibernate merge method.

Parameters:

o validate (optional) - Set to false if validation should be skipped

o flush (optional) - When set to true flushes the persistent context, hence persisting the

object immediately

Page 173: grails command main

NAMEDQUERIES

Purpose

The namedQueries static property is used to define named queries. Named queries

support the criteria builder syntax. See the section on the Criteria Builder in the user guide for more information.

Examples class Publication {

String title

String author

Date datePublished

Integer numberOfPages

static namedQueries = {

recentPublications {

def now = new Date()

gt 'datePublished', now - 365

}

oldPublicationsLargerThan { pageCount ->

def now = new Date()

lt 'datePublished', now - 365

gt 'numberOfPages', pageCount

}

publicationsWithBookInTitle {

like 'title', '%Book%'

}

recentPublicationsWithBookInTitle {

// calls to other named queries…

recentPublications()

publicationsWithBookInTitle()

}

}

}

// get all recent publications…

def recentPubs = Publication.recentPublications.list()

// get up to 10 recent publications, skip the first 5…

def recentPubs = Publication.recentPublications.list(max: 10, offset: 5)

// get the number of recent publications…

def numberOfRecentPubs = Publication.recentPublications.count()

// get a recent publication with a specific id…

def pub = Publication.recentPublications.get(42)

// get all recent publications where title = 'Some Title'

def pubs = Publication.recentPublications.findAllWhere(title: 'Some Title')

// get a recent publication where title = 'Some Title'

def pub = Publication.recentPublications.findWhere(title: 'Some Title')

Page 174: grails command main

// dynamic finders are supported

def pubs = Publication.recentPublications.findAllByTitle('Some Title')

// get all old publications with more than 350 pages

def pubs = Publication.oldPublicationsLargerThan(350).list()

// get all old publications with more than 350 pages and the word 'Grails'

in the title

def pubs =

Publication.oldPublicationsLargerThan(350).findAllByTitleLike('%Grails%')

// get all recent publications with 'Book' in their title

def pubs = Publication.recentPublicationsWithBookInTitle().list()

The list method on named queries supports the same attributes as the

static list method added to domain classes (sort, order, ignoreCase, fetch etc...). See

the list docs for details.

Note that calling something like Publication.recentPublications.get(42) is not the

same thing as calling something like Publication.get(42). The former will only return

aPublication if the Publication with id 42 meets all the criteria defined in

the recentPublications named query.

Named criteria support listDistinct().

class PlantCategory {

Set plants

String name

static hasMany = [plants:Plant]

static namedQueries = {

withPlantsInPatch {

plants {

eq 'goesInPatch', true

}

}

}

}

class Plant {

boolean goesInPatch

String name

}

PlantCategory.withPlantsInPatch.listDistinct()

Named criteria support additional criteria being supplied at invocation time in the form of a criteria closure:

// get all recent publications with author names beginning with Tony or

Phil…

def books = Publication.recentPublications {

or {

like 'author', 'Tony%'

like 'author', 'Phil%'

}

}

Page 175: grails command main

// get the number of recent publications with author names beginning with

Tony or Phil…

def numberOfBooks = Publication.recentPublications.count {

or {

like 'author', 'Tony%'

like 'author', 'Phil%'

}

}

Named criteria may be chained together. When criteria are chained together, the query will be generated as if all of the chained criteria had been combined in a single criteria closure.

// recent publications with 'Book' in the title

def books =

Publication.recentPublications.publicationsWithBookInTitle.list()

// old publications with more than 500 pages and with 'Book' in the title

def books =

Publication.oldPublicationsLargerThan(500).publicationsWithBookInTitle.list

()

Page 176: grails command main

PROPERTIES

Purpose

Allows access to the domain class properties as a map and is typically used for Data Binding to perform types conversion when set allowing properties to be set from request parameters.

Examples def b = new Book(title:"The Shining")

b.properties = this.params

Page 177: grails command main

READ

Purpose

Retrieves an instance of the domain class for the specified id in a read-only state, if the

object doesn't exist null is returned.

Examples def b = Book.read(1)

Description

Parameters:

o id - The id of the object to retrieve

Page 178: grails command main

REFRESH

Purpose

Refreshes a domain classes state from the database

Examples def b = Book.get(1)

b.refresh()

Description

Equivalent to the Hibernate refresh method.

Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances. For example

o where a database trigger alters the object state upon insert or update

o after executing direct SQL (eg. a mass update) in the same session

o after inserting a Blob or Clob

Page 179: grails command main

REMOVEFROM*

Purpose

Opposite of the addTo method in that it removes instances from an association.

Examples def author = Author.findByName("Stephen King")

def book = author.books.find { it.title = 'The Stand' }

author.removeFromBooks(book)

Page 180: grails command main

SAVE

Purpose

Saves a domain class instance to the database cascading updates to any child instances if required.

Examples def b = new Book(title:"The Shining")

b.save()

Description

The save method informs the persistence context that an instance should be saved or

updated. The object will not be persisted immediately unless the flush argument is

used:

b.save(flush:true)

The save method returns null if validation failed and the instance was not saved and

the instance itself if successful. This allows you to write code like the following:

if( !b.save() ) {

b.errors.each {

println it

}

}

Parameters:

o validate (optional) - Set to false if validation should be skipped

o flush (optional) - When set to true flushes the persistent context, hence persisting the

object immediately

o insert (optional) - When set to true will force Hibernate to do a SQL INSERT, this is

useful in certain situations when legacy databases (such as AS/400) are involved and Hibernate cannot detect whether to do an INSERT or an UPDATE

o failOnError (optional) - When set to true the save method with throw

a grails.validation.ValidationException if validation fails during a save. This

behavior may also be triggered by setting the grails.gorm.failOnError property

in grails-app/conf/Config.groovy. If the Config property is set and the argument is

passed to the method, the method argument will always take precedence. For more details about the config property and other GORM config options, see the GORM Configuration Options section of The User Guide.

o deepValidate (optional) - Determines whether associations of the domain instance

should also be validated, i.e. whether validation cascades or not. This is true by default

- set to false to disable cascading validation.

Page 181: grails command main

TRANSIENTS

Purpose

Defines a list of property names that should not be persisted to the database. This is often useful if you have read-only getters that include logic.

Examples class Author {

String name

String getUpperCaseName() { name.toUpperCase() }

static transients = ['upperCaseName']

}

Here we have a getter that takes the name and converts it to upper case. In this case it doesn't make sense to persist this property, hence we mark it as transient by referring to the name using JavaBean conventions.

Page 182: grails command main

VALIDATE

Purpose

Validates a domain class against the applied constraints (see Validation)

Description

The validate method will validate a domain class based on its defined constraints. The

errors will be stored within the errors object.

The validate method accepts an optional List argument which may contain the names

of the properties that should be validated. When a List is passed to

the validate method, only the properties defined in the List will be validated.

Examples def b = new Book(title:"The Shining")

if( !b.validate() ) {

b.errors.each {

println it

}

}

def a = new Album(artist: "Genesis", title: "Nursery Cryme", releaseDate:

1971)

// only validate title and releaseDate

if( !a.validate(["title", "releaseDate"]) ) {

a.errors.each {

println it

}

}

Parameters:

o deepValidate (optional) - Determines whether associations of the domain instance

should also be validated, i.e. whether validation cascades or not. This is true by default

- set to false to disable cascading validation.

Page 183: grails command main

WITHCRITERIA

Purpose

Allows inline execution of criteria with a closure. See the createCriteria method for reference.

Examples def results = Book.withCriteria {

def now = new Date()

between('releaseDate', now-7, now)

like('title', '%Groovy%')

}

Description

The withCriteria method allows the inline definition of Criteria. Arguments to

the HibernateCriteriaBuilder can be passed as the first parameter:

def book = Book.withCriteria(uniqueResult:true) {

def now = new Date()

between('releaseDate', now-7, now)

like('title', '%Groovy%')

}

Parameters:

o arguments (optional) - A map on named arguments that will be set on the criteria

instance

o closure - A closure that defines the criteria

Page 184: grails command main

WITHNEWSESSION

Purpose

Provides a way to execute code within the context of a completely new Hibernate session which shares the same transactional (JDBC Connection) resource as the currently bound session.

Examples Book.withNewSession { org.hibernate.Session session ->

// do work

}

Description

Parameters:

o closure - A closure the first argument to which is the Session object

Page 185: grails command main

WITHSESSION

Purpose

Provides access to the underlying Hibernate Session object

Examples Book.withSession { org.hibernate.Session session ->

session.clear()

}

Description

Parameters:

o closure - A closure the first argument to which is the Session object

Page 186: grails command main

WITHTRANSACTION

Purpose

Allows programmatic transactions using Spring's Transaction Abstraction and a block.

Examples Account.withTransaction { status ->

def source = Account.get(params.from)

def dest = Account.get(params.to)

def amount = params.amount.toInteger()

if(source.active) {

source.balance -= amount

if(dest.active) {

dest.amount += amount

}

else {

status.setRollbackOnly()

}

}

}

Description

The withTransaction method uses a block or closure that gets passed

Spring TransactionStatus object. The TransactionStatus object can be used to

programmatically control rollback of the transaction.

Refer to the user guide section of Programmatic Transactions for more information.

Page 187: grails command main

PLUG-IN USAGE

A plug-in provides additional capability to the Grails runtime and can be created with the create-plugin command:

grails create-plugin simple

This will create a plug-in project which can then be packaged with package-plugin:

grails package-plugin

And installed into Grails applications with install-plugin:

grails install-plugin ../grails-simple-0.1.zip

Refer to the user guide topic on Plug-ins for more information.

Page 188: grails command main

URLMAPPINGS

Purpose

The URLMappings plug-in configures Grails' URL Mapping infrastructure.

Examples

An example UrlMapping class:

class UrlMappings {

static mappings = {

"/$controller/$action?/$id?" {

constraints {

// apply constraints here

}

}

}

}

Description

Refer to the section on URL Mapping in the Grails user guide which details how Grails' URL mappings work.

Configured Spring Beans:

o grailsUrlMappingsHolderBean -

A org.codehaus.groovy.grails.web.mapping.UrlMappingsHolderFactoryBean factory bean that constructs aorg.codehaus.groovy.grails.web.mapping.UrlMappingsHolder instance that stores all of the URL mappings.

o urlMappingsTargetSource - A

Spring org.springframework.aop.target.HotSwappableTargetSource used in auto-reloading to automatically update URL mappings when changed.

o grailsUrlMappingsHolder - A

Spring org.springframework.aop.framework.ProxyFactoryBean that proxies onto the

actual UrlMappingsHolderinstance using the HotSwappableTargetSource

Page 189: grails command main

CODECS

Purpose

Provides facility to register encoders and decoders of textual data as methods on any object

class HTMLCodec {

static encode = { theTarget ->

HtmlUtils.htmlEscape(theTarget.toString())

}

static decode = { theTarget ->

HtmlUtils.htmlUnescape(theTarget.toString())

}

}

assert "&lt;p&gt;Hello World!&lt;/p&gt;" == "<p>Hello

World!</p>".encodeAsHTML()

assert "<p>Hello World!</p>" == "&lt;p&gt;Hello

World!&lt;/p&gt;".decodeHTML()

Description

This plug-in searches for classes that end in the convention Codec and dynamically

registers encodeAsCodec and decodeCodec methods onjava.lang.Object so that any

data can be encoded and decoded. For more information refer to the section of Encoding and Decoding Objects in the user guide.

Provided Codecs:

o HTMLCodec - encodes/decodes HTML mark-up

o URLCodec - encodes/decodes URLs

o JavascriptCodec - encodes (escapes) Javascript

o Base64Codec - encodes/decodes Base64 data

o HexCodec - encodes a byte array or list of integers into a hex string, and decodes hex

strings into byte array

o MD5Codec - encodes a byte array or list of integers, or the characters of a string (using

default system encoding) into an MD5 digest as a hex string

o MD5BytesCodec - encodes a byte array or list of integers, or the characters of a string

(using default system encoding) into an MD5 digest as a byte array

o SHA1Codec - encodes a byte array or list of integers, or the characters of a string (using

default system encoding) into an SHA1 digest as a hex string

o SHA1BytesCodec - encodes a byte array or list of integers, or the characters of a string

(using default system encoding) into an SHA1 digest as a byte array

o SHA256Codec - encodes a byte array or list of integers, or the characters of a string

(using default system encoding) into an SHA256 digest as a hex string

o SHA256BytesCodec - encodes byte array or list of integers, or the characters of a string

(using default system encoding) into an SHA256 digest as a byte array

Page 190: grails command main

CONTROLLERS

Purpose

A plug-in that sets up core Grails MVC architecture using the underlying Spring MVC component model

Examples

A controller:

class BookController {

def list = {

books:Book.list()

}

}

A tag library:

import java.text.*

class FormatTagLib {

def dateFormat = { attrs ->

out << new

SimpleDateFormat(attrs.format).format(attrs.value)

}

}

Description

This plug-in deals with setting up Grails to use Spring MVC at its core to deal with web

requests. The plug-in sets up the GrailsDispatcherServlet and necessary Spring

beans (see below) for controllers, tag libraries and Groovy Server Pages (GSP)

Configured Spring Beans:

o exceptionHandler - An instance

of org.codehaus.groovy.grails.web.errors.GrailsExceptionResolver for dealing with exceptions

o multipartResolver - An instance

of org.springframework.web.multipart.commons.CommonsMultipartResolver used for dealing with file uploads using Apache Commons File Upload. If you do not wish to use this, set grails.disableCommonsMultipart to true in Config.groovy. Be aware that disabling multipart handling will effect the behaviour of g:actionSubmit which needs to inspect the parameters (requiring the multipart request to be parsed) during the URL mapping phase.

o simpleGrailsController - An instance

of org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController, which is an instance of the Spring MVC Controller interface and deals with delegating onto actual Grails controller classes

Page 191: grails command main

o groovyPageResourceLoader - Configured in development mode only or when

the grails.gsp.view.dir is set. This is a Spring ResourceLoader that knows how to

load GSP views from the an arbitrary location

o groovyPagesTemplateEngine - An instance

of org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine, this class deals with rendering of GSP views

o jspViewResolver - An instance

of org.codehaus.groovy.grails.web.servlet.view.GrailsViewResolver that knows how to resolve GSP views and is environment aware

The plug-in will also configure each Grails controller class as a prototyped Spring bean and each Grails tag library as a singleton Spring bean

Page 192: grails command main

CORE

Purpose

The core plug-in that adds methods and beans that other plug-ins rely upon

Description

This plug-in deals with setting up Grails to use Spring MVC at its core to deal with web

requests. The plug-in sets up the GrailsDispatcherServlet and necessary Spring

beans (see below) for controllers, tag libraries and Groovy Server Pages (GSP)

Configured Spring Beans:

o classLoader - A bean that refers to the GroovyClassLoader used to load this

GrailsApplication

o classEditor - A PropertyEditor that allows conversion of String's to classes using

the classLoader bean

o customEditors - An instance

of org.springframework.beans.factory.config.CustomEditorConfigurer, that uses allows

the classEditor bean to be used as a PropertyEditor

Page 193: grails command main

DATASOURCE

Purpose

The dataSource plug-in sets up the Grails JDBC DataSource instance.

Examples

A DataSource configured with explicit settings in grails-

app/conf/DataSource.groovy:

dataSource {

pooled = true

dbCreate = "update"

url = "jdbc:mysql://localhost/yourDB"

driverClassName = "com.mysql.jdbc.Driver"

username = "yourUser"

password = "yourPassword"

}

A DataSource configured to look-up via JNDI:

dataSource {

jndiName = "java:comp/env/myDataSource"

}

Description

Refer to the section on Data Sources in the Grails user guide.

Configured Spring Beans:

o dataSource - An instance of the Apache DBCP

libraries org.apache.commons.dbcp.BasicDataSource class or

aorg.springframework.jndi.JndiObjectFactoryBean in the case of a JNDI DataSource

Page 194: grails command main

DOMAINCLASS

Purpose

The domainClass plug-in sets up Grails domain classes as prototyped beans in the

Spring ApplicationContext

Examples

An example domain class:

class Book {

String title

Date releaseDate

Author author

}

Description

Refer to the section on GORM in the Grails user guide which details how to create Grails domain classes.

Configured Spring Beans given a domain class of Book:

o BookValidator -

A org.codehaus.groovy.grails.validation.GrailsDomainClassValidator that validates a domain class' defined constraints.

o BookPersistentClass - The java.lang.Class for the domain class Book

o BookDomainClass -

The org.codehaus.groovy.grails.commons.GrailsDomainClass instance which understands the conventions defined within a domain class and is used by GORM to perform ORM mapping.

o Book - A prototyped bean that will create a new instance of Book every time requested.

This bean is used to perform auto-wiring of domain classes when constructed with

the new operator.

Page 195: grails command main

FILTERS

Purpose

The filters plug-in sets up Grails' support for Filters.

Examples

An example filter:

class SecurityFilters {

def filters = {

loginCheck(controller:'*', action:'*') {

before = {

if(!session.user && !actionName.equals('login')) {

redirect(action:'login')

return false

}

}

}

}

}

Filter rule attributes: controller - controller matching pattern, by default is replaced

with . and a regex is compiled action - action matching pattern, by default is

replaced with . and a regex is compiled regex (true/false) - use regex syntax (don't

replace '' with '.') find (true/false) - rule matches with partial match (see

java.util.regex.Matcher.find()) invert (true/false) - invert the rule (NOT rule)

Description

Refer to the section on Filters in the Grails user guide which details how filters work.

Configured Spring Beans:

o filterInterceptor - An instance

of org.codehaus.groovy.grails.plugins.web.filters.CompositeInterceptor that

composes all the filters together into a single Spring Interceptor.

Configured Spring Beans given a filter called SecurityFilters:

o SecurityFiltersClass -

The org.codehaus.groovy.grails.web.filters.GrailsFiltersClass instance which aids in analyzing the conventions within the filter.

o SecurityFilters - A singleton reference to the filter itself to support auto-wiring into a

Filter

Page 196: grails command main

HIBERNATE

Purpose

The hibernate plug-in sets up GORM and Grails' Hibernate integration.

Examples

An example domain class:

class Book {

String title

Date releaseDate

Author author

}

Description

Refer to the section on GORM in the Grails user guide which details how to create Grails domain classes.

Configured Spring Beans:

o dialectDetector - An instance of

org.codehaus.groovy.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean that attempts to automatically detect the Hibernate Dialect which is used to communicate with the database.

o hibernateProperties - A map of Hibernate properties passed to the SessionFactory

o lobHandlerDetector - An instance of

org.codehaus.groovy.grails.orm.hibernate.support.SpringLobHandlerDetectorFactoryBean that attempts to automatically detect the Spring LobHandler to use based on the database.

o sessionFactory - An instance of the Hibernate SessionFactory class used by

the GORM infrastructure.

o transactionManager - An instance of

Spring's org.springframework.orm.hibernate3.HibernateTransactionManager class

o persistenceInterceptor - An instance

of org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor that abstracts away how persistence is used from the controller/view layer so that Grails can be used without GORM.

o openSessionInViewInterceptor - An instance

of org.codehaus.groovy.grails.orm.hibernate.support.GrailsOpenSessionInViewFilter that deals with Grails' Session management.

Page 197: grails command main

I18N

Purpose

The i18n plug-in sets up Grails' support for Internationalization.

Examples

An example messages.properties within the grails-app/i18n directory:

default.doesnt.match.message=Property [{0}] of class [{1}] with value [{2}]

does not match the required pattern [{3}]

default.invalid.url.message=Property [{0}] of class [{1}] with value [{2}]

is not a valid URL

default.invalid.creditCard.message=Property [{0}] of class [{1}] with value

[{2}] is not a valid credit card number

Description

Refer to the section on Internationalization in the Grails user guide which details how Grails' i18n support works.

Configured Spring Beans:

o messageSource - An instance the

Spring org.springframework.context.support.ReloadableResourceBundleMessageSource class which is used to resolve messages.

o localeChangeInterceptor - An instance of the

Spring org.springframework.web.servlet.i18n.LocaleChangeInterceptor class which is

used to switch locales using a lang request parameter.

o localeResolver - An instance of the

Spring org.springframework.web.servlet.i18n.CookieLocaleResolver class that is used to store the user locale in a cookie.

Page 198: grails command main

LOGGING

Purpose

The logging plug-in sets up Grails' support for Logging with Log4j.

Examples

Example log statements:

log.info "Configuration data source"

try {

..

}

catch(Exception e) {

log.error "Error: ${e.message}", e

}

Description

Refer to the section on Logging in the Grails user guide which details Grails' logging support.

Page 199: grails command main

SCAFFOLDING

Purpose

The scaffolding plug-in sets up Grails' support for CRUD via Scaffolding.

Examples

An example of enabling "dynamic" scaffolding:

class BookController {

def scaffold = true

}

Description

Refer to the section on Scaffolding in the Grails user guide which details how Grails' scaffolding support works.

Page 200: grails command main

SERVICES

Purpose

The services plug-in sets up Grails' support for Services.

Examples

An example service class in the grails-app/services directory:

class BookService {

Book[] getBooks() {

Book.list() as Book[]

}

}

Description

Refer to the section on Services in the Grails user guide which details how Grails' service support works.

Configured Spring Beans given a service class of BookService:

o BookServiceServiceClass -

The org.codehaus.groovy.grails.commons.GrailsServiceClass instance which understands the conventions defined within a services class.

o BookService - A bean configured according to the services'

scope: if the service is transactional then the type of the actual bean definition will beorg.springframework.transaction.interceptor.TransactionProxyFactoryBean.

Page 201: grails command main

SERVLETS

Purpose

The servlets plug-in enhances with Servlet API with new methods

Examples

Attributes from the request, session, and servletContext can be accessed with the de-reference operator:

class BookController {

def find = {

def findBy = params.findBy

def foo = request.foo

def loggedUser = session.logged_user

}

}

Page 202: grails command main

WEBFLOW

Purpose

The webflow plug-in sets up Grails' support for Spring Webflow

Examples

An example web flow:

class BookController {

def shoppingCartFlow = {

showCart {

on("checkout").to "enterPersonalDetails"

on("continueShopping").to "displayCatalogue"

}

displayCatalogue {

redirect(controller:"catalogue", action:"show")

}

displayInvoice()

}

}

Description

Refer to the section on Web Flow in the Grails user guide which details how Grails' web flow support works.

Configured Spring Beans:

o conversationManager - An instance of

the org.springframework.webflow.conversation.impl.SessionBindingConversatio

nManager that manages conversations in the session.

o executionListenerLoader - A Web

Flow org.springframework.webflow.execution.factory.StaticFlowExecutionListe

nerLoader that uses thehibernateConversationListener bean with flow execution

events to manage the Hibernate session.

o flowBuilderServices - An instance of

the org.springframework.webflow.engine.builder.support.FlowBuilderServices c

lass used to help the Flow engine locate services.

o flowExecutor - An instance of

the org.codehaus.groovy.grails.webflow.execution.GrailsFlowExecutorImpl that knows how to execute Grails flows based on flow execution keys.

o flowExecutionFactory - An instance of

the org.springframework.webflow.engine.impl.FlowExecutionImplFactory that

constructs flow executions.

o flowExecutionSnapshotFactory - An instance of

theorg.springframework.webflow.execution.repository.snapshot.SerializedFlow

ExecutionSnapshotFactory class that is used to create flow snapshots that can be

stored for resumption later on.

Page 203: grails command main

o flowExecutionRepository - An instance of

the org.springframework.webflow.execution.repository.impl.DefaultFlowExecut

ionRepository class that is used to store flows.

o flowRegistry - An instance of

the org.codehaus.groovy.grails.webflow.engine.builder.ControllerFlowRegistr

y class that stores persisted flows.

o flowScopeRegistrar - An instance of the Spring Web

Flow org.springframework.webflow.config.scope.ScopeRegistrar class which

registers the flow scopes with the ApplicationContext so that services can be scoped

using flow scopes such as flow, conversation and flash.

o hibernateConversationListener - An instance of the Web

Floworg.codehaus.groovy.grails.webflow.persistence.SessionAwareHibernateFlo

wExecutionListener class that manages the Hibernate session for the scope of a flow,

allowing atomic use of flows.

o viewFactoryCreator - An instance of

the org.springframework.webflow.mvc.builder.MvcViewFactoryCreator class used

to construct views

Page 204: grails command main

SERVICE USAGE

A service contains business logic that can be re-used across a Grails application. In

Grails a service is a class that ends in the convention "Service" and lives in the grails-

app/services directory. A service can be created with the create-service command:

grails create-service Book

Or via your favourite IDE or text editor.

class BookService {

Book[] getBooks() {

Book.list() as Book[]

}

}

Refer to the user guide topic on Services for more information

Page 205: grails command main

SCOPE

Purpose

Changes the scope of a service

Examples class BookService {

static scope = "session"

}

Description

By default services are "singleton" scoped which means that clients of a service only ever use a single instance (a singleton) of the service. This behaviour can be changed

by specifying a scope attribute with on the following values:

o prototype - A new service is created every time it is injected into another class

o request - A new service will be created per request

o flash - A new service will be created for the current and next request only

o flow - In web flows the service will exist for the scope of the flow

o conversation - In web flows the service will exist for the scope of the conversation. ie a

root flow and its sub flows

o session - A service is created for the scope of a user session

o singleton (default) - Only one instance of the service ever exists

See Scoped Services in the user guide for more information.

Page 206: grails command main

TRANSACTIONAL

Purpose

Enables transaction demarcation if set to true

Examples class BookService {

static transactional = true

}

Description

By default services have automatic transaction management such as propagation and so

on. By setting transactional to false you disable automatic Spring managed

transaction demarcation for every method in the service. When set to the true, The

propagation level of the transaction is by default set to PROPAGATION_REQUIRED.

You can also configure services using Spring's @Transactional annotation. See Declarative Transactions in the user guide for more information.

Page 207: grails command main

REQUEST

Purpose

The request object is an instance of the Servlet API's HttpServletRequest class

class BookController {

def list = {

log.info "User agent: " + request.getHeader("User-Agent")

render(view:actionName)

}

}

Description

The HttpServletRequest class is useful for, amongst other things, obtaining request headers, storing request scoped attributes and establishing information about the client. Refer to the Servlet API's javadocs for further information.

Grails enhances the HttpServletRequest instance by adding the following new

properties and methods:

o XML - An instance of XmlSlurper's GPathResult class that allows parsing of an incoming

XML request (useful for REST).

o JSON - An instance of Grails' JSONObject class that allows parsing of an incoming JSON

request (useful for JSON based REST).

o forwardURI - Useful for obtaining the current request URI since

the request objects requestURI property returns the original URI, not the matched one.

o get - Returns true if the current request is an HTTP GET request.

o post - Returns true if the current request is an HTTP POST request.

o each - Implementation of Groovy's each method for iterating over request attributes.

o find - Implementation of Groovy's default find method for searching request attributes.

o findAll - Implementation of Groovy's default findAll method for searching request

attributes.

o format - The request format, used for content negotiation.

The XML and JSON properties are useful for XML APIs and can be used to parse incoming

XML or JSON packages. For example given a request body of:

<book>

<title>The Stand</title>

</book>

This can be parsed trivially:

def title = request.XML?.book?.title

render "The Title is $title"

Request attributes which are normally accessible via the getAttribute can also be indexed into using the array index operator or de-reference operator:

def user = request['user']

request['user'] = 'John'

asset 'John' == request.user

Page 208: grails command main

RESPONSE

Purpose

The response object is an instance of the Servlet API's HttpServletResponse class

Examples class BookController {

def downloadFile = {

byte[] bytes = // read bytes

response.outputStream << bytes

}

}

Description

The Servlet API's HttpServletResponse class can be used within Grails to perform all

typical activities such as writing out binary data, writing directly to the response and sending error response codes to name but a few. Refer to the documentation on the HttpServletResponse class in the Servlet API for more information.

Grails also overrides the left shift operator on the response object making it easier to

write to the response writer:

response << "Hello World"

Page 209: grails command main

SERVLETCONTEXT

Purpose

The servletContext object is an instance of the Servlet API's ServletContext class.

Examples class BookController {

def doSomething = {

def input

try {

input = servletContext.getResourceAsStream("/WEB-

INF/myscript.groovy")

def result = new GroovyShell().evaluate(input.text)

render result

}

finally {

input.close()

}

}

}

Description

The Servlet API's ServletContext is useful for, amongst other things, storing global application attributes, reading local server resources and establishing information about the servlet container.

Application attributes which are normally accessible via the getAttribute can also be indexed into using the array index operator or de-reference operator:

def mySetting = servletContext["mySetting"]

servletContext["mySetting"] = "foo"

asset "foo" == servletContext.mySetting

Page 210: grails command main

SESSION

Purpose

The session object is an instance of the Servlet API's HttpSession class

Examples class UserController {

def logout = {

log.info "User agent: " + request.getHeader("User-Agent")

session.invalidate()

redirect(action:"login")

}

def login = {

}

}

Description

The HttpSession class is useful for associated session data with a client.

Session attributes which are normally accessible via the getAttribute can also be indexed into using the array index operator or de-reference operator:

def user = session["user"]

session["user"] = "John"

asset "John" == session.user

Page 211: grails command main

TAG LIBRARY USAGE

A tag library fulfills role of "view helper" in the Model View Controller (MVC) pattern and is responsible aiding GSP rendering. In Grails a tag library is a class that ends in the

convention "TagLib" and lives in the grails-app/taglib directory. A controller can be

created with the create-tag-lib command:

grails create-tag-lib format

Or via your favourite IDE or text editor.

class FormatTagLib {

def dateFormat = { attrs, body ->

out << new

java.text.SimpleDateFormat(attrs.format).format(attrs.value)

}

}

Each property in a tag library that takes two arguments is considered a tag. The first

argument attrs is the attributes of the tag whilst the second bodyargument is another

block or closure that can be invoked.

Refer to the user guide topic on Tag Libraries for more information.

Page 212: grails command main

ACTIONNAME

Purpose

Returns the name of the currently executing action

Examples class BookController {

def list = {

log.info "Executing action $actionName"

render(view:actionName)

}

}

Description

Returns the name of the currently executing action which is dictated by the URL mappings

Page 213: grails command main

CONTROLLERNAME

Purpose

Returns the name of the currently executing controller

Examples

class BookController {

def list = {

log.info "Executing within controller $controllerName"

render(view:actionName)

}

}

Description

Returns the name of the currently executing controller which is dictated by the URL mappings

Page 214: grails command main

FLASH

Purpose

A temporary storage map that stores objects within the session for the next request and the next request only, automatically clearing out the objects held there after the next request completes.

Examples

class BookController {

def index = {

flash.message = "Welcome!"

redirect(action:home)

}

def home = {}

}

Description

The flash object is essentially a map (a hash) which you can use to store key value pairs. These values are transparently stored inside the session and then cleared at the end of the next request.

This pattern allows you to use HTTP redirects (which is useful for redirect after post ) and retain values that can retrieved from the flash object.

Page 215: grails command main

PAGESCOPE

Purpose

A reference to the binding of the GSP that the tag library is being executed within. Allows access to variables set with the set tag and those passed to the page via the controller model.

Examples class BookTagLib {

def parent = { attrs, body ->

pageScope.parent = "John"

out << body()

}

def child = { attrs, body ->

out << "My parent is ${pageScope.parent}"

}

}

<g:parent>

<g:child /> // Outputs "My parent is John"

</g:parent>

Description

The pageScope variable contains a reference to the underlying model being manipulated

by the page. It can also be used to pass variables from parent to child tags.

Page 216: grails command main

PARAMS

Purpose

A mutable multi-dimensional map (hash) of request (CGI) parameters

Examples

To obtain a request parameter called id:

class BookController {

def show {

def book = Book.get(params.id)

}

}

To perform data binding (see Data Binding in the user guide):

def save = {

def book = new Book(params) // bind request parameters onto

properties of book

}

Description

The standard Servlet API provides access to parameters via

the HttpServletRequest object. Although Grails provides the same capability through

therequest object, it goes a bit further by providing a mutable map of request

parameters called params.

The params object can be indexed into via de-refrencing so given the

URL /hello?foo=bar you can obtain the value of foo as follows:

println params.foo

The params object can also be used to bind request parameters onto the properties of a domain class using either the constructor or the propertiesproperty:

def book = new Book(params)

book = Book.get(1)

book.properties = params

For further reading see Data Binding in the user guide.

Page 217: grails command main

REQUEST

Purpose

The request object is an instance of the Servlet API's HttpServletRequest class

Examples class BookController {

def list = {

log.info "User agent: " + request.getHeader("User-Agent")

render(view:actionName)

}

}

Description

The HttpServletRequest class is useful for, amongst other things, obtaining request headers, storing request scoped attributes and establishing information about the client. Refer to the Servlet API's javadocs for further information.

The additional methods added to the request object are documented in the Grails Servlet API reference guide

Page 218: grails command main

RESPONSE

Purpose

The response object is an instance of the Servlet API's HttpServletResponse class

Examples class BookController {

def downloadFile = {

byte[] bytes = // read bytes

response.outputStream << bytes

}

}

Description

The Servlet API's HttpServletResponse class can be used within Grails to perform all

typical activities such as writing out binary data, writing directly to the response and sending error response codes to name but a few. Refer to the documentation on the HttpServletResponse class in the Servlet API for more information.

The additional methods added to the response object are documented in the Grails Servlet API reference guide

Page 219: grails command main

SERVLETCONTEXT

Purpose

The servletContext object is an instance of the Servlet API's ServletContext class.

Examples class BookController {

def doSomething = {

def input

try {

input = servletContext.getResourceAsStream("/WEB-

INF/myscript.groovy")

def result = new GroovyShell().evaluate(input.text)

render result

}

finally {

input.close()

}

}

}

Description

The Servlet API's ServletContext is useful for, amongst other things, storing global application attributes, reading local server resources and establishing information about the servlet container.

Grails adds additional methods to the standard Servlet API's servletContext object. See

link for details.

Page 220: grails command main

SESSION

Purpose

The session object is an instance of the Servlet API's HttpSession class

Examples class UserController {

def logout = {

log.info "User agent: " + request.getHeader("User-Agent")

session.invalidate()

redirect(action:"login")

}

def login = {

}

}

Description

The HttpSession class is useful for associated session data with a client.

The additional methods added to the session object are documented in the Grails

Servlet API reference guide

Page 221: grails command main

ACTIONSUBMIT

Purpose

Creates a submit button that maps to a specific action, which allows you to have multiple submit buttons in a single form. Javascript event handlers can be added using the same parameter names as in HTML.

Examples <g:actionSubmit value="Update" />

<!--'Update' is action, label is 'Some update label'-->

<g:actionSubmit value="Some update label" action="Update" />

<!--label derived from message bundle-->

<g:actionSubmit value="${message(code:'label.update')}" action="Update" />

<g:actionSubmit value="Delete" />

<g:actionSubmit value="DeleteAll" onclick="return confirm('Are you

sure???')" />

Description

Attributes

o value (required) - The title of the button and name of action when not explicitly

defined.

o action (optional) - The name of the action to be executed, otherwise it is derived from

the value.

When you use a normal submit button inside a form, it is the form itself that determines what URL the request is sent to, and therefore what action is executed. However, this tag overrides that behaviour and determines which action is executed. Note that it is still the form that determines the target controller.

Due to the way that the tag works, you should not specify an action on the enclosing form unless it is completely necessary. If you do, the URL address in the browser is likely to include the name of the action specified by the form, not the one specified by

the actionSubmit tag. In such cases, it is probably a good idea to use custom URL

mappings.

URL Mappings

The implementation of the actionSubmit tag means that it does not sit entirely

comfortably with URL mappings, particularly the default one. The reason for this is that

URL mappings work on the URL of the request, but actionSubmit uses a parameter to

determine the action to execute. This means that there is a mismatch between any action name in the URL mapping, and the name of the actual action executed.

Take this simple case with the default URL mapping:

class UrlMappings {

static mappings = {

"/$controller/$action?/$id?"{

constraints {

// apply constraints here

}

}

}

}

and a GSP page containing this simple form:

Page 222: grails command main

<g:form controller="test">

<g:actionSubmit value="Submit" action="success"/>

</g:form>

The URL generated for the <form> element will either be ".../test" or ".../test/index"

(assuming "index" is the default action) depending on your version of Grails. Note that neither version includes "success" in the URL, and when you click on the submit button the URL in the browser will be without "success" too.

This isn't too much of a problem when the form URL does not include an action name, but if you have a version of Grails that appends the name of the default action, or you

specify an action in your <g:form> tag, then you should probably use a custom URL

mapping to hide the action name:

"/test/submit" {

controller = "test"

action = "index"

}

where the action specified in the mapping is either the default action of the controller,

or the action specified in the <g:form> tag.

Also note that this tag relies on the multipart resolver to be able to inspect parameters included with mulitpart requests. If you disable the resolver by setting grails.disableCommonsMultipart to true in Config.groovy, actionSubmit will not work.

Source

Show Source

Page 223: grails command main

ACTIONSUBMITIMAGE

Purpose

Creates a submit button using the input type="image" with the indicated value. Javascript event handlers can be added using the same parameter names as in HTML.

Examples <g:actionSubmitImage value="Update" action="update"

src="${resource(dir:'images',file:'update.gif')}"/>

Description

Attributes

o value - The title of the button and name of action when not explicitly defined

o src - The source of the image to use

o action (optional) - The name of the action to be executed

You cannot use multiple actionSubmitImage tags within the same form and have it work in Internet Explorer 6 or 7 unless you add some custom JavaScript. See this page for a bit more information and a workaround.

Page 224: grails command main

APPLYLAYOUT

Purpose

Applies the specified layout to either the body, a given template and an arbitrary URL allowing the development of "portlet" style applications and mashups

Examples <g:applyLayout name="myLayout" template="displaybook" collection="${books}"

/>

or

<g:applyLayout name="myLayout" url="http://www.google.com" />

or

<g:applyLayout name="myLayout">

The content to apply a layout to

</g:applyLayout>

Description

Attributes

o name - The name of the layout to apply

o url - The URL of the content to apply, could be an external URL

o template (optional) - The name of the template to apply

o bean (optional) - The bean to apply the template against

o model (optional) - The model to apply the template against as a java.util.Map

o collection (optional) - A collection of model objects to apply the template to

Source

Show Source

Page 225: grails command main

CHECKBOX

Purpose

Creates a checkbox form field. All the usual HTML elements apply.

Examples <g:checkBox name="myCheckbox" value="${true}" />

Description

Attributes

o name - The name of the checkbox

o value (optional) - The value of the checkbox

o checked (optional) - Expression if evaluates to true sets to checkbox to checked

The checkBox tag typically only requires the name and value attributes and will infer

whether the checkbox should be checked or not from the value. However, if you need to

override this behaviour the checked attribute can be used for fine grained control.

Source

Show Source

Page 226: grails command main

COLLECT

Purpose

Uses the Groovy JDK collect method to iterate over each element of the specified

object transforming the result using the expression in the closure

Examples Books titles:

<g:collect in="${books}" expr="it.title">

<p>Title: ${it}</p>

</g:collect>

Description

Attributes

o in - The object to iterative over

o expr - A GPath expression

Page 227: grails command main

COOKIE

Purpose

Obtains the value of a named cookie

Examples

Reading a cookie's value:

Hello <g:cookie name="myCookie" />

Or testing for existence:

<g:if test="${cookie(name:'myCookie')}">Hello</g:if>

Description

Attributes

o name - The name of the cookie

Source

Show Source

Page 228: grails command main

COUNTRY

Purpose

Renders the default English name for a given ISO3166_3 3-letter country code

Examples Country: <g:country code="${user.country}"/>

Supported countries: <g:country code="gbr"/>, <g:country code="deu"/>

Description

Uses the internal ISO3166_3 country code date that the selectCountry tag is based upon, to quickly render the name of a country given the code.

If you need to internationalized versions of the country names, you must define these in your message bundles and use the <g:message> tag instead.

Attributes

o code - The 3-letter lowercase ISO3166 country code

Source

Page 229: grails command main

COUNTRYSELECT

Purpose

Helper tag for creating HTML select boxes containing Country names.

Examples // create a select for all countries

<g:countrySelect name="user.country" value="${country}"

noSelection="['':'-Choose your age-']"/>

// create select from a list of ISO3166_3 country codes

<g:countrySelect name="user.country"

from="['gbr', 'usa', 'deu']"

value="${user?.country}"/>

// create country select with internationalized labels

// expected properties in messages.properties:

// countryname.gbr=My United Kingdom

// countryname.usa=Home of the brave

// countryname.deu=Germany

<g:countrySelect name="user.country" from="['gbr', 'usa', 'deu']

valueMessagePrefix="countryname" />

Description

This class renders a select box with one option for every ISO3166_3 country code, or for the list of country codes supplied in "from".

The 3-letter ISO codes are used in lowercase format.

Attributes

o from (optional) - The list or range to select from

o value (optional) - The current selected value that evaluates equals() to true for one of

the elements in the from list.

o default (optional) - The ISO code of the default country to display if "value" is not set

o noSelection (optional) - A single-entry map detailing the key and value to use for the

"no selection made" choice in the select box. If there is no current selection this will be shown as it is first in the list, and if submitted with this selected, the key that you provide will be submitted. Typically this will be blank - but you can also use 'null' in the case that you're passing the ID of an object

o valueMessagePrefix (optional) - By default the value "option" element will be the

internal English name of the country according to the ISO3166_3 standard. Setting this allows the value to be resolved from the I18n messages. The valueMessagePrefix will be suffixed with a dot ('.') and then the country code of the option to resolve the message. If the message could not be resolved, the prefix plus country code is presented.

Source

Show Source

Page 230: grails command main
Page 231: grails command main

CREATELINK

Purpose

Creates a link that can be used where necessary (for example in an href, javascript, ajax call etc.)

Examples

Example controller for an application called "shop":

class BookController {

static defaultAction="list"

def list = { [ books: Book.list( params ) ] }

def show = { [ book : Book.get( params['id'] ) ] }

}

Example usages for above controller:

<g:createLink action="show" id="1" /> == /shop/book/show/1

<g:createLink action="show" params="[foo: 'bar', boo: 'far']"/> ==

/shop/book/show?foo=bar&boo=far

<g:createLink controller="book" /> == /shop/book

<g:createLink controller="book" action="list" /> == /shop/book/list

<g:createLink url="[action:'list',controller:'book']" /> == /shop/book/list

<g:createLink controller="book" absolute="true"/> ==

http://portal.mygreatsite.com/book

<g:createLink controller="book" base="http://admin.mygreatsite.com"/> ==

http://admin.mygreatsite.com/book

<g:createLink controller = "book" action="list" params="[title:'The

Shining', author:'Stephen King', id:'1']"/> ==

/shop/book/list/1?title=The+Shining&author=Stephen+King

Example as a method call in GSP:

<a href="${createLink(action:'list')}">my link</a>

results in:

<a href="/shop/book/list">my link</a>

Description

Attributes

o action (optional) - The name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - The name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o fragment (optional) - The link fragment (often called anchor tag) to use

o mapping (optional) - The named URL mapping to use to rewrite the link

o params (optional) - A map containing URL query parameters

o url (optional) - A map containing the action,controller,id etc.

o absolute (optional) - If set to "true" will prefix the link target address with the value of

the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.

Page 232: grails command main

o base (optional) - Sets the prefix to be added to the link target address, typically an

absolute server URL. This overrides the behaviour of theabsolute property, if both are

specified.

Source

Show Source

Page 233: grails command main

CREATELINKTO

Deprecated: Use resource instead.

Purpose

Creates a link that can be used where necessary (for example in an href, javascript, ajax call etc.)

Examples

Example controller for an application called "shop":

Example usages for the "shop" app:

<g:createLinkTo dir="css" file="main.css" /> == /shop/css/main.css

<g:createLinkTo dir="css" file="main.css" absolute="true"/> ==

http://portal.mygreatsite.com/css/main.css

<g:createLinkTo dir="css" file="main.css"

base="http://admin.mygreatsite.com"/> ==

http://admin.mygreatsite.com/css/main.css

Example as a method call in GSP only:

<link type="text/css" href="${createLinkTo(dir:'css',file:'main.css')}" />

Results in:

<link type="text/css" href="/shop/css/main.css" />

Description

Attributes

o dir (optional) - the name of the directory within the grails app to link to

o file (optional) - the name of the file within the grails app to link to

o absolute (optional) - If set to "true" will prefix the link target address with the value of

the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.

o base (optional) - Sets the prefix to be added to the link target address, typically an

absolute server URL. This overrides the behaviour of theabsolute property, if both are

specified.

Source

Show Source

Page 234: grails command main

CURRENCYSELECT

Purpose

Helper tag for creating HTML selects for selecting from a list of currency symbols (eg. 'EUR', 'USD' etc.).

Examples <g:currencySelect name="myCurrency" value="${currency}" />

Description

Attributes

o from (optional) - The currency symbols to select from, defaults to the major ones if not

specified

o value (optional) - The currency value as the currency code. Defaults to the currency for

the current Locale if not specified

Source

Show Source

Page 235: grails command main

DATEPICKER

Purpose

Creates a date picker which renders as selects for the day,month,year,hour and second of the day.

Examples <g:datePicker name="myDate" value="${new Date()}"

noSelection="['':'-Choose-']"/>

<g:datePicker name="myDate" value="${new Date()}" precision="day"

years="${1930..1970}"/>

<g:datePicker name="myDate" value="${new Date()}" precision="day"

years="[1930, 1940, 1950, 1960, 1970]"/>

Description

Attributes

o name (required) - The name of the date picker field set

o value (optional) - The current value of the date picker; defaults to now if not specified

o precision (optional) - The desired granularity of the date to be rendered

o Valid values are 'year', 'month', 'day', 'hour', or 'minute'

o Defaults to 'minute' if not specified

o Uses default values for the non-rendered date components. Default values...

o month = January

o day = 1st day of the month

o hour = 00

o minute = 00

o noSelection (optional) - A single-entry map detailing the key and value to use for the

"no selection made" choice in the select box. If there is no current selection this will be shown as it is first in the list, and if submitted with this selected, the key that you provide will be submitted. Typically this will be blank.

o years (optional) - A list or range of years to display, in the order specified. i.e. specify

2007..1900 for a reverse order list going back to 1900. If this attribute is not specified, a range of years from the current year - 100 to current year + 100 will be shown.

Source

Show Source

Page 236: grails command main

EACH

Purpose

Uses the Groovy JDK each method to iterate over each element of the specified object.

Examples <g:each in="${books}">

<p>Title: ${it.title}</p>

<p>Author: ${it.author}</p>

</g:each>

With a named item:

<g:each var="book" in="${books}">

<p>Title: ${book.title}</p>

<p>Author: ${book.author}</p>

</g:each>

With a range literal - note how the literal must be enclosed in parentheses:

<ul>

<g:each var="i" in="${ (0..<100) }">

<li>Item ${i}</li>

</g:each>

</ul>

Another example, where a named item is necessary (otherwise the access to the title property will fail):

<g:each in="${itemList}" var="item">

<g:link action="show" id="${item.id}">${item.title}</g:link>

</g:each>

Using the status parameter to alternate the coloring of a table's rows:

<tbody>

<g:each status="i" in="${itemList}" var="item">

<!-- Alternate CSS classes for the rows. -->

<tr class="${ (i % 2) == 0 ? 'a' : 'b'}">

<td>${item.id?.encodeAsHTML()}</td>

<td>${item.parentId?.encodeAsHTML()}</td>

<td>${item.type?.encodeAsHTML()}</td>

<td>${item.status?.encodeAsHTML()}</td>

</tr>

</g:each>

</tbody>

Description

Attributes

1. in - The object to iterate over

2. status (optional) - The name of a variable to store the iteration index in. For the first

iteration this variable has a value of 0, for the next, 1, and so on. If this parameter is used, then var is required.

3. var (optional) - The name of the item, defaults to "it".

Note that var attribute must be specified when the iterator value is to be used from

within the body of a GSP Dynamic Tag, such as in<g:link>.

Page 237: grails command main

EACHERROR

Purpose

Loops through each error of the specified bean or model. If no arguments are specified it will go through all model attributes and check for errors.

Examples

Loop through each error in the "book" bean:

<g:eachError bean="${book}">

<li>${it}</li>

</g:eachError>

Loop through each error in the title field of the "book" bean:

<g:eachError bean="${book}" field="title">

<li>${it}</li>

</g:eachError>

Loop through each error in model:

<g:eachError model="${[book1:book1,book2:book2]}" field="title">

<li>${it}</li>

</g:eachError>

Loop through each error displaying its i18n message:

<g:eachError bean="${book}">

<li><g:message error="${it}"/></li>

</g:eachError>

Description

Attributes

o bean (optional) - The instance of the bean to check for errors

o model (optional) - The name of model, an map instance, to check for errors

o field (optional) - The field within the bean or model to check for errors for

Source

Show Source

Page 238: grails command main

ELSE

Purpose

The logical else tag

Examples <g:if test="${name == 'fred'}">

Hello Fred!

</g:if>

<g:else>

Hello ${name}! Do I know you?

</g:else>

Page 239: grails command main

ELSEIF

Purpose

The logical elseif tag

Examples <g:if test="${name == 'fred'}">

Hello Fred!

</g:if>

<g:elseif test="${name == 'bob'}">

Hello bob!

</g:elseif>

<g:elseif env="development">

Hello unknown developer!

</g:elseif>

Description

Attributes

o test - The expression to test

o env - An environment name

Page 240: grails command main

FIELDVALUE

Purpose

This tag will inspect a bean which has been the subject of data binding and obtain the value of the field either from the originally submitted value contained within the bean's errors object populating during data binding or from the value of a bean's property. Once the value is obtained it will be automatically HTML encoded.

Examples <g:fieldValue bean="${book}" field="title" />

// or as a method

<input type="text" value="${fieldValue(bean:book,field:'title')}" />

Description

Attributes

o bean (required) - The bean instance to inspect

o field (required) - The name of the field to obtain the value of

Source

Show Source

Page 241: grails command main

FINDALL

Purpose

Uses the Groovy JDK findAll method to iterate over each element of the specified object that match the GPath expression within the attribute "expr"

Examples Stephen King's Books:

<g:findAll in="${books}" expr="it.author == 'Stephen King'">

<p>Title: ${it.title}</p>

</g:findAll>

Description

Attributes

o in - The object to iterative over

o expr - A GPath expression

Page 242: grails command main

FORM

Purpose

Creates a form that submits to a controller, action, and/or id. Beyond what is below all the usual HTML attributes apply.

Examples

Example controller for an application called "shop":

class Book {

def list = { [ books: Book.list( params ) ] }

def show = { [ book : Book.get( params['id'] ) ] }

}

Example usages for above controller:

<g:form name="myForm" action="myaction" id="1">...</g:form>

results in:

<form action="/shop/book/myaction/1" method="post" name="myForm"

id="myForm" >...</form>

<g:form name="myForm" url="[action:'list',controller:'book']">...</g:form>

results in:

<form action="/shop/book/list" method="post" name="myForm" id="myForm"

>...</form>

<g:form action="show">...</g:form>

results in:

<form action="/shop/book/show" method="post" >...</form>

Description

Attributes

o action (optional) - The name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - The name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o fragment (optional) - The link fragment (often called anchor tag) to use

o mapping (optional) - The named URL mapping to use to rewrite the link

o params (optional) - A map containing URL query parameters

o url (optional) - A map containing the action,controller,id etc.

o absolute (optional) - If set to "true" will prefix the link target address with the value of

the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.

o base (optional) - Sets the prefix to be added to the link target address, typically an

absolute server URL. This overrides the behaviour of theabsolute property, if both are

specified.

o name (optional) - A value to use for both the name and id attribute of the form tag

Page 243: grails command main

o useToken (optional) - Set whether to send a token in the request to handle duplicate

form submissions. See Handling Duplicate Form Submissions

Source

Show Source

Page 244: grails command main

FORMREMOTE

Purpose

Creates a form tag that uses a remote uri to execute an ajax call serializing the form elements falling back to a normal form submit if javascript is not supported.

Examples

Example controller for an application called "shop":

class BookController {

def list = { [ books: Book.list( params ) ] }

def show = { [ book : Book.get( params['id'] ) ] }

}

Example usages for above controller:

<g:formRemote name="myForm" on404="alert('not found!')" update="updateMe"

url="[action:'show']">

Login: <input name="login" type="text"></input>

</g:formRemote>

<div id="updateMe">this div is updated by the form</div>

<g:formRemote name="myForm" update="updateMe"

url="[ controller: 'book', action: 'list', params: [ sort:

'title', order: 'desc' ]]">

Login: <input name="login" type="text"></input>

</g:formRemote>

<div id="updateMe">this div is updated by the form</div>

You can override both the form method and action to use when javascript is unavailable

by providing method and action attributes. This example will submit the form

to /<context>/book/oldList using a GET if javascript is unavailable:

<g:formRemote name="myForm" method="GET" action="${createLink(controller:

'book', action: 'oldList')}"

url="[ controller: 'book', action: 'list', params: [ sort:

'title', order: 'desc' ]]">

Login: <input name="login" type="text"></input>

</g:formRemote>

Description

Attributes

o url - The url to submit to as either a map (containing values for the controller, action,

id, and params) or a URL string

o action (optional) - The action to execute as a fallback, defaults to the url if non

specified

o update (optional) - Either a map containing the elements to update for 'success' or

'failure' states, or a string with the element to update in which cause failure events would be ignored

o before (optional) - The javascript function to call before the remote function call

o after (optional) - The javascript function to call after the remote function call

o asynchronous (optional) - Whether to do the call asynchronously or not (defaults to

true)

o method (optional) - The method to use the execute the call (defaults to "post")

Page 245: grails command main

Events

o onSuccess (optional) - The javascript function to call if successful

o onFailure (optional) - The javascript function to call if the call failed

o on_ERROR_CODE (optional) - The javascript function to call to handle specified error

codes (eg on404="alert('not found!')")

o onUninitialized (optional) - The javascript function to call the a ajax engine failed to

initialise

o onLoading (optional) - The javascript function to call when the remote function is

loading the response

o onLoaded (optional) - The javascript function to call when the remote function is

completed loading the response

o onComplete (optional) - The javascript function to call when the remote function is

complete, including any updates

Source

Show Source

Page 246: grails command main

FORMATBOOLEAN

Purpose

Outputs the given boolean as the specified text label.

Examples <g:formatBoolean boolean="${myBoolean}" />

<g:formatBoolean boolean="${myBoolean}" true="True!" false="False!" />

Description

Outputs the given boolean as the specified text label. If the <code>true</code> and <code>false</code> option are not given, then the boolean is output using the default label.

Attributes:

boolean - the boolean to output true (optional) - text label for boolean true value

. boolean.true or default.boolean.true key is looked up from the Message Source /

ResourceBundle (i18n/*.properties) if this attribute is not given. false (optional) - text

label for boolean false value . boolean.false ordefault.boolean.false key is looked

up from the Message Source / ResourceBundle (i18n/*.properties) if this attribute is not given.

Source

Show Source

Page 247: grails command main

FORMATDATE

Purpose

Allows the formatting of java.util.Date instances using the same patterns defined by

the SimpleDateFormat class.

Examples <g:formatDate format="yyyy-MM-dd" date="${date}"/>

<g:formatDate date="${date}" type="datetime" style="MEDIUM"/>

<g:formatDate date="${date}" type="datetime" style="LONG"

timeStyle="SHORT"/>

<g:formatDate date="${date}" type="time" style="SHORT"/>

Description

Attributes

o date (required) - The date object to format

o format (optional) - The formatting pattern to use for the date, see SimpleDateFormat

o formatName (optional) - Look up format from the default MessageSource /

ResourceBundle (i18n/*.properties file) with this key. If format andformatName are

empty, format is looked up with 'default.date.format' key. If the key is missing,

'yyyy-MM-dd HH:mm:ss z' formatting pattern is used.

o type (optional) - The type of format to use for the date /

time. format or formatName aren't used when type is specified. Possible values: 'date' -

shows only date part, 'time' - shows only time part, 'both'/'datetime' - shows date and time

o timeZone (optional) - Sets the time zone for formatting. See TimeZone class.

o locale (optional) - Force the locale for formatting.

o style (optional) - Use default date/time formatting of the country specified by the

locale. Possible values: SHORT (default), MEDIUM, LONG, FULL . See DateFormat for explanation.

o dateStyle (optional) - Set separate style for the date part.

o timeStyle (optional) - Set separate style for the time part.

Source

Show Source

Page 248: grails command main

FORMATNUMBER

Purpose

Allows the formatting of numbers using the same patterns defined by the DecimalFormat class. Supports also attributes that are used in the JSTL formatNumber tag.

Examples <g:formatNumber number="${myNumber}" format="\\$###,##0" />

Example of formatting an EUR currency amount:

<g:formatNumber number="${myCurrencyAmount}" type="currency"

currencyCode="EUR" />

Example of formatting a USD currency amount:

<g:formatNumber number="${myCurrencyAmount}" type="currency"

currencyCode="USD" />

For USD, the currency symbol will be based on the locale of the request. For the

"en_US" locale, the result is "$123.45" and for "fi_FI" locale, the formatting is "123,45

USD". The formatting rules come from the java.util.Currency class.

Example of left padding a number with zeros:

<g:formatNumber number="${myNumber}" type="number" minIntegerDigits="9" />

Example of formatting a number showing 2 fraction digits:

<g:formatNumber number="${myNumber}" type="number" maxFractionDigits="2" />

Example of formatting a number showing 2 fraction digits, rounding with RoundingMode.HALF_DOWN:

<g:formatNumber number="${myNumber}" type="number" maxFractionDigits="2"

roundingMode="HALF_DOWN" />

Description

Attributes

o number (required) - The number object to formate

o format (optional) - The formatting pattern to use for the number, see DecimalFormat

o formatName (optional) - Look up format from the default MessageSource /

ResourceBundle (i18n/.properties file) with this key.Look upformat from the

default MessageSource / ResourceBundle (i18n/.properties file) with this key.

If format and formatName are empty,format is looked up with

'default.number.format' key. If the key is missing, '0' formatting pattern is used.

o type (optional) - The type of formatter to use: 'number', 'currency' or 'percent'

. format or formatName aren't used when type is specified.

o locale (optional) - Override the locale of the request , String or java.util.Locale value

o groupingUsed (optional) - Set whether or not grouping will be used in this format.

o minIntegerDigits (optional) - Sets the minimum number of digits allowed in the

integer portion of a number.

Page 249: grails command main

o maxIntegerDigits (optional) - Sets the maximum number of digits allowed in the

integer portion of a number.

o minFractionDigits (optional) - Sets the minimum number of digits allowed in the

fraction portion of a number.

o maxFractionDigits (optional) - Sets the maximum number of digits allowed in the

fraction portion of a number.

o currencyCode (optional) - The standard currency code ('EUR', 'USD', etc.), uses

formatting settings for the currency. type='currency' attribute is recommended.

o currencySymbol (optional) - Force the currency symbol to some symbol, recommended

way is to use currencyCode attribute instead (takes symbol information

from java.util.Currency)

o roundingMode (optional) - Sets the RoundingMode used in this DecimalFormat. Usual

values: HALF_UP, HALF_DOWN. If roundingMode is UNNECESSARY and ArithemeticException raises, the original number formatted with default number formatting will be returned.

Source

Show Source

Page 250: grails command main

GREP

Purpose

Uses the Groovy JDK grep method to iterate over each element of the specified object that match the specified "filter" attribute. The filter can be different instances such as classes, regex patterns etc.

Examples Stephen King's non-fiction Books:

<g:grep in="${books}" filter="NonFictionBooks.class">

<p>Title: ${it.title}</p>

</g:grep>

<g:grep in="${books.title}" filter="~/.*Groovy.*/">

<p>Title: ${it}</p>

</g:grep>

Description

Attributes

o in - The object to iterative over

o filter - The filter instance such as a class, regular expression or anything that

implements isCase

Page 251: grails command main

HASERRORS

Purpose

Checks whether a bean, request scope, or model reference has any errors and if it does invokes the body of the tag. Typically used in conjunction with either eachError or renderErrors

Examples

Checks whether there are any errors for any bean throughout the request scope:

<g:hasErrors>

<g:eachError><p>${it.defaultMessage}</p></g:eachError>

</g:hasErrors>

Checks whether there are any errors for the specified bean

<g:hasErrors bean="${book}">

<g:eachError><p>${it.defaultMessage}</p></g:eachError>

</g:hasErrors>

Checks whether there are any errors for the field "title" of the specified "book" bean:

<g:hasErrors bean="${book}" field="title">

<div class="errors">

<g:renderErrors bean="${book}" field="title" as="list" />

</div>

</g:hasErrors>

As a method call in GSP only. In this case we check for a field error on a particular field and set a CSS class on the surround div thus allowing us to highlight the error with a red border for example:

<div class="prop ${hasErrors(bean:user,field:'login', 'errors')}">

<label for="login"><input type="text" name="login" />

</div>

Checking for errors inside a nested object:

<div class="prop ${hasErrors(bean:parent, field:'child.name', 'errors')}">

<label for="child.name"><input type="text" name="child.name"

value="${fieldValue(bean:parent,field:'child.name'} />

</div>

Description

Attributes

o bean (optional) - The bean to check for errors

o model (optional) - The name of the model reference to check for errors

o field (optional) - Check if a field of the bean or model reference has errors

Source

Show Source

Page 252: grails command main

HEADERS

Purpose

Obtains the value of a named header

Examples

Reading a header's value:

Format? <g:header name="Content-Type" />

Or testing for existence:

<g:if test="${header(name:'User-Agent')}">Hello</g:if>

Description

Attributes

o name - The name of the header

Source

Show Source

Page 253: grails command main

HIDDENFIELD

Purpose

Creates a input of type 'hidden' (a hidden field). All the usual HTML elements apply.

Examples <g:hiddenField name="myField" value="myValue" />

Description

Attributes

o name (required) - The name of the text field

o value (optional) - The value of the text field

Source

Show Source

Page 254: grails command main

IF

Purpose

The logical if tag to switch on an expression and/or current environment.

Examples <g:if test="${name == 'fred'}">

Hello ${name}!

</g:if>

<g:if env="development">

Dev mode - debug: $someDebug

</g:if>

<g:if env="production" test="${cacheEnabled}">

$cache.getContent('1234')

</g:if>

Description

Attributes

o test - The expression to test

o env - An environment name

At least one of the attributes must be supplied. If both are supplied, they are combined using AND.

Page 255: grails command main

INCLUDE

Purpose

Includes the response of another controller/action or view in the current response

Examples

Example controller for an application called "shop":

class BookController {

def list = { [ books: Book.list( params ) ] }

def show = { [ book : Book.get( params['id'] ) ] }

}

Example usages for above controller:

<g:include action="show" id="1" />

<g:include action="show" id="${currentBook.id}" />

<g:include controller="book" />

<g:include controller="book" action="list" />

<g:include action="list"

params="[sort:'title',order:'asc',author:currentBook.author]" />

Example as a method call in controllers, tag libraries or GSP:

def content = g.include(action:'list',controller:'book')

Description

Attributes

o action (optional) - the name of the action to use in the include

o controller (optional) - the name of the controller to use in the include

o id (optional) - the id to use in the include

o view (optional) - The name of the view to use in the include

o params (optional) - a map containing request parameters

o model (optional) - Any request attributes (the model) to pass to the view to be included

Source

Show Source

Page 256: grails command main

JAVASCRIPT

Purpose

Allows inclusion of javascript libraries and scripts as well a shorthand for inline Javascript

Examples // actually imports '/app/js/myscript.js'

<g:javascript src="myscript.js" />

// imports all the necessary js for the scriptaculous library

<g:javascript library="scriptaculous" />

<g:javascript>alert('hello')</g:javascript>

Description

Attributes

o contextPath (optional) - the context path to use (relative to the application context

path). Defaults to "" or path to the plugin for a plugin view or template.

o library (optional) - The name of the library to include. Either "prototype",

"scriptaculous", "yahoo" or "dojo"

o src (optional) - The name of the javascript file to import. Will look in /app/js dir

o base (optional - Since 0.6) - specifies the full base url to prepend to the library name

o plugin (optional) - The plugin to look for the javascript in

Source

Show Source

Page 257: grails command main

JOIN

Purpose

Uses the Groovy JDK join method to concatenate the toString() representation of each item in this collection with the given separator.

Examples <g:join in="['Grails', 'Groovy', 'Gradle']" delimiter="_"/>

That would result in output like this:

Grails_Groovy_Gradle

Description

Attributes

1. in - The collection to iterate over

2. delimiter (optional) - The value of the delimiter to use during the join. If no delimiter

is specified then ", " (a comma followed by a space) will be used as the delimiter.

Show Source

Page 258: grails command main

LAYOUTBODY

Purpose

Used in layouts to output the contents of the body tag of the decorated page.

Examples

Example decorated page:

<html>

<head>

<meta name="layout" content="myLayout" />

<script src="myscript.js" />

</head>

<body>Page to be decorated</body>

</html>

Example decorator layout:

<html>

<head>

<script src="global.js" />

<g:layoutHead />

</head>

<body><g:layoutBody /></body>

</html>

Results in:

<html>

<head>

<script src="global.js" />

<script src="myscript.js" />

</head>

<body>Page to be decorated</body>

</html>

Source

Show Source

Page 259: grails command main

LAYOUTHEAD

Purpose

Used in layouts to output the contents of the head tag of the decorated page. Equivalent to the SiteMesh <decorator:head /> tag.

Examples

Example decorated page:

<html>

<head>

<meta name="layout" content="myLayout" />

<script src="myscript.js" />

</head>

<body>Page to be decorated</body>

</html>

Example decorator layout:

<html>

<head>

<script src="global.js" />

<g:layoutHead />

</head>

<body><g:layoutBody /></body>

</html>

Results in:

<html>

<head>

<script src="global.js" />

<script src="myscript.js" />

</head>

<body>Page to be decorated</body>

</html>

Source

Show Source

Page 260: grails command main

LAYOUTTITLE

Purpose

Used in layouts to output the contents of the title tag of the decorated page. Equivalent to the SiteMesh <decorator:title /> tag.

Examples

Example decorated page:

<html>

<head>

<title><g:layoutTitle default="Some Title" /></title>

<script src="global.js" />

<g:layoutHead />

</head>

<body><g:layoutBody /></body>

</html>

Results in:

<html>

<head>

<title>Hello World!</title>

<script src="global.js" />

<script src="myscript.js" />

</head>

<body>Page to be decorated</body>

</html>

Source

Show Source

Page 261: grails command main

LINK

Purpose

Creates an html anchor tag with the href set based on the parameters specified.

Examples

Example controller for an application called "shop":

class BookController {

def list = { [ books: Book.list( params ) ] }

def show = { [ book : Book.get( params['id'] ) ] }

}

Example usages for above controller:

<g:link action="show" id="1">Book 1</g:link>

<g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>

<g:link controller="book">Book Home</g:link>

<g:link controller="book" action="list">Book List</g:link>

<g:link url="[action:'list',controller:'book']">Book List</g:link>

<g:link action="list"

params="[sort:'title',order:'asc',author:currentBook.author]">

Book List

</g:link>

<g:link controller="book" absolute="true">Book Home</g:link>

<g:link controller="book" base="http://admin.mygreatsite.com">Book

Home</g:link>

Example as a method call in GSP only:

<%= link(action:'list',controller:'book') { 'Book List' }%>

Results in:

<a href="/shop/book/list">Book List</a>

Description

Attributes

o action (optional) - the name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - the name of the controller to use in the link, if not specified the

current controller will be linked

o elementId (optional) - this value will be used to populate the id attribute of the

generated href

o id (optional) - the id to use in the link

o fragment (optional) - The link fragment (often called anchor tag) to use

o mapping (optional) - The named URL mapping to use to rewrite the link

o params (optional) - a map containing request parameters

o url (optional) - a map containing the action, controller, id etc.

o absolute (optional) - If set to "true" will prefix the link target address with the value of

the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.

Page 262: grails command main

o base (optional) - Sets the prefix to be added to the link target address, typically an

absolute server URL. This overrides the behaviour of theabsolute property, if both are

specified.

Source

Show Source

Page 263: grails command main

LOCALESELECT

Purpose

Creates a select to select from a list of available locales

Examples // create a locale select

<g:localeSelect name="myLocale" value="${locale}" />

Description

Attributes

o name - The name to be used for the select box

o value (optional) - The set locale, defaults to the current request locale if not specified

Source

Show Source

Page 264: grails command main

MESSAGE

Purpose

Resolves a message from the given code or error. Normally used in conjunction with eachError. O

Examples

Loop through each error and output the message:

<g:eachError bean="${book}">

<li><g:message error="${it}" /></li>

</g:eachError>

Note that this is typically used for built-in Grails messages, rather than user application messages. For user application messages, use the code or message parameters, as

illustrated below.

Output a message for a specific known code:

<g:message code="my.message.code" />

Output a message for a compatible object.

<g:message message="${myObj}" />

Note that objects passed to the message parameter must implement the

org.springframework.context.MessageSourceResolvable interface.

Description

Attributes

o error (optional) - The error to resolve the message for. Used for built-in Grails

messages.

o code (optional) - The code to resolve the message for. Used for custom application

messages.

o message (optional) - The object to resolve the message for. Objects must implement

org.springframework.context.MessageSourceResolvable.

o default (optional) - The default message to output if the error or code cannot be found

in messages.properties.

o args (optional) - A list of argument values to apply to the message, when code is used.

o encodeAs (optional - 0.6+) - The name of a codec to apply, i.e. HTML, JavaScript, URL

etc

One of either the error attribute, the code attribute or the message attribute is

required. Messages are resolved from the grails-

app/i18n/messages.properties bundle. See also Internationalization.

For a more complex example, to output your own message with parameters and a default message, you might use the following code from your controller:

flash.message = "book.delete.message"

flash.args = [ "The Stand" ]

flash.default = "book deleted"

You would then specify the following in messages.properties:

book.delete.message="Book {0} deleted."

Page 265: grails command main

and specify the following from your view:

<g:message code="${flash.message}" args="${flash.args}"

default="${flash.default}"/>

Which would result in the output "Book The Stand deleted." If you had misnamed the

message or not specified it in messages.properties, your default message of "book

deleted" would be output.

Source

Show Source

Page 266: grails command main

META

Purpose

Renders application metadata properties.

Examples Version <g:meta name="app.version"/>

Built with Grails <g:meta name="app.grails.version"/>

Description

Meta properties come from the application.properties file, and among other things

contain the application's version and the grails version it requires. It can be used to expose some invariant data about your application at runtime. See the Application Metadata section for more details.

Attributes

o name - The name of the metadata property to retrieve, for example "app.version"

Source

Page 267: grails command main

PAGEPROPERTY

Purpose

Used in layouts to output the contents a property of the decorated page. Equivalent to the SiteMesh <decorator:getProperty/> tag.

Examples

Example decorated page:

<html>

<head>

<meta name="layout" content="myLayout" />

<script src="myscript.js" />

</head>

<body onload="alert('hello');">Page to be decorated</body>

</html>

Example decorator layout:

<html>

<head>

<script src="global.js" />

<g:layoutHead />

</head>

<body onload="${pageProperty(name:'body.onload')}"><g:layoutBody

/></body>

</html>

Results in:

<html>

<head>

<script src="global.js" />

<script src="myscript.js" />

</head>

<body onload="alert('hello');">Page to be decorated</body>

</html>

Source

Show Source

Page 268: grails command main

PAGINATE

Purpose

Creates next/previous buttons and a breadcrumb trail to allow pagination of results

Examples

Example domain class:

class Book {

String title

String author

}

Example controller:

class BookController {

def list = {

[books: Book.list(params)]

}

}

Paginate code:

<g:paginate controller="book" action="list" total="${Book.count()}" />

or

<g:paginate next="Forward" prev="Back"

maxsteps="0" controller="book"

action="list" total="${Book.count()}" />

Description

Attributes

o total (required) - The total number of results to paginate

o action (optional) - the name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - the name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o params (optional) - A map containing request parameters

o prev (optional) - The text to display for the previous link (defaults to "Previous" as

defined by default.paginate.prev property in I18n messages.properties)

o next (optional) - The text to display for the next link (defaults to "Next" as defined by

default.paginate.next property in I18n messages.properties)

o max (optional) - The number of records displayed per page (defaults to 10). Used ONLY

if params.max is empty

o maxsteps (optional) - The number of steps displayed for pagination (defaults to 10).

Used ONLY if params.maxsteps is empty

o offset (optional) - Used ONLY if params.offset is empty

Source

Show Source

Page 269: grails command main
Page 270: grails command main

PASSWORDFIELD

Purpose

Creates a input of type 'password' (a password field). An implicit "id" attribute is given the same value as name unless you explicitly specify one. All the usual HTML elements apply beyond the below:

Examples <g:passwordField name="myPasswordField" value="${myPassword}" />

Description

Attributes

o name (required) - The name of the password field

o value (optional) - The value of the password field

Source

Show Source

Page 271: grails command main

RADIO

Purpose

Helper tag for a radio button

Examples <g:radio name="myGroup" value="1"/>

<g:radio name="myGroup" value="2" checked="true"/>

results in:

<input type="radio" name="myGroup" value="1" />

<input type="radio" name="myGroup" checked="checked" value="2" />

Description

Attributes

o value (required) - The value of the radio button

o name (required) - The name of the radio button

o checked (optional) - boolean to indicate that the radio button should be checked

Source

Show Source

Page 272: grails command main

RADIOGROUP

Purpose

Helper tag for creating radio button groups

Examples <g:radioGroup name="myGroup" values="[1,2,3]" value="1" >

<p><g:message code="${it.label}" />: ${it.radio}</p>

</g:radioGroup>

results in:

<p>Radio 1: <input type="radio" name="myGroup" value="1" checked="checked"

/></p>

<p>Radio 2: <input type="radio" name="myGroup" value="2" /></p>

<p>Radio 3: <input type="radio" name="myGroup" value="3" /></p>

<g:radioGroup name="lovesGrails" labels="['Yes!','Of course!','Always!']"

values="[1,2,3]" >

<p>${it.label} ${it.radio}</p>

</g:radioGroup>

results in:

<p>Yes! <input type="radio" name="lovesGrails" value="1" /></p>

<p>Of course! <input type="radio" name="lovesGrails" value="2" /></p>

<p>Always! <input type="radio" name="lovesGrails" value="3" /></p>

Description

The body of the tag contains the GSP to render for each value. The two following variables are provided for use:

o it.label - the label for the current value

o it.radio - the radio button <input> tag for the current value

Attributes

o name (required) - The name of the group

o values (required) - The list values for the radio buttons

o value (optional) - The current selected value

o labels (optional) - Labels for each value contained in the values list. If this is ommitted

the label property on the iterator variable (see below) will default to 'Radio ' + value.

Source

Page 273: grails command main

REMOTEFIELD

Purpose

Creates a text field that sends its value to a remote link when it changes. By default the parameter name sent is called 'value', this can be changed by specifying a 'paramName' attribute.

Examples

Example controller for an application called "shop":

class BookController {

def changeTitle = {

def b = Book.get(params.id)

b.title = params.value

b.save()

}

}

Example usages for above controller:

<g:remoteField action="changeTitle" update="titleDiv" name="title"

value="${book?.title}"/>

<div id="titleDiv">I'm updated with the new title!</div>

Description

Attributes

o name (required) - the name of the field

o value (optional) - The initial value of the field

o paramName (optional) - The name of the parameter send to the server

o action (optional) - the name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - the name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o update (optional) - Either a map containing the elements to update for 'success' or

'failure' states, or a string with the element to update in which cause failure events would be ignored

o before (optional) - The javascript function to call before the remote function call

o after (optional) - The javascript function to call after the remote function call

o asynchronous (optional) - Whether to do the call asynchronously or not (defaults to

true)

o method (optional) - The method to use the execute the call (defaults to "post")

Events

o onSuccess (optional) - The javascript function to call if successful

o onFailure (optional) - The javascript function to call if the call failed

Page 274: grails command main

o on_ERROR_CODE (optional) - The javascript function to call to handle specified error

codes (eg on404="alert('not found!')")

o onUninitialized (optional) - The javascript function to call the a ajax engine failed to

initialise

o onLoading (optional) - The javascript function to call when the remote function is

loading the response

o onLoaded (optional) - The javascript function to call when the remote function is

completed loading the response

o onComplete (optional) - The javascript function to call when the remote function is

complete, including any updates

Source

Show Source

Page 275: grails command main

REMOTEFUNCTION

Purpose

Creates a remote javascript function that can be assigned to a DOM event to call the remote method

Examples

Example controller for an application called shop:

class BookControlller {

def list = {

[ books: Book.list( params ) ]

}

def show = {

[ book : Book.get( params['id'] ) ]

}

def bookByName = {

[ book : Book.findByName( params.bookName ) ] }

}

Example usages for above controller:

$('mydiv').onclick = <g:remoteFunction action="show" id="1" />

Example as a method call in GSP only:

<select

onchange="${remoteFunction(action:'bookByName',update:[success:'great',

failure:'ohno'], params:'\'bookName=\' + this.value' )}">

<option>first</option>

<option>second</option>

</select>

Example changing the asynchronous option to false:

<select from="[1,2,3,4,5]" onchange="${remoteFunction(action:'bookByName',

update:[success:'great', failure:'ohno'], options=[asynchronous:false]}" />

Description

Attributes

o action (optional) - the name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - the name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o update (optional) - Either a map containing the elements to update for 'success' or

'failure' states, or a string with the element to update in which cause failure events would be ignored

o before (optional) - The javascript function to call before the remote function call

o after (optional) - The javascript function to call after the remote function call

o asynchronous (optional) - Whether to do the call asynchronously or not (defaults to

true, specified in 'options' array)

o method (optional) - The method to use the execute the call (defaults to "post", specified

in 'options' array)

Page 276: grails command main

Events

o onSuccess (optional) - The javascript function to call if successful

o onFailure (optional) - The javascript function to call if the call failed

o on_ERROR_CODE (optional) - The javascript function to call to handle specified error

codes (eg on404="alert('not found!')")

o onUninitialized (optional) - The javascript function to call the a ajax engine failed to

initialise

o onLoading (optional) - The javascript function to call when the remote function is

loading the response

o onLoaded (optional) - The javascript function to call when the remote function is

completed loading the response

o onComplete (optional) - The javascript function to call when the remote function is

complete, including any updates

Source

Show Source

Page 277: grails command main

REMOTELINK

Purpose

Creates a link that calls a remote function when clicked

Examples

Example controller for an application called shop:

class BookControlller {

def list = {

[ books: Book.list( params ) ]

}

def show = {

[ book : Book.get( params['id'] ) ]

}

def bookByName = {

[ book : Book.findByName( params.bookName ) ] }

}

Example usages for above controller:

<g:remoteLink action="show" id="1">Test 1</g:remoteLink>

<g:remoteLink action="show" id="1"

update="[success:'success',failure:'error']"

on404="alert('not found');">Test 2</g:remoteLink>

<g:remoteLink action="show" id="1" update="success"

onLoading="showSpinner();">Test 3</g:remoteLink>

<g:remoteLink action="show" id="1" update="success"

params="[sortBy:'name',offset:offset]">Test 4</g:remoteLink>

As a method call in GSP:

my link = <%= remoteLink( action:'show', id:1,

update:'success', onFailure:'showError();' )

{ "this is the link body" } %>

Description

Attributes

o action (optional) - the name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - the name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o fragment (optional) - The link fragment (often called anchor tag) to use

o mapping (optional) - The named URL mapping to use to rewrite the link

o params (optional) - a map containing request parameters

o update (optional) - Either a map containing the elements to update for 'success' or

'failure' states, or a string with the element to update in which case failure events would be ignored

o before (optional) - The javascript function to call before the remote function call

Page 278: grails command main

o after (optional) - The javascript function to call after the remote function call

o asynchronous (optional) - Whether to do the call asynchronously or not (defaults to

true)

o method (optional) - The method to use the execute the call (defaults to "post")

Events

o onSuccess (optional) - The javascript function to call if successful

o onFailure (optional) - The javascript function to call if the call failed

o on_ERROR_CODE (optional) - The javascript function to call to handle specified error

codes (eg on404="alert('not found!')"). With Prototype, this prevents execution of onSuccess and onFailure.

o onUninitialized (optional) - The javascript function to call the a ajax engine failed to

initialise

o onLoading (optional) - The javascript function to call when the remote function is

loading the response

o onLoaded (optional) - The javascript function to call when the remote function is

completed loading the response

o onComplete (optional) - The javascript function to call when the remote function is

complete, including any updates

Source

Show Source

Page 279: grails command main

RENDER

Purpose

Applies an inbuilt or user defined Groovy template against a model so that templates can be re-used for lists or instance or a single instance

Examples

Example domain class:

class Book {

String title

String author

}

Example template:

<p>${it.title}</p>

<p>${it.author}</p>

This template can now be re-used whether you have a list of books or a single book. For a list the template will be repeated for each instance:

<g:render template="displaybook" collection="${books}" />

or

<g:render template="displaybook" bean="${book}" />

or you could create a template that handles a certain type of model. For example the template below:

<p><%= book.title %></p>

<p><%= author.fullName %></p>

Could be used with the model as below. The disadvantage of this technique however is that the template is less re-usable

<g:render template="displaybook" model="['book':book,'author':author]" />

It is also possible to define the name of the variable to be used by the template in the render tag:

Example template:

<p>${myBook.title}</p>

<p>${myBook.author}</p>

Example render tag call for the above template

<g:render template="displaybook" collection="${books}" var="myBook"/>

Description

Note that if the value of the template attribute starts with a '/' it will be resolved relative to the views folder. This is useful for sharing templates between views. Without the leading '/' it will be first be resolved relative to the current controller's view folder then, failing that, the top level views folder. In either case the template file must be named with a leading underscore ('_') but referenced in the template attribute without that underscore or the '.gsp' suffix.

Attributes

o contextPath (optional) - the context path to use (relative to the application context

path). Defaults to "" or path to the plugin for a plugin view or template.

Page 280: grails command main

o template (required) - The name of the template to apply

o bean (optional) - The bean to apply the template against

o model (optional) - The model to apply the template against as a java.util.Map

o collection (optional) - A collection of model objects to apply the template to

o var (optional) - The variable name of the bean to be referenced in the template

o plugin (optional) - The plugin to look for the template in

See render in the user guide for more information.

Source

Page 281: grails command main

RENDERERRORS

Purpose

Allows rendering of errors in different formats (at the moment only an HTML list is implemented )

Examples

Render a list for the "book" bean:

<g:renderErrors bean="${book}" as="list" />

Render a list for the title field of the "book" bean:

<g:renderErrors bean="${book}" as="list" field="title"/>

Description

Attributes

o as (optional) - What to render it as current options are "list". Defaults to "list" if not

specified.

o bean (optional) - The name of the bean to check for errors

o model (optional) - The name of model, an map instance, to check for errors

o field (optional) - The field within the bean or model to check for errors for

Source

Show Source

Page 282: grails command main

RESOURCE

Purpose

Creates a link that can be used where necessary (for example in an href, javascript, ajax call etc.)

Examples

Example controller for an application called "shop":

Example usages for the "shop" app:

<g:resource dir="css" file="main.css" /> == /shop/css/main.css

<g:resource dir="css" file="main.css" absolute="true"/> ==

http://portal.mygreatsite.com/css/main.css

<g:resource dir="css" file="main.css" base="http://admin.mygreatsite.com"/>

== http://admin.mygreatsite.com/css/main.css

Example as a method call in GSP only:

<link type="text/css" href="${resource(dir:'css',file:'main.css')}" />

Results in:

<link type="text/css" href="/shop/css/main.css" />

Description

Attributes

o base (optional) - Sets the prefix to be added to the link target address, typically an

absolute server URL. This overrides the behaviour of theabsolute property, if both are

specified.x≈

o contextPath (optional) - the context path to use (relative to the application context

path). Defaults to "" or path to the plugin for a plugin view or template.

o dir (optional) - the name of the directory within the grails app to link to

o file (optional) - the name of the file within the grails app to link to

o absolute (optional) - If set to "true" will prefix the link target address with the value of

the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.

o plugin (optional) - The plugin to look for the resource in

Source

Show Source

Page 283: grails command main

SELECT

Purpose

Helper tag for creating HTML selects.

Examples // create a select from a range

<g:select name="user.age" from="${18..65}" value="${age}"

noSelection="['':'-Choose your age-']"/>

// use a no selection with a nullable Object property (use 'null' as key)

<g:select id="type" name='type.id' value="${person?.type?.id}"

noSelection="${['null':'Select One...']}"

from='${PersonType.list()}'

optionKey="id" optionValue="name"></g:select>

// create select from a list of companies

// note the 'optionKey' is set to the id of each company element

<g:select name="user.company.id"

from="${Company.list()}"

value="${user?.company.id}"

optionKey="id" />

// create multiple select

<g:select name="cars"

from="${Car.list()}"

value="${person?.cars*.id}"

optionKey="id"

multiple="true" />

// create select with internationalized labels (this is useful for small

static lists and the inList constraint)

// expected properties in messages.properties:

// book.category.M=Mystery

// book.category.T=Thriller

// book.category.F=Fantasy

<g:select name="book.category" from="${['M', 'T', 'F']}"

valueMessagePrefix="book.category" />

Example as a method call in GSP only:

${select(from:aList,value:aValue)}

Description

Attributes

o from (required) - The list or range to select from

o value (optional) - The current selected value that evaluates equals() to true for one of

the elements in the from list.

Page 284: grails command main

o optionKey (optional) - By default value attribute of each <option> element will be the

result of a "toString()" call on each element. Setting this allows the value to be a bean property of each element in the list.

o optionValue (optional) - By default the body of each <option> element will be the

result of a "toString()" call on each element in the "from" attribute list. Setting this allows the value to be a bean property of each element in the list.

o keys (optional) - A list of values to be used for the value attribute of each "option"

element.

o noSelection (optional) - A single-entry map detailing the key and value to use for the

"no selection made" choice in the select box. If there is no current selection this will be shown as it is first in the list, and if submitted with this selected, the key that you provide will be submitted. Typically this will be blank - but you can also use 'null' in the case that you're passing the ID of an object

o valueMessagePrefix (Optional) - By default the value "option" element will be the

result of a "toString()" call on each element in the "from" attribute list. Setting this allows the value to be resolved from the I18n messages. The valueMessagePrefix will be suffixed with a dot ('.') and then the value attribute of the option to resolve the message. If the message could not be resolved, the value is presented.

o multiple (optional) - Set to "true" to generate a multi-select listbox rather than a

dropdown list.

The optionKey and optionValue attribute of the <g:select> tag deserve special

mention as these allow you to control what is displayed to the user within the

resulting <select> tag and also the value which is submitted in a form submission. The

default behaviour is to call toString() on each element in the from attribute, but for

example if you had a list of Book domain classes this may not be useful behaviour.

As an example the following <g:select> uses the optionKey attribute to resolve

the id property of each Book as the value of the value attribute in each <option> tag.

It also uses the optionValue attribute of <g:select> to display the title property of

each Book to the user:

<g:select optionKey="id" optionValue="title" name="book.title"

from="${bookList}" />

If you require even more control over how each <option> element is presented to the

user you can use a closure to apply a transformation within theoptionValue attribute.

As an example, the following code transforms each Book title to upper case:

<g:select optionKey="id" optionValue="${{it.title?.toUpperCase()}}"

name="book.title" from="${bookList}" />

Source

Show Source

Page 285: grails command main

SET

Purpose

Set the value of a variable accessible with the GSP page.

Examples <g:set var="tomorrow" value="${new Date(today.getTime() + 24L * 60 * 60 *

1000)}" />

<g:set var="counter" value="${1}" />

<g:each in="${list}">

${counter}.&nbsp; ${it} -> ${counter % 2 == 0 ? 'even' : 'odd'}

<g:set var="counter" value="${counter + 1}" /><br/>

</g:each>

Using scopes:

<g:set var="foo" value="${new Date()}" scope="page" />

<g:set var="bar" value="${new Date()-7}" scope="session" />

Using the body contents:

<g:set var="foo">Hello!</g:set>

Description

Attributes

o var - The name of the variable

o value - The initial value to be assgined

o scope - Scope to set variable in (either request, page, flash or session. Defaults

to page).

Source

Show Source

Page 286: grails command main

SORTABLECOLUMN

Purpose

Renders a sortable column to support sorting in tables.

Examples <g:sortableColumn property="title" title="Title" />

<g:sortableColumn property="title" title="Title" style="width: 200px" />

<g:sortableColumn property="title" titleKey="book.title" />

<g:sortableColumn property="releaseDate" defaultOrder="desc" title="Release

Date" />

<g:sortableColumn property="releaseDate" defaultOrder="desc" title="Release

Date" titleKey="book.releaseDate" />

Description

Attribute title or titleKey is required. When both attributes are specified

then titleKey takes precedence, resulting in the title caption to be resolved against the

message source. In case when the message could not be resolved, the title will be used as title caption.

Attributes

o property - name of the property relating to the field

o defaultOrder (optional) - default order for the property; choose between asc (default if

not provided) and desc

o title (optional) - title caption for the column

o titleKey (optional) - title key to use for the column, resolved against the message

source

o params (optional) - a map containing request parameters

o action (optional) - the name of the action to use in the link, if not specified the list

action will be linked

Source

Show Source

Page 287: grails command main

SUBMITBUTTON

Purpose

Creates a submit button with the indicated value. Javascript event handlers can be added using the same parameter names as in HTML.

Examples <g:submitButton name="update" value="Update" />

Description

Attributes

o name (required) - The name of the button

o value (required) - The title of the button and name of action when not explicitly

defined.

Source

Show Source

Page 288: grails command main

SUBMITTOREMOTE

Purpose: Creates a button that submits the surrounding form as a remote ajax

call serializing the fields into parameters.

Example controller for an application called "shop":

class BookController {

def list = { [ books: Book.list( params ) ] }

def show = { [ book : Book.get( params['id'] ) ] }

}

Example usages for above controller:

<g:form action="show">

Login: <input name="login" type="text"></input>

<g:submitToRemote update="updateMe" />

</g:form>

<div id="updateMe">this div is updated by the form</div>

Description

Attributes

o url - The url to submit to, either a map contraining keys for the action,controller and id

or string value

o update (optional) - Either a map containing the elements to update for 'success' or

'failure' states, or a string with the element to update in which cause failure events would be ignored

o before (optional) - The javascript function to call before the remote function call

o after (optional) - The javascript function to call after the remote function call

o asynchronous (optional) - Whether to do the call asynchronously or not (defaults to

true)

o method (optional) - The method to use the execute the call (defaults to "post")

Events

o onSuccess (optional) - The javascript function to call if successful

o onFailure (optional) - The javascript function to call if the call failed

o on_ERROR_CODE (optional) - The javascript function to call to handle specified error

codes (eg on404="alert('not found!')")

o onUninitialized (optional) - The javascript function to call the a ajax engine failed to

initialise

o onLoading (optional) - The javascript function to call when the remote function is

loading the response

o onLoaded (optional) - The javascript function to call when the remote function is

completed loading the response

o onComplete (optional) - The javascript function to call when the remote function is

complete, including any updates

Source

Show Source

Page 289: grails command main

TEXTAREA

Purpose

Creates a HTML text area element. An implicit "id" attribute is given the same value as name unless you explicitly specify one. All the usual HTML elements apply beyond the below:

Examples <g:textArea name="myField" value="myValue" rows="5" cols="40"/>

Description

Attributes

o name (required) - The name of the text area

o value (optional) - The initial text to display in the text area. By default the text area will

be empty.

Source

Show Source

Page 290: grails command main

TEXTFIELD

Purpose

Creates a input of type 'text' (a text field). An implicit "id" attribute is given the same value as name unless you explicitly specify one. All the usual HTML elements apply beyond the below:

Examples <g:textField name="myField" value="${myValue}" />

Description

Attributes

o name (required) - The name of the text field

o value (optional) - The initial text to display in the text field. By default the text field will

be empty.

Source

Show Source

Page 291: grails command main

TIMEZONESELECT

Purpose

Helper tag for creating HTML selects for selecting from a list of time zones

Examples // Create a timezone selector

<g:timeZoneSelect name="myTimeZone" value="${tz}" />

Description

Attributes

o name (required) - The name of the select

o value (optional) - An instance of java.util.TimeZone. Defaults to the time zone for the

current Locale if not specified

Source

Show Source

Page 292: grails command main

UNLESS

Purpose

The logical unless tag renders its body conditionally, based on an expression and/or current environment. The unless tag will render its body unless all of the specified conditions (test and/or environment) are true. The tag will always do the opposite of what the if tag would have done.

Examples <g:unless test="${name == 'fred'}">

Hello ${name}!

</g:unless>

<g:unless env="development">

Dev mode - debug: $someDebug

</g:unless>

<g:unless env="production" test="${cacheEnabled}">

$cache.getContent('1234')

</g:unless>

Description

Attributes

o test - The expression to test

o env - An environment name

At least one of the attributes must be supplied. If both are supplied, they are combined using AND.

Page 293: grails command main

UPLOADFORM

Purpose

Creates a form that can submit multi-part data used in file uploads.

Examples <g:uploadForm name="myUpload">

<input type="file" name="myFile" />

</g:uploadForm>

Description

Identical to regular form except sets enctype attribute to "multipart/form-

data" automatically.

Attributes

o action (optional) - the name of the action to use in the link, if not specified the default

action will be linked

o controller (optional) - the name of the controller to use in the link, if not specified the

current controller will be linked

o id (optional) - The id to use in the link

o url (optional) - A map containing the action,controller,id etc.

Source

Show Source

Page 294: grails command main

WHILE

Purpose

Executes a condition in a loop until the condition returns false

Examples <g:while test="${i < 5}">

<%i++%>

<p>Current i = ${i}</p>

</g:while>

Description

Attributes

o test - The conditional expression