Introduction

The Fields plugin allows you to customize the rendering of input fields for properties of domain objects, command beans and POGOs based on their type, name, etc. The plugin aims to:

  • Use good defaults for fields.

  • Make it very easy to override the field rendering for particular properties or property types without having to replace entire form templates.

  • Not require you to copy and paste markup for containers, labels and error messages just because you need a different input type.

  • Support inputs for property paths of arbitrary depth and with indexing.

  • Enable other plugins to provide field rendering for special property types that gets picked up automatically (e.g. the Joda Time plugin can provide templates for the various date/time types).

  • Support embedded properties of GORM domain classes.

Find the Changelog here

Installation

The plugin is available on Maven Central and should be a dependency like this:

dependencies {
    implementation 'io.github.gpc:fields:"5.0.3"'
}

Usage

The plugin provides a set of tags you can use to render the fields in a form.

In the simplest case you can use f:all to render a field for every property of a bean (the domain object or command the form will bind to):

<g:form>
    <f:all bean="person"/>
</g:form>

To render individual fields you use the f:field tag:

<g:form>
    <f:field bean="person" property="name"/>
    <f:field bean="person" property="address"/>
    <f:field bean="person" property="dateOfBirth"/>
</g:form>

The f:field tag will automatically handle embedded domain properties recursively:

<f:field bean="person" property="address"/>

If there is no bean object backing a form but you still want to render the surrounding field markup you can give f:field a body:

<f:field property="password">
    <g:password name="password"/>
</f:field>

It should be an unusual case but to render just the widget without its surrounding container you can use the f:widget tag:

<f:widget bean="person" property="name"/>

To make it more convenient when rendering lots of properties of the same bean you can use the f:with tag to avoid having to specify bean on any tags nested inside:

<g:form>
    <f:with bean="person">
        <f:field property="name"/>
        <f:field property="address"/>
        <f:field property="dateOfBirth"/>
    </f:with>
</g:form>

If you need to render a property for display purposes you can use f:display. It will internally use g:fieldValue, g:formatBoolean or g:formatDate to format the value.

<f:display bean="person" property="name"/>

If you need to render the value in a different way you can give f:display a body instead.

<f:display bean="person" property="dateOfBirth">
    <g:formatDate format="dd MMM yyyy" date="${value}"/>
</f:display>

By default f:display simply renders the property value but if you supply a \_display.gsp template you can render the value in some structured markup, e.g. a table cell or list item. See the Customizing Field Rendering section for how to override templates. For example to render values in a definition list you could use a template like this:

<dt>${label}</dt>
<dd>${value}</dd>

Extra attributes (Since version 2.1.4)

You can pass any number of extra attributes to the f:with and f:all tags that will be propagated to the inner fields and displays. See their individual tags sections for more information.

Breaking changes

Templates

The names of the templates were changed for more adequate ones:

  • _field to _wrapper

  • _input to _widget

  • _display to _displayWrapper

  • _displayWidget was added

To use the old names (for backwards compatibility), configure the following in Config.groovy

grails.plugin.fields.wrapper = "field"
grails.plugin.fields.displayWrapper = "display"
grails.plugin.fields.widget = "input"

Widget attributes

To pass additional attributes to widgets, prefix them with widget-.

Example:

<f:field property="birthDate" widget-format="dd/MM/yyyy"/>

To use the old prefix (for backwards compatibility), configure the following in Config.groovy:

grails.plugin.fields.widgetPrefix = "input-"

Changes in tags

  • The f:input tag was deprecated because the name was confusing. Use the new f:widget tag instead.

  • The f:displayWidget tag was added. It outputs the widget for display purposes, without the wrapper (similar to the widget tag).

Localized numbers

All numbers are now rendered localized. This means that when using Locale.ENGLISH the number 1000.50 is represented as 1,000.50 but with Locale.GERMAN is represented as 1.000,50. To use the old behavior (for backwards compatibility) without localizing the numbers, configure the following in Config.groovy:

grails.plugin.fields.localizeNumbers = false

Customizing Field Rendering

The plugin resolves the GSP template used for each property according to conventions. You can override the rendering based on the class and property name or the property type. The f:field tag looks for a template called _wrapper.gsp, the f:widget tag looks for a template called _widget.gsp, the f:display tag looks for a template called _displayWrapper.gsp.

Breaking changes in version 1.5

In version 1.5 a new template was introduced _displayWidget.gsp. This is the corollary of _widget.gsp for fields that are read-only, i.e. it is responsible for rendering just the markup for the field itself. Furthermore, the default names of all the templates were changed in this version, in the interest of clarity and consistency. The changes to the template names are summarized below:

Table 1. Template Name Changes
Old Template Name (before v.1.5) New Template Name (v.1.5 onwards)

_field.gsp

_wrapper.gsp

_display.gsp

_displayWrapper.gsp

N/A

_displayWidget.gsp

Users upgrading to 1.5 from a previous version should either rename their templates (recommended) or add the following to grails-app/conf/application.yml to change the default templates names to the old names

