This is my first blog post since i joined our Grails programming team. Let me try to explain MVC by breaking it down into simple components. Basically model is used to work with back-end. View is what gets displayed to user. Controller is one of most important place when we develop any project because it controls all communication between model and view.

There are many IDE’s to develop project for grails like Netbeans,Eclipse, but IntelliJ idea is one of best option to do the development with Grails. Now we are going to discuss about MVC one by one.

Let’s create a new project and we can do this by two methods. One is to use command prompt or you can use any IDE.

1. With Command Prompt: 
grails create-app my-project        OR
grails createApp my-project
cd my-project

Both commands will have same effect. Its basically a convention either write it in camel case or write all words in lower case following with ‘-‘ as shown in above example. “my-project” is name of your project and now you have an empty project with basic structure ready for you. Now time to make domain, controller and view.

Domain Class:

The domain model in Grails is persisted to the database using GORM (Grails Object Relational Mapping). The core of most Grails applications is the domain model, which represents the persistent data of the application. It maintains all relation of your data and maps to tables in database. This is how you create a domain class :

grails create-domain-class org.example.Human
grails createDomainClass org.example.Human

It will create Book.groovy in grails-app/domain/org/example directory where org.example is the name of package where your domain class is saved. This is a normal text file with .groovy extension and we can edit it in any editor or IDE. It will create a class by it self like this.

package org.example
   class Human
   static constraints = {
   }
}

Lets add some data members to this class.

package org.example

class Human {
   String height
   String chestWidth
   Face face

   static constraints = {
      height (blank: false)
      chestWidth(blank: false)
   }
}

The result of the above code is that when we save an instance of Book , its title and author are persisted to the database. Note that we haven’t configured the database nor have we created the tables and columns: this all happens automatically.Constraints are basically used to specify validation requirement for your properties in domain class.

2. Controller Class

Controllers are central to generating your user interface or providing a programmatic REST interface. They typically handle the web requests that come from a browser or some other client and you’ll find that each URL of your application is usually handled by one controller.for create controller we write this syntax.

grails create-controller org.example.Book        OR
grails createController org.example.Book

It will create a controller in grails-app/org/example/BookController.groovy directory and code will look like this.

package org.example

class HumanController {

  def index() { }
}

def index() is an action in controller which is generated by default by Grails. If you want to generate CRUD action in controller by default then run this syntax.

grails generate-controller org.example.Book

It will generate action related to CRUD by itself.and your controller will look like this.

package org.example

class HumanController {

static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

def index() {
   redirect(action: "list", params: params)
}

def list(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    [humanInstanceList: Human.list(params), humanInstanceTotal: Human.count()]
}

def create() {
    [humanInstance: new Human(params)]
}

def save() {
    def humanInstance = new Human(params)
    if (!humanInstance.save(flush: true)) {
        render(view: "create", model: [humanInstance: humanInstance])
        return
    }

    flash.message = message(code: 'default.created.message', args: [message(code: 'human.label', default: 'Human'), humanInstance.id])
    redirect(action: "show", id: humanInstance.id)
}

def show(Long id) {
    def humanInstance = Human.get(id)
    if (!humanInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'human.label', default: 'Human'), id])
        redirect(action: "list")
        return
    }
    [humanInstance: humanInstance]
}

def edit(Long id) {
    def humanInstance = Human.get(id)
    if (!humanInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'human.label', default: 'Human'), id])
        redirect(action: "list")
        return
    }
    [humanInstance: humanInstance]
}

def update(Long id, Long version) {
    def humanInstance = Human.get(id)
    if (!humanInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'human.label', default: 'Human'), id])
        redirect(action: "list")
        return
    }

    if (version != null) {
        if (humanInstance.version > version) {
            humanInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
[message(code: 'human.label', default: 'Human')] as Object[],
"Another user has updated this Human while you were editing")
            render(view: "edit", model: [humanInstance: humanInstance])
            return
        }
    }

    humanInstance.properties = params

    if (!humanInstance.save(flush: true)) {
        render(view: "edit", model: [humanInstance: humanInstance])
        return
    }

    flash.message = message(code: 'default.updated.message', args: [message(code: 'human.label', default: 'Human'), humanInstance.id])
    redirect(action: "show", id: humanInstance.id)
}

def delete(Long id) {
    def humanInstance = Human.get(id)
    if (!humanInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'human.label', default: 'Human'), id])
        redirect(action: "list")
        return
    }

    try {
        humanInstance.delete(flush: true)
        flash.message = message(code: 'default.deleted.message', args: [message(code: 'human.label', default: 'Human'), id])
        redirect(action: "list")
    }catch (DataIntegrityViolationException e) {
        flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'human.label', default: 'Human'), id])
        redirect(action: "show", id: id)
    }
    }
}

Now your first application is ready to run on browser and this is how you run it.

grails run-app        OR
grails runApp

Now when application is running and you click on org.example.HumanController. It will go to index action by default.To run this action you need to have a view named index inside view/book/ directory . Let’s generate views using CRUD

grails generate-views org.example.Human        OR
grails generateViews org.example.Human

It will generate all views related to action of its Controller.you can also add other views according to your need.Now your program is fully functional and running properly.

There are three way to go at view from action.
1. Choose default view with action: If you have an action with action name and also .gsp page with same name then it goes to that action by default unless you do not make change in action. If there are no view with same name then it will throw an error. If you want to send some value on view then make a map with key value pair and send it.You can use these values to show dynamic value on view. This is called a Model

Syntax:    [key1:value1,key2,value2]

2. Render different view: If you have an action and you do not have a view with same name then you need to render a different view.

Syntax: render(view: "viewName", model: [key1: value1,key2:value2])

3. Redirect to another action: If you want to go to another action and then go to view then you need to redirect to an action.

Syntax:
redirect(action: "show")

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

If you call only action then it goes to in same controller and it you redirect with both action and controller then it allow you to connect with other controller’s action.

This was my first blog post after spending less then a week with Grails. I am sure i will learn more as we move ahead with our project.