Modalbox in Grails

There is a nice and handy javascript library for creating kind of a modal “window”, similar to the famous lightbox. Here are few lines of code to make it running in a Grails application

Installation

First of all, you have to download the library. The easiest way is to install a plugin modalbox

grails install-plugin modalbox

There was a slight problem in version 0.2. So, check your plugins/modalbox-0.2/grails-app/taglib/ModalboxTagLib.groovy. The version was not correct and the script tags were not correctly ended. Here is my tag library.

class ModalboxTagLib {
 
    static namespace = "modalbox"
 
    def createLink = { attrs,body ->
        // By default trigger onclick, but allow onmouseover etc
        def event = attrs.event ? attrs.event : 'onclick';
 
        // linkname only supported for backwards-compatibility. Default it to empty-string
        def linkname = attrs.linkname ? attrs.linkname : ""
 
        out << """
            <a href='${g.createLink(attrs)}' title='${attrs['title']}' ${event}='Modalbox.show(this.href, {title: this.title, width: ${attrs['width']}}); return false;'>${linkname}${body.call()}</a>
        """
    }
 
    def modalIncludes = {
        def jsFolder    = createLinkTo(dir:'plugins',file:'modalbox-0.2/js/modalbox')
        def cssFolder   = createLinkTo(dir:'plugins',file:'modalbox-0.2/css')
 
        out << """
            <script type='text/javascript' src='${jsFolder}/prototype.js' ></script>
    		<script type='text/javascript' src='${jsFolder}/scriptaculous.js?load=effects'></script>
    		<script type='text/javascript' src='${jsFolder}/modalbox.js' ></script>
    		<link rel='stylesheet' href='${cssFolder}/modalbox.css' />
        """
    }
}

“Parent” view

In the view that will call the Modalbox, use tag modalInclude like this one.

<modalbox:createLink controller="book" action="showDetails" params="[bookId:book.id]" title="Book details" width="500">book</modalbox:createLink>

Once clicked, it calls book/showDetails

“Modalbox” view

The view of book/showDetails is quite simple. You can create any static page and it will be displayed. If you want something more “spicy”, use AJAX.

Book details
 
<g:formRemote name="myForm" url="[controller:'book',action:'findSimilar']" update="[success:'similar']" onComplete="Modalbox.resizeToContent()">
	<input type="hidden" name="bookId" value="${book.id}" />
	<input id='search' name='search' />
	<input type="submit" value="Find similar" />
</g:formRemote >
 
<div id="similar">
</div>
 
<a href="#" title="Close window" onclick="Modalbox.hide(); return false;">Close</a>

Notice the resizeToContent() method. It assures, that the content that will come via AJAX will fit. Last, but not least; for comfortable close, there is the last line.

Enjoy it.