grails:
    plugin:
        fields:
            wrapper: field
            displayWrapper: display
            widget: input
            displayWidget: displayWidget

Locating Field Templates by Convention

The template for a field is chosen by a convention using the names of the controller, action, bean class, bean property, theme, etc. All the tags will look for templates in the following directories in decreasing order of preference:

  • grails-app/views/*controllerNamespace*/*controllerName*/*actionName*/*propertyName*/_themes/*themeName*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*actionName*/_themes/*themeName*/*propertyType*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*actionName*/_themes/*themeName*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*propertyName*/_themes/*themeName*/

  • grails-app/views/*controllerNamespace*/*controllerName*/_themes/*themeName*/*propertyType*/

  • grails-app/views/*controllerNamespace*/*controllerName*/_themes/*themeName*/

  • grails-app/views/*controllerName*/*actionName*/*propertyName*/_themes/*themeName*/

  • grails-app/views/*controllerName*/*actionName*/_themes/*themeName*/*propertyType*/

  • grails-app/views/*controllerName*/*actionName*/_themes/*themeName*/

  • grails-app/views/*controllerName*/*propertyName*/_themes/*themeName*/

  • grails-app/views/*controllerName*/_themes/*themeName*/*propertyType*/

  • grails-app/views/*controllerName*/_themes/*themeName*/

  • grails-app/views/_fields/_themes/*themeName*/*class*/*propertyName*/

  • grails-app/views/_fields/_themes/*themeName*/*superclass*/*propertyName*/

  • grails-app/views/_fields/_themes/*themeName*/*associationType*/

  • grails-app/views/_fields/_themes/*themeName*/*propertyType*/

  • grails-app/views/_fields/_themes/*themeName*/*propertySuperclass*/

  • grails-app/views/_fields/_themes/*themeName*/default/

  • grails-app/views/*controllerNamespace*/*controllerName*/*actionName*/*propertyName*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*actionName*/*propertyType*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*actionName*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*propertyName*/

  • grails-app/views/*controllerNamespace*/*controllerName*/*propertyType*/

  • grails-app/views/*controllerNamespace*/*controllerName*/

  • grails-app/views/*controllerName*/*actionName*/*propertyName*/

  • grails-app/views/*controllerName*/*actionName*/*propertyType*/

  • grails-app/views/*controllerName*/*actionName*/

  • grails-app/views/*controllerName*/*propertyName*/

  • grails-app/views/*controllerName*/*propertyType*/

  • grails-app/views/*controllerName*/

  • grails-app/views/_fields/*class*/*propertyName*/

  • grails-app/views/_fields/*superclass*/*propertyName*/

  • grails-app/views/_fields/*associationType*/

  • grails-app/views/_fields/*propertyType*/

  • grails-app/views/_fields/*propertySuperclass*/

  • grails-app/views/_fields/default/

The variables referenced in these paths are:

Table 2. Referenced Variables
Name Description

controllerName

The name of the current controller (if any).

actionName

The name of the current action (if any).

themeName

Theme name specified as value of theme attribute (Optional).

class

The bean class. For simple properties this is the class of the object passed to the bean attribute of the f:field or f:widget tag but when the property attribute was nested this is the class at the end of the chain. For example, if the property path was employees[0].address.street this will be the class of address.

superclass

Any superclass or interface of class excluding Object, GroovyObject, Serializable, Comparable and Cloneable and those from GORM.

propertyName

The property name at the end of the chain passed to the property attribute of the f:field or f:widget tag. For example, if the property path was employees[0].address.street then this will be street.

propertyType

The type of the property at the end of the chain passed to the property attribute of the f:field or f:widget tag. For example, for a java.lang.String property this would be string.

propertySuperclass

Any superclass or interface of propertyType excluding Object, GroovyObject, Serializable, Comparable and Cloneable.

associationType

One of 'oneToOne', 'oneToMany', 'manyToMany' or 'manyToOne'. Only relevant if the property is a domain class association.

All class names are camel-cased simple forms. For example java.lang.String becomes string, and com.project.HomeAddress becomes homeAddress.

Templates are resolved in this order so that you can override in the more specific circumstance and fall back to successively more general defaults. For example, you can define a field template for all java.lang.String properties but override a specific property of a particular class to use more specialized rendering.

Templates in plugins are resolved as well. This means plugins such as Joda Time can provide default rendering for special property types. A template in your application will take precedence over a template in a plugin at the same level. For example if a plugin provides a grails-app/views/_fields/string/_widget.gsp the same template in your application will override it but if the plugin provides grails-app/views/_fields/person/name/_widget.gsp it would be used in preference to the more general template in your application.

For most properties the out-of-the-box defaults should provide a good starting point.

Locating Templates Conventionally Example

Imagine an object of class Employee that extends the class Person and has a String name property.

