jQuery Tags

Description

This set of tags allows you to include the JQuery JavaScript libary and register a "toggle" effect on an arbitrary HTML element referenced via id. Toggle means that the element you reference is magically disappearing and then shows up again if you hit the toggle link again. You first need to download jQuery which is only 15kB in size. Place the jquery.js file in a new web-app/js/jquery directory. To use the tags, you first need to reference the jquery.js from your HTML header, as shown below:

How it might look

Below are two example screenshots out of my app. The orange box is a div, referenced by id and styled via CSS. Note that the link is in a separate div box, resulting in the link beeing visible all the time. &nbsp;
Once you click the link, the box slides down and opens.&nbsp;
&nbsp;
&nbsp;
To have the boxed immediately closed after the page loaded, add this after the toggleelement tag of the example above: $("#notecontent").hide("slow");&nbsp;
&nbsp;

toggleelement description

elementId - references the id of the element that you want to toggle, e.g. disappear and appear

linkId - the link that will trigger the action, e.g. a <a href="http://docs.codehaus.org/pages/editpage.action#" id="showhidelink">link</a> ...

event - the event that is listened to: click means you have to click the link, can also be: dblclick, mouseover, etc. see the visual jQuery guide for a full list (go to events/mouse)

Note that this only implements a very small subset of the jQuery tag library. Feel free to extend this and post your code here :-) Enjoy.

textField enhanced&nbsp;

Description

Creates an input of type "text" specifically tailored to display and update a property on an object.

Parameters

object (required) - the object the property of which is accessed
field(required) - the name of the property to access
id(optional) - the id of the resulting input element, defaults to the name of the property

Yahoo Calendar&nbsp;

Description

3 tags that allow the Yahoo calendar control to be used to enter date values in a form. Note that this calendar tag is still a little rough, I placed it here because someone on the forum needed one and I figured that it was better than starting from scratch :-)

Parameters

yuiCalendarUtils

No Parameters

yuiCalendarHeader

name - the name of the calendar instance (mandatory)

value - the date value to set the calendar to (optional)

yuiCalendarBody

name - the name of the calendar instance

bean - the bean containing the date parameter to set the display and hidden fields to

/**
* Tag to provide initialization code for a single Yahoo calendar instance. This tag
* should be used once for each calendar instance used on the page. This tag
* should be placed in the page header and paired with a yuiCalendarBody tag in the body with
* the same value for the calendarName parameter.
* @param name the name of the calendar instance
* @param value the date value to set the calendar to
*/
def yuiCalendarHeader = {attrs, body ->
def calendarName = attrs.name
if (calendarName == null) {
thrownew IllegalArgumentException("name parameter must be specified")
}
Date dateValue = attrs.value
def monthYearFormatter = new SimpleDateFormat("MM/yyyy")
def monthDayFormatter = new SimpleDateFormat("MM/dd")
out << "<script language='javascript'>n"
out << 'YAHOO.namespace("example.calendar");n'
out << "function init${calendarName}() {n"
out << " YAHOO.example.calendar.${calendarName} = new YAHOO.widget.Calendar('YAHOO.example.calendar.${calendarName}', '${calendarName}Container'"if (dateValue != null) {
out << ", '${monthYearFormatter.format(dateValue)}', '${monthDayFormatter.format(dateValue)}'"
}
out << ");n"
out << " YAHOO.example.calendar.${calendarName}.title = 'Select ${calendarName}';n"
out << " YAHOO.example.calendar.${calendarName}.onSelect = set${calendarName};n"
out << " YAHOO.example.calendar.${calendarName}.render();n"
out << "}n"
out << "function set${calendarName}() {n"
out << " var calendarInstance = YAHOO.example.calendar.${calendarName};n"
out << " setCalendarDateValue('${calendarName}', calendarInstance, '${calendarName}Value');n"
out << "}n"
out << "function show${calendarName}() {n"
out << " var calendarInstance = YAHOO.example.calendar.${calendarName};n"
out << " showYUICalendar("${calendarName}", calendarInstance);n"
out << "}n"
out << "YAHOO.util.Event.addListener(window, 'load', init${calendarName});n"
out << "</script>n"
}

