Home > Groovy > Grails cheatsheet

Grails cheatsheet

September 26th, 2011 Leave a comment Go to comments

This is supposed to be a cheatsheet for some common elements in Grails.
It’s a little bare at the moment but I hope that in time it will be a nice mashup of different Grails elements.

Grails Cheatsheet

Constraints

static constraints = {
    propertyName(
        blank: false,
        nullable: false,
        inList: ['a', 'b'], //Or reference property here
        matches: '[0-9]+',
        minSize: 1,
        maxSize: 10,
        min: 1,
        max: 10,
        range: 1..10,
        unique: true,
        url: true,
        email: true,
        notEqual: "passwd", //Or reference property here
        validator: { val, obj ->
            return val != obj.propertyName
        },
 
        /* Display Options */
        attributes: [year: 2000..2011], //Adds extra attributes to item when rendered.
        password: true, //Indicate that this is a password field
        widget: 'textarea', //Choose what widget will be used to render this item.
                //textField, hiddenField, submitButton, field, textArea, form, actionSubmit, actionSubmitImage, datePicker, renderNoSelectionOption, timeZoneSelect, localeSelect, currencySelect, select, checkBox, radio
        display: false //Hide this item when scaffolding
    )
}

Persistence Callbacks

  • beforeInsert – Executed before an object is initially persisted to the database
  • beforeUpdate – Executed before an object is updated
  • beforeDelete – Executed before an object is deleted
  • beforeValidate – Executed before an object is validated
  • afterInsert – Executed after an object is persisted to the database
  • afterUpdate – Executed after an object has been updated
  • afterDelete – Executed after an object has been deleted
  • onLoad – Executed when an object is loaded from the database

Sample:

def beforeInsert() {
	doSomething()
}
 
def beforeUpdate() {
	if (isDirty('fieldName')) {
		doSomething()
	}
}

Showing SQL-queries

Edit the DataSource.groovy file in the Configuration directory and add the following to the hibernate section (preferably in non-production environments):

hibernate {
	show_sql = true
}
Categories: Groovy Tags:
  1. No comments yet.
  1. No trackbacks yet.

Time limit is exhausted. Please reload CAPTCHA.