You can override the template f:field uses with any of these:

  • grails-app/views/*controllerName*/*actionName*/name/_themes/*themeName*/_wrapper.gsp

  • grails-app/views/*controllerName*/*actionName*/name/_wrapper.gsp

  • grails-app/views/*controllerName*/*actionName*/string/_wrapper.gsp

  • grails-app/views/*controllerName*/*actionName*/_wrapper.gsp

  • grails-app/views/*controllerName*/name/_wrapper.gsp

  • grails-app/views/*controllerName*/string/_wrapper.gsp

  • grails-app/views/*controllerName*/_wrapper.gsp

  • grails-app/views/_fields/employee/name/_wrapper.gsp

  • grails-app/views/_fields/person/name/_wrapper.gsp

  • grails-app/views/_fields/string/_wrapper.gsp

  • grails-app/views/_fields/default/_wrapper.gsp

override the template f:widget uses with any of these:

  • grails-app/views/*controllerName*/*actionName*/name/_themes/*themeName*/_widget.gsp

  • grails-app/views/*controllerName*/*actionName*/name/_widget.gsp

  • grails-app/views/*controllerName*/*actionName*/string/_widget.gsp

  • grails-app/views/*controllerName*/*actionName*/_widget.gsp

  • grails-app/views/*controllerName*/name/_widget.gsp

  • grails-app/views/*controllerName*/string/_widget.gsp

  • grails-app/views/*controllerName*/_widget.gsp

  • grails-app/views/_fields/employee/name/_widget.gsp

  • grails-app/views/_fields/person/name/_widget.gsp

  • grails-app/views/_fields/string/_widget.gsp

  • grails-app/views/_fields/default/_widget.gsp

And override the template f:display uses with any of these:

  • grails-app/views/*controllerName*/*actionName*/name/_themes/*themeName*/_displayWrapper.gsp

  • grails-app/views/*controllerName*/*actionName*/name/_displayWrapper.gsp

  • grails-app/views/*controllerName*/*actionName*/string/_displayWrapper.gsp

  • grails-app/views/*controllerName*/*actionName*/_displayWrapper.gsp

  • grails-app/views/*controllerName*/name/_displayWrapper.gsp

  • grails-app/views/*controllerName*/string/_displayWrapper.gsp

  • grails-app/views/*controllerName*/_displayWrapper.gsp

  • grails-app/views/_fields/employee/name/_displayWrapper.gsp

  • grails-app/views/_fields/person/name/_displayWrapper.gsp

  • grails-app/views/_fields/string/_displayWrapper.gsp

  • grails-app/views/_fields/default/_displayWrapper.gsp

During template development it is usually recommended to disable template caching in order to allow the plugin to recognize new/renamed/moved templates without restarting the application. See the "Performance" section of the guide for the exact settings.

See Template Seach Path

The plugin logs which locations it is checking for templates as debug log. You can enable this by defining a logger in logback.groovy

logger('grails.plugin.formfields.FormFieldsTemplateService', DEBUG,['STDOUT'])

The can disable the caching in application.yml using:

grails:
    plugin:
        fields:
            disableLookupCache: true

Default Behaviour - Using Grails Widget Tags

If no template override is found the plugin will use the standard grails input tags (e.g. g:select, g:checkbox, g:field) for rendering input controls. Using f:field you can pass extra arguments (e.g. optionKey, optionValue) through to these tags by prefixing them with widget-, e.g.

<f:field bean="person" property="gender" widget-optionValue="name"/>

Template parameters

The f:field and f:widget tags will pass the following parameters to your templates or to the body of f:field if you use one:

Table 3. Template Parameters
Name Type Description

bean

Object

The bean attribute as passed to the f:field or f:widget tag.

property

String

The property attribute as passed to the f:field or f:widget tag. This would generally be useful for the name attribute of a form input.

type

Class

The property type.

label

String

The field label text. This is based on the label attribute passed to the f:field or f:widget tag. If no label attribute was used the label is resolved by convention - see below.

value

Object

the property value. This can also be overridden or defaulted if the value or default attribute was passed to f:field or f:widget.

constraints

ConstrainedProperty

The constraints for the property if the bean is a domain or command object.

persistentProperty

DomainProperty

The persistent property object if the bean is a domain object.

errors

List<String>

The error messages for any field errors present on the property. If there are no errors this will be an empty List.

required

boolean

true if the field is required, i.e. has a nullable: false or blank: false constraint.

invalid

boolean

true if the property has any field errors.

prefix

String

A string (including the trailing period) that should be appended before the input name such as name="${prefix}propertyName". The label is also modified.

In addition f:field passes the following parameters:

Table 4. Parameter Names from f:field

Name

Type

Description

widget

String

The output of f:widget for the current bean and property if f:field was used without a tag body, otherwise the output of the tag body.

If the bean attribute was not supplied to f:field then bean, type, value and persistentProperty will all be null.

Field labels