/**
* Tag to provide field code for a single Yahoo calendar instance. This tag
* should be used once for each calendar instance used on the page. This tag
* should be placed in the page body and paired with a yuiCalendarHeader tag in the header with
* the same value for the calendarName parameter.
* @param name the name of the calendar instance
* @param bean the bean containing the date parameter to set the display and hidden fields to
*/
def yuiCalendarBody = { attrs, body ->
def calendarName = attrs.name
def bean = attrs.bean
if (calendarName == null) {
thrownew IllegalArgumentException("name parameter must be specified")
}
if (bean == null) {
thrownew IllegalArgumentException("bean parameter must be specified")
}

DOM ids&nbsp;

With all this Ajaxy goodness you need some easy consistent way to reference DOM elements. Until something like this is integrated into the core domain objects here's a simple tag to generate dom ids for you.

/** takes two attributes object (that you want the dom_id of)
and optionally a prefix which will be prepended with an underscore
before the object's class and id.
<g:domId object="${aStudentObject}" prefix="foo" />
Assuming the Student object's id was 4 this outputs:
foo_student_4
*/
def domId = { attrs ->
if (attrs['prefix']){
out << attrs['prefix'];
out << '_';
}
out << attrs['object'].getClass().getName().toLowerCase();
out << '_';
out << attrs['object'].id
}

Enable or disable checkbox

This version of the g:checkbox is identical to the original one, except that you can set the "disabled=" property to true or false.

Model TagLib

This tag lib refines Bean TagLib to modularize the code and provide support for many more field types, and provides template-driven control of the rendering of fields, their labels, errors and required indicator.

The code is currently running on 2 live sites, sadly without unit tests (TagLib testing was broken in head when I wrote this). modelRadioXXX is not implemented yet.

There is a modelCountry tag which is dependent on another taglib called I18NTaglib.

transform Tag

Description

Applies an XSL stylesheet to a source XML document and writes the output to the response. The transformed XML will appear wherever the tag is used in a GSP.

Parameters

source - The source XML to transform. This can be one of: a DOM node, an _InputStream_, a _Reader_, or a file path.

transformer (optional) - A javax.xml.transform.Transformer instance that will be used to transform the source XML.

stylesheet (optional) - The name of the XSL stylesheet to apply. The stylesheet will be loaded from a stylesheets directory in the root of the web application (i.e. _<app>/web-app/stylesheets_). For example, if this parameter has the value "verbatim", then the stylesheet will be loaded from _<app>/web-app/stylesheets/verbatim.xsl_. Note Either transform or stylesheet must be specified, but not both.

factory (optional) - This parameter can be used with stylesheet to specify a particular javax.xml.transform.TransformerFactory to use. It is the fully-qualified class name of the TransformerFactory you want to use.

Examples

The following example uses a JAXP transformer that has already been configured in the controller. The controller simply puts the transformer object in the model under the key 'transformer' and the source DOM document under the key 'doc'.

// Check the various attributes.
//
// We must have one of 'transformer' or 'stylesheet'.
def transformer = attrs['transformer']
if (!transformer) {
// No transformer specified, so use a stylesheet instead.
def stylesheet = attrs['stylesheet']

// See whether a factory class has been specified. If so,
// we use that one to create a transformer. Otherwise, we
// just use the default factory.
def factory
if (attrs['factory']) {
factory = Class.forName(attrs['factory']).newInstance()
}
else {
factory = TransformerFactory.newInstance()
}

multiple select tag

Description&nbsp;

The current (as of 1.0 RC3) GSP select tag does not deal with a 'value' of anything but a single string.&nbsp; This tag allows you to have a list as the 'value' parameter, so that select boxes with multiple options can display multiple values pre-selected.

Example

How to use&nbsp;

&nbsp;Copy the code below in to a file named "MultiselectTagLib.groovy" and place in the grails-app/taglib directory of your application.

Code&nbsp;

/**
* multiselect taglib
* adapted from select functionality in Grails' FormTagLib.groovy file
*
* Intended as a stopgap until multiselect functionality is added
* to Grails permanently
*
* Additional functionality for multiple select behaviour
* provided by Michael Kimsal
*
* Original FormTagLib code
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*/

Sorting each Tag

Description

An each tag that can sort the items by it's alphanumeric string value, not lexical string value (Test2 is before Test100)

This uses AlphNumSorter.groovy from http://www.davekoelle.com/files/alphanum.groovy. Put AlphNumSorter.groovy in grails_app_home/src/groovy/. It support the var and status attributes of the standard g:each tag. It will sort if the sort attribute is set to "true".

stateDropDown Tag

Description

Creates a state drop down list (including DC) and allows for passing in of preselected state value. Does NOT require the "from" attribute of the g:select tag so you don't have to pass in a list of states.

Check Box List

Description

In a has-many relationship, Grials default implementation generates a list of links, and an add link where one can add a new item.

The Check Box List allows selection of existing items by presenting them as an array of checkboxes. In other words, it allows the user to select a subset amongst a superset of all items - as a more user-friendly alternative to a multi-select listbox (where a single click without the modifier key de-selects everything!). The CSS rendering provides the list within a scrollable DIV element to keep it independent of the total number of items in the list.

Tag parameters:

name: Name of the checkboxlist - this will also be the name of the element&nbsp;

from: A collection of the master set of elements (containing all possible items)

// sets the style to override height and/or width if either of them
// is specified, else the default from the CSS is taken
style = "style='"if(attrs.height)
style += "height:${attrs.height};"if(attrs.width)
style += "width:${attrs.width};"

// if we wanted to select the checkbox using a click anywhere on the label (also hover effect)
// but grails does not recognize index suffix in the name as an array:
// cname = "${attrs.name}[${idx++}]"
// and put this inside the li: <label for='$cname'>...</label>

To map the selected ids to corresponding domain objects, an additional set property required in the containing domain class
&nbsp;&nbsp;&nbsp;

// this is a has-many defined as usual
static hasMany = [users:User]

// this additional setter is used in the multiselect list to convert
// the ids selected in the checkbox list to the corresponding domain objects
public void setUserIds(List ids) {
this.users = ids.collect { User.get(it) }
}

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Label List

Description

Renders a delimiter-seperated list of values from an array. Could be used in conjunction with a CheckBoxList - placing it just above it to show the selected items in a label.

The Code

/**
* LastFmTagLib provides two targets to retrieve user data from last.fm
* (http://www.lastfm.com).
*
* 1. The "recent" tag pulls the 10 most recently listened to tracks for the
* supplied username:
* <lastfm:recent username="someuser"/>
*
* 2. The "weekly" tag pulls the most listened to artists for a supplied
* username, sorted by most tracks played:
* <lastfm:weekly username="someuser" limit="20"/>
*
* Each target can optionally take a "src" attribute to read the XML from
* instead of hitting the last.fm site each time it's executed. This is
* useful for a busy site or page that can grab the XML via a cron job or
* quartz job, storing the data locally for some minutes at a time.
*
* @author Darren Davison (darren [at] davisononline (dot) org)
*/
class LastFmTagLib {

/*
* supply a 'username' attribute to get the most recent
* last.fm tracks for that user as a list. Optionally
* supply a 'listClass' css attribute for the list.
*
* This target also takes an optional "limit" attribute to
* limit the number of entries shown from the 250 available.
* Default is 10.
*/
def weekly = { attrs, body ->

ICQStatus

Description

Displays a little icon showing your ICQ status. You have to specify the UIN (ICQ's user number) and optional a style for the image. I think image style 21 is the best one. That is the default if you omit the 'style' attribute.