If the label attribute is not supplied to the f:field tag then the label string passed to the field template is resolved by convention. The plugin uses the following order of preference for the label:

  • An i18n message using the key beanClass.path.label. For example when using <f:field bean="authorInstance" property="book.title"/> the plugin will try the i18n key author.book.title.label. If the property path contains any index it is removed so <f:field bean="authorInstance" property="books<<0>>.title"/> would use the key author.books.title.label.

  • For classes using the same bean class as properties, it is possible to get a key without the class name prefixed. If the configuration value grails.plugin.fields.i18n.addPathFromRoot is set to true (default: false). Example: a class Publisher has two Address properties authorAddress and printAddress. With addPathFromRoot=true they will share the key address.city.label. The same goes if Author and Publisher had a Book book, the key would be book.title.label, and if they both had a List<Book> books the key would be books.title.label

  • An i18n message using the key objectType.propertyName`.label`. For example when using <f:field bean="personInstance" property="address.city"/> the plugin will try the i18n key address.city.label.

  • The natural property name. For example when using <f:field bean="personInstance" property="dateOfBirth"/> the plugin will use the label "Date Of Birth".

Locating Field Templates Directly

Rather than relying on the convention described previously to locate the template(s) to be used for a particular field, it is instead possible to directly specify the directory containing the templates. This feature was introduced in version 1.5.

  • The wrapper attribute can be used with the f:field or f:display tags to specify the directory containing the _wrapper.gsp or _displayWrapper.gsp template to be used

  • The widget attribute can be used with the f:field or f:display tags to specify the directory containing the _widget.gsp or _displayWidget.gsp template to be used

  • If the wrapper and widget templates both have the same value, the templates attribute can be used instead as a shorthand. For example:

<f:field property="startDate" templates="bootstrap3" />

is equivalent to:

<f:field property="startDate" wrapper="bootstrap3" widget="bootstrap3" />

if theme is specified, theme will be searched first to find the templates For example

<f:field property="startDate" templates="custom" theme="bs-horizontal"/>

Will search the templates first in \_fields/_themes/bs-horizontal/custom and then \_fields/custom

If a direct location is specified, and the templates cannot be found therein, the plugin will fall back to locating templates by convention.

Locating Templates Directly Example

// renders _fields/\_themes/bs-horizontal/custom/_wrapper.gsp:
<f:field property="startDate" wrapper="custom" theme="bs-horizontal"/>

// renders _fields/bootstrap3/_wrapper.gsp:
<f:field property="startDate" wrapper="bootstrap3"/>

// renders _fields/time/_widget.gsp:
<f:field property="startDate" widget="time"/>

// renders _fields/time/_wrapper.gsp and _fields/time/_widget.gsp:
<f:field property="startDate" templates="time"/>

// renders _fields/\_themes/bs-horizontal/custom/_displayWrapper.gsp:
<f:display property="startDate" wrapper="custom" theme="bs-horizontal"/>


// renders _fields/bootstrap3/_displayWrapper.gsp:
<f:display property="startDate" wrapper="bootstrap3"/>

// renders _fields/time/_displayWidget.gsp:
<f:display property="startDate" widget="time"/>

// renders _fields/time/_displayWrapper.gsp and _fields/time/_displayWidget.gsp:
<f:display property="startDate" templates="time"/>

Embedded Properties

Embedded properties are handled in a special way by the f:field and f:all tags. If the property attribute you pass to f:field is an embedded property then the tag recursively renders each individual property of the embedded class with a surrounding fieldset. For example if you have a Person class with a name property and an Address embedded class with street, city and country properties <f:field bean="person" property="address"> will effectively do this:

<fieldset class="embedded address">
    <legend>Address</legend>
    <f:field bean="person" property="address.street"/>
    <f:field bean="person" property="address.city"/>
    <f:field bean="person" property="address.country"/>
</fieldset>

You can customize how embedded properties are surrounded by providing a layout at grails-app/views/layouts/_fields/embedded.gsp which will override the default layout provided by the plugin.

When you use the f:all tag it will automatically handle embedded properties in this way.

Themes

Since version 2.1.4 It is possible to create themes to provide set of templates for different css frameworks or form layouts. For example, a bootstrap-fields plugin can provide different themes (eg bs-horizontal, bs-vertical) to support horizontal and vertical form layouts. And another plugin can provide theme for purecss framework.

Themes are put under directory _fields/themes/*themeName*/.

All of the field tags supports theme attribute which accepts the name of the theme. When a theme name is specified, widget, wrapper, and display templates will be searched in theme directory first as described in Customizing Field Rendering.

Including Templates in Plugins

Plugins can include field and/or input level templates to support special UI rendering or non-standard property types. Just include the templates in the plugin’s grails-app/views directory as described in the Customizing Field Rendering section.

If you supply templates in a plugin you should consider declaring a <%@page defaultCodec="html" %> directive so that any HTML unsafe property values are escaped properly regardless of the default codec used by client apps.

In order to be performant, the Fields plugin caches field template lookup results by default. This makes it possible to perform the time-consuming template path resolutions only once during the runtime of the application.

When template caching is active, only the first page renderings are slow, subsequent ones are fast.

Due to the flexibility needed during template development, this feature can be disabled so it would be possible to recognize newly added field templates without restarting the application. As a result, with bigger webpages, containing a lot of fields, rendering may be fairly slow in development (depending on the number of fields on the page).

Performance

For template development, the following configuration attribute should be placed in the development environment section of your application’s Config.groovy:

application.groovy
grails.plugin.fields.disableLookupCache = true

or

application.yml
environments:
    development:
        grails:
            plugin:
                fields:
                    disableLookupCache: true

After the template development has finished, it is recommended to re-enable the template lookup cache in order to have a performant page rendering even during development.

Reference

Tags

all

f:all

Purpose

Renders fields for all properties of an object by using f:field for each property.

The id, version, dateCreated and lastUpdated properties are skipped on domain classes. Additionally any property with a display: false constraint set will be skipped.

Attributes
Table 5. Attributes for f:all
Name Required Description

bean

if not inside f:with

The bean whose property is being rendered. This can be the object itself or the name of a page-scope variable.

except

N/A

A comma-separated list of properties that should be skipped (in addition to the defaults).

order

N/A

A comma-separated list of properties which represents the order in which the tag should generate fields.

prefix

String

A string (including the trailing period) that should be appended before the input name such as name="${prefix}propertyName". The label is also modified.

theme

String

Theme to use if available.

Extra attributes (Since version 2.1.4)

You can pass extra attributes to the all tag that will be propagated to the inner fields.

Example
<f:all bean="person" wrapper="someWrapper"/>

In that way all the fields are going to be executed as if they were executed with the extra attribute on them.

Remember that if you want to use some of those attributes in the widget templates you need to prefix them with the widget- word (unless you have configured another prefix)

display

f:display

Purpose

f:display renders a property for display. If there is no _displayWrapper template in scope the tag will simply render the property value.

f:display template will look for a _displayWrapper for the wrapper itself and a _displayWidget for the widget used inside the wrapper template.

If the f:display tag has a body its output is used as the value passed as the value model to the _display template. If there is no body then the raw property value is passed to g:fieldValue, g:formatDate or g:formatBoolean depending on its type and the result is passed as the value model to the _display template.

In version 1.5 new attributes were added: Since then you can specify the folders where the templates are located. You can do this for the wrapper folder, the widget folder ot both (if they are located on the same folder).
Examples
<f:display bean="person"/>

<f:display bean="person" displayStyle="table"/>

<f:display bean="person" property="name"/>

// renders widget and wrapper from subdirectory of _fields/_themes/purecss if defined
<f:display bean="person" property="name" theme="purecss"/>

// renders _fields/bootstrap3/_displayWrapper.gsp:
<f:display bean="person" property="name" wrapper="bootstrap3"/>

// renders _fields/maskedInput/_displayWidget.gsp:
<f:display bean="person" property="name" widget="maskedInput"/>

// renders _fields/maskedInput/_displayWrapper.gsp and _fields/maskedInput/_displayWidget.gsp:
<f:display bean="person" property="name" templates="maskedInput"/>

<f:display bean="person" property="dateOfBirth">
    <g:formatDate format="dd MMM yyyy" date="${value}"/>
</f:display>
Attributes
Table 6. Attributes for f:display
Name Required Description

bean

if not inside f:with

The bean whose property is being rendered. This can be the object itself or the name of a page-scope variable.

property

No

The path to the property. This can include any level of nesting and numeric or string indexes. For example employees[0].address[home].street is a valid path. If absent, all properties will be displayed via the grails-app/views/templates/_fields/_list.gsp (see the template code below).

value

No

Overrides the actual value of the property.

default

No

A default value for the property that will be used if the actual property value is false.

label

No

Overrides the field label passed to the template. This value may either be an i18n key or a literal string.

displayStyle

No

When specified and different from the string default, this tag will try to use a _display-${displayStyle} template with a _display template as fallback. `displayStyle="table" will render embedded components by default with toString() instead of rendering all nested properties.

except

No

A comma-separated list of properties that should be skipped.

order

No

A comma-separated list of properties which represents the order in which the tag should display them.

theme

No

Theme to use if available. The theme can define a new directory structure in /_fields/_themes/<themename> which will take priority over templates, wrapper and widget if they are specified, as it is injecting the search path first in the list.

templates

No

Specify the folder inside _fields where to look up for the wrapper and widget template.

widget

No

Specify the folder inside _fields where to look up for the widget template.

wrapper

No

Specify the folder inside _fields where to look up for the wrapper template.

Any additional attributes are passed to the rendered template.

Special case for rendering all properties of a bean

When f:display is used without a property then all bean properties are rendered. This is done with the grails-app/views/templates/_fields/_list.gsp template. The default template can be found on GitHub

displayWidget

f:displayWidget

Purpose

f:displayWidget renders an appropriate widget for a display property, for example an <span>${value}</span> element for a String property.

Using f:displayWidget directly will only be necessary for very specialized cases, usually it will be invoked via f:display.
Attributes

f:displayWidget accepts exactly the same attributes as the f:display tag (except for wrapper and templates attributes).

Example of a _displayWidget.gsp

If you have a domain class with a java.time.LocalDate you might want to format it specially:

grails-app/views/_fields/localDate/_displayWidget.gsp
<%@ page import="java.time.format.DateTimeFormatter" %>
<g:set var="localDatePattern" value="${message(code: 'default.localDate.format',default: 'yyyy-MM-dd')}"/>
${value?.format(DateTimeFormatter.ofPattern(localDatePattern, request.getLocale()))}

field

f:field

Description

f:field renders the widget using either f:widget or the tag body accompanied by any surrounding markup, typically a container, a label tag and any validation messages.

By default the f:field tag will output:

<div class="fieldcontain">
    <label for="foo">Foo</label>
    <!-- the widget as generated by f:widget or the tag body -->
</div>

The intention is that f:field should typically be used without a tag body. For example:

<f:field bean="person" property="name"/>

In which case the tag will use f:widget to generate an appropriate input. Alternatively in more specialized cases you can give f:field a tag body. For example:

<f:field bean="person" property="name">
    <g:textField name="${property}" value="${value}"/>
</f:field>

Since version 1.5 you can specify which specific templates are going to be used on the view. You can accomplish this using new attributes: wrapper, widget and templates. (See attributes section)

Since version 2.1.4 you can specify the theme to be used.

<f:field bean="person" property="name" theme="bs-horizontal"/>
// renders _fields/bootstrap3/_wrapper.gsp:
<f:field bean="person" property="name" wrapper="bootstrap3"/>

// renders _fields/maskedInput/_widget.gsp:
<f:field bean="person" property="name" widget="maskedInput"/>

// renders _fields/maskedInput/_wrapper.gsp and _fields/maskedInput/_widget.gsp:
<f:field bean="person" property="name" templates="maskedInput"/>

See Customizing Field Rendering for details of the parameters passed to the tag body.

The f:field tag handles embedded domain properties in a special way. See Embedded Properties for details.

Attributes
Table 7. Attributes for f:field
Name Required Description

bean

yes for f:widget if not inside f:with, optional for f:field

The bean whose property is being rendered. This can be the object itself or the name of a page-scope variable.

property

yes

The path to the property. This can include any level of nesting and numeric or string indexes. For example employees[0].address[home].street is a valid path. If absent, all properties will be displayed.

value

No

Overrides the actual value of the property.

default

No

A default value for the property that will be used if the actual property value is false.

required

No

Overrides the required status of the property. By default this is worked out based on the property’s constraints.

invalid

No

Overrides the validity of the property. By default this is worked out using the bean’s errors property for domain and command objects.

label

No

Overrides the field label passed to the template. This value may either be an i18n key or a literal string.

prefix

No

A string (including the trailing period) that should be appended before the input name such as name="${prefix}propertyName". The label is also modified.

wrapper

No

Specifies the name of the folder inside _fields where the _wrapper.gsp template is located.

widget

No

Specifies the name of the folder inside \_fields where the \_widget.gsp template is located.

templates

No

Specifies the name of the folder inside _fields where the _wrapper.gsp and _widget.gsp templates are located. It is a shorthand for specifying both (wrapper and widget).

theme

String

Theme to use if available.

Any additional attributes are passed to the rendered template. Any additional attributes prefixed with widget- are instead passed to the widget template or rendered on the default input.

Example of overriding a _wrapper.gsp

If you want to override a f:wrapper to be used for all widgets then create a file with content like this:

grails-app/views/_fields/default/_wrapper.gsp
<div class="form-group ${invalid ? 'has-error' : ''}">
    <label for="${property}">${label} ${required ? '*' : ''}</label>

    <div>
        <f:widget property="${property}"/>
        <g:if test="${errors}">
            <g:each in="${errors}" var="error">
                <span class="help-block"><g:message error="${error}"/></span>
            </g:each>
        </g:if>
    </div>
</div>

input

f:input (DEPRECATED)

Deprecated since version 1.5

Use f:widget tag instead

table

f:table

Purpose

<f:table/> renders some or all properties of a collection of beans in a table using the f:display widget for each property type. If there is no \_display template in scope the tag will simply render the property values.

Examples
<f:table collection="personList"/>

<f:table collection="personList" properties="firstName, lastName"/>

<f:table collection="personList" properties="['firstName', 'lastName']"/>

<f:table collection="catsAndDogsList" domainClass="org.zoo.Animal"/>

<f:table collection="catsAndDogsList" domainClass="org.zoo.Animal" theme="bs-horizontal"/>

// List first three properties in Person
<f:table collection="personList" maxProperties="3"/>

// Include id, lastUpdated, dateCreated
<f:table collection="personList" except="[]]"/>

The template for <f:table/> should be in

grails-app/views/templates/_fields/_table.gsp

but you can have multiple table templated, if you specify the template property. All templates should still be located in view/templates/_fields/, the example below uses 4 different templates for table.

<f:table collection="myList" myProperty="Template: view/templates/_fields/_table.gsp" />
<f:table collection="${demoList}" template="table3" myProperty="Template: view/templates/_fields/_table3.gsp" />
<f:table collection="${demoList}" template="tables/table2" myProperty="Template: in view/templates/_fields/tables/_table2.gsp" />
<f:table collection="${demoList}" template="tables/table" myProperty="Template: view/templates/_fields/tables/_table.gsp" />

When theme is specified, the \_display template will be searched first in theme, but the theme property does not directly apply to table.

Attributes
Name Required? Default Description

collection

yes

The collection of beans to be displayed

domainClass

Class of first element in collection

The FQN of the domain class of the elements in the collection.

properties

First 7 (or less)

Comma-separated String or List of properties to be shown (table columns). Defaults to the first 7 (or less) properties of the domain class ordered by the domain class' constraints, unless maxProperties is set below

displayStyle

Determines the display template used for the bean’s properties. Defaults to table meaning that \_display-table templates will be used when available.

except

['id', 'lastUpdated', 'dateCreated']

A comma-separated String or List of properties that should be skipped. Use the empty list to include id, lastUpdated and dateCreated

order

Comma-separated String or List of properties which represents the order in which the tag should display them.

theme

String

Theme to use if available.

maxProperties

Number

7

The maximum number of properties to display when rendering the table. If zero is specified all columns are shown, otherwise properties[0..<maxProperties] are shown. maxProperties can be negative.

template

String

table

Alternative template for table rendering. Templates should be in the grails-app/views/templates/_fields/ folder.

Any additional attributes are passed to the rendered template.
Modifying the _table.gsp template.

To make you own version of a f:table template, the file should be located in grails-app/views/templates/_fields/_table.gsp unless a different location is specified with the template property. You can find a starting point for a new file on GitHub

Model in the template

The following model is passed to the _table.gsp template:

Name Content

domainClass

The type of the persistent instance. Either type of the first row in the collection or the domainClass passed as argument to f:table

columnProperties

Contains a list of Map describing each table column. See table below for the map content

domainProperties

deprecated: see columnProperties

collection

Rows with data

displayStyle

The attribute displayStyle passed to the model unmodified

theme

The attribute theme passed to the model unmodified

The column model:

Name Content

bean

Empty instance of a domainClass bean

property

The property name

name

Deprecated, see property

type

The property type

defaultLabel

Translated label (deprecated)

label

Translated label

constraints

If the property has constraints

required

Is the property required

(This is a simplified version of a wrapper model)

widget

f:widget

Purpose

f:widget renders an appropriate widget for a property, for example an <input type="text"> element for a String property or a <select> for an enum.

Using f:widget directly will only be necessary for very specialized cases, usually it will be invoked via f:field.
Attributes

f:widget accepts exactly the same attributes as the f:field tag (except for wrapper and templates attributes).

Default rendering

The <f:widget/> tag will will by default use sensible defaults when rendering String, Number, Boolean, URL, Enum, Date and associations like oneToOne, oneToMany, manyToOne and manyToMany.

In a few cases it is possible to control which default widget to use, by specifying it in the beans constraints.

The following happens with these types:

String

By default, properties instance of String renders a <g:field type="text"> type field, but the constraints in the bean will alter this in these cases:

constraint

Rendered Widget type

inList

<g:select/>. If the field is not required, a noSelection is added to the select

password: true

<g:field type="password"/>

email: true

<g:field type="email"/>

url: true

<g:field type="url"/>

widget: 'textarea'

<g:textArea/>

Numeric and primitive types

By default, properties instance of Number renders a <g:field type="number"> or <:field type="number decimal"/> type field, but the constraints in the bean will alter this in these cases:

constraint

Affects the rendered widget

scale

Sets the step attribute on the input field

min

Set the min attribute on the input field

max

Set the max attribute on the input field

By default, the value is formatted with the default numberFormatter based on the request locale.

This behavior can be turned off in the configuration by setting:

grails:
    plugin:
        fields:
            localizeNumbers: false
Boolean

Renders a <g:checkBox/>

URL

Renders a <g:field type="url"/>

Enum

enum types always renders a <g:select/> with all the values in the type. To render a subset of enum values, the inList constraint can be used.

Date, Calendar, java.sql.Date and java.sql.Time

Renders a <g:datePicker/>. If Date, Calendar, or java.sql.Date then precision is set to day, if java.sql.Time then minute

byte[], Byte[], Blob

Renders a <g:field type="file"/>

oneToOne, manyToOne or manyToMany associations

All these associations renders a <g:select/> and if association has a nullable: true constraint, then a noSelection attribute is added.

For the manyToMany association, the multiple attribute is set.

oneToOne and `manyToOne renders a

oneToMany association

The oneToMany association does not render an input type field, but does instead render a list of links to the associated objects.

Example of overriding a _widget.gsp

If you want to override a f:widget for a String, then create a file with content like this:

grails-app/views/_fields/string/_widget.gsp
<g:textField name="${property}" value="${value}" required="${required}" class="form-control"/>

with

f:with

Purpose

Places a bean in scope so that the bean attribute can be omitted on contained tags.

Example
<f:with bean="person">
    <f:field property="name"/>
    <f:field property="address.city"/>
</f:with>
Attributes
Name Required? Description

bean

yes

The bean whose property is being rendered. This can be the object itself or the name of a page-scope variable.

prefix

String

A string (including the trailing period) that should be appended before the input name such as name="${prefix}propertyName". The label is also modified.

Extra attributes (Since version 2.1.4)

You can pass any number of extra attributes to the with tag that will be propagated to the inner fields and displays.

<f:with bean="person" wrapper="someWrapper">
 <f:field property="name"/>
 <f:field property="address.city"/>
</f:with>

That way you don’t need to repeat the same attribute over and over. The code above is the same as:

<f:with bean="person">
 <f:field property="name" wrapper="someWrapper"/>
 <f:field property="address.city" wrapper="someWrapper"/>
</f:with>
Override extra attributes

You can override the extra attributes on any field just changing the attribute value on the popper field or display

<f:with bean="person" wrapper="someWrapper">
 <f:field property="name"/>
 <f:field property="address.city"/>
 <f:field property="address.zip" wrapper="differentWrapper"/>
</f:with>
Remember that if you want to use some of those attributes in the widget or displayWidget templates you need to prefix them with the widget- word (unless you have configured another prefix)

Changelog

Version 5.0.0 - Grails 5.3.x

In your build.gradle file, use:

implementation 'io.github.gpc:fields:5.0.0'

Version 4.0.0 - Grails 4.1.x

Important

New group id.

In your build.gradle file, use:

compile 'io.github.gpc:fields:4.0.0'

Thank goes to the community for all the contributions!

Version 3.0.0.RC1 - Grails 4.0.x

Last version that is on the "old" group org.grails.plugins

Version 2.2.8

  • BugFix: Table Tag does not render transient fields correctly (Issue #264)

  • BugFix: Table Tag does not render references correctly! (Issue #269)

  • BugFix: Fix XSS vulnerability when rendering beans (Issue #278) GitHub diff

Version 2.2.7

  • BugFix: The fix for #257 did not work as described, but now it does.

  • Improvement: Documentation has been improved with more examples for the various tags. GitHub diff

Version 2.2.6

  • Improvement: Documentation of maxProperties on <f:table/>

  • Improvement: <f:table\> can now show id, lastUpdated and dateCreated (see f:table doc). Injecting DomainModelService instead of instantiating DomainModelServiceImpl in FormsFieldTagLib (Issue #257)

Version 2.2.4/2.2.5

  • Improvement: Introduced maxProperties attribute to <f:table/>

  • Improvement: Render value that is an association but not to a grom entity

  • Improvement: Rendering numbers is now Locale-aware (can be configured)

Version 2.2.3

  • Bug-fix: Another issue with old API

Version 2.2.2

  • Bug-fix: Fix issue with oneToMany expecting the old API

Version 2.2.1

  • Bug-fix: Autowire beans

Version 2.2.0

  • Conversion to the Mapping Context API. Usages of the GrailsDomainClass and GrailsDomainClassProperty classes have been removed. If you extend a template that relies on those classes, they have been replaced with PersistentEntity and DomainProperty respectively.

  • Conversion of constraints to a common implementation between grails.validation and grails.gorm.validation. See Constrained.

Version 2.1.4

  • Upgrade to Grails 3.2.8

  • Convert documentation to Asciidoc

  • Add support for themes

Version 2.0

  • Redesign for Grails 3.0

Version 1.5

2015_04_26

See Usage and Customizing Field Rendering for breaking changes.

Version 1.4

  • Upgraded plugin to work with Grails 2.3.x (Issue #122)

  • Fixed missing property exception (Issue #134)

  • Fixed encoding in tag libraries (Issue #137)

  • Configuring caching in dev mode (Issue #139)

  • byte[] and Byte[] arrays types now look for files in byteArray folders (general for all array types) (Issue #144)

Version 1.3

2012-07-31

  • Adds the f:display tag.

  • Supports overriding templates by property type or by default in individual controllers and actions.

Browse issues Thanks to https://github.com/cdeszaq,[Rick Jensen] https://github.com/delight,[Konstantinos Kostarellis] Gus Power and Eliot Sykes for their contributions.

Version 1.2

2012-03-16

  • Pass attributes from f:field to the rendered input using input- prefix.

  • Optionally use entire property path for label key.

Browse issues Thanks to Brian Saville and OverZealous for contributions.

Version 1.1

2012-03-11

  • Adds the prefix attribute.

  • Support widget:'textarea' constraint.

Browse issues Thanks to Brian Saville for contributions.

Version 1.0.4

2012-02-13: Bugfix release.

Version 1.0.3

2012-02-09: Bugfix release.

Version 1.0.2

2012-02-07: Bugfix release.

Version 1.0.1

2012-02-03: Bugfix release.

Version 1

2012-02-01: Initial release.