What is CRUD

Posted by Anantha Narayanan On 11:41 AM

A CRUD or short form for Create/Read/Update/Delete is a controller action that is built in grails for supporting basic inserting of data, querying of data, updating of data and deleting of data from table linked to a domain class.

In short, these common actions of users need not be coded for a domain class.

Consider the following example of a controller with just one line of code which enables this feature.


class BookController {
    static scaffold = true
}

The scaffold variable if its true, grails helps to auto-generate user actions for CRUD without a single line of code. The naming convention for controller follows the domain name. For a domain name Book a controller of BookController can be created.

This naming convention helps grails auto-identify your domain class and provide you with code for insert, query, update and delete for the domain class.

When the scaffold is created, grails automatically adds the above four user actions which are common for database access.

For more information on scaffolding refer Grails docs.

What are Transient Properties

Posted by Anantha Narayanan On 3:32 PM


Grails GORM by default creates all the properties on your domain as columns in database tables. We may not require such functionality. For Example in a user creation domain we may require the user to enter the confirm password along with password. We will definitely not require two columns in tables with same password (provided there is validation for that).

In such cases you can map properties in domain as Transient, conveying to Grails GORM not to create a column for the property. For Example:

Class Person {
  static transients = ["confirmPassswd"]

  String firstName
  String lastName
  String emailID
  String loginPasswd
  String confirmPasswd
}

In Grails it is simple enough to define such extensible features.

Login application - Validate from Database

Posted by Anantha Narayanan On 5:17 PM


Click here to see a very basic login application with hard-coded user credentials. In current article I am discussing as on how to validate from a table where login id and password is stored. The article above points to the usage of flash and session's uses. I will not discuss more about flash and session in this article.

My assumption is that a person is assigned for a login with his email id. Based on that I planned for a domain called "Person" as below (I named the application happy):

package happy
class Person {
  String firstName
  String lastName
  String emailID
  String loginPassword
  Boolean superUser

  static constraints = { 
    firstName(size:1..120,nullable:false,blank:false)
    lastName(size:1..120,nullable:false,blank:false)
    emailID(email:true,size:1..120,nullable:false,blank:false)
    loginPassword(password:true,size:6..20,nullable:false,blank:false)
  }
}


In my PersonController.groovy, I added an interceptor which should validate a session. If no session is available it should redirect me to login page.


package happy
class PersonController {
  def beforeInterceptor = [action.this.&checkUser]
  static scaffold = true
  def checkUser() {
    if(!session.user) {
      redirect(controller:'person',action:'login')
      flash.message = "Invalid Username/Password, please try again."
    }
  }
}


I have successfully added a validation for all controllers in Person. If there is no login detected the user should be redirected to a login page. Next part is to design that page.


  def login = {
  }
 
   

I have put a blank controller inside the Person controller for login. Now I have to create a gsp file for this controller to successfully work. For this, I copied the index.gsp from views folder and copied it as login.gsp inside person foler within views. I deleted the entire contents within body tag and replaced with the following code:


<body>
  <a href="#page-body" class="skip">
  <g:message code="default.link.skip.label" default="Skip to content&hellip;"/></a>
  <g:render template="loginHeader"/>
  <div class="bodyContent" id="bodyContent">
    <g:if test="${flash.message}">
      <div class="message">${flash.message}
</div>
    </g:if>
  </div>
</body>


It is a simple code, please read through all lines. From <g:render> tag, I will explain. It is looking for a _loginHeader.gsp as its a template. It then displays the body content and if any messages.

The following are the contents of _loginHeader.gsp located in views/person folder.


<g:if test="${session.user}">
<div class="login">
<g:remoteLink controller="person" action="list" update="bodyContent">${session.user.emailID}</g:remoteLink> | <g:link action="logout">Logout</g:link>
</div>
</g:if>
<g:else>
<g:form action="doLogin" method="post">
<div class="login">
 <label for='emailID'>Email ID</label>
 <input id="emailID" required type='text' name='emailID' value='${person?.emailID}' />
 <label for='loginPassword'>Password</label>
 <input id="loginPassword" required type='password' name='loginPassword' value='${person?.loginPassword}' />
 <input type="submit" value="Login"></input>
 </div>
</g:form>
</g:else>


This page will be used across all pages, that is why I decided to create it as a template. It checks for a session, and if found it displays the person logged in or else displays the login input boxes.

The form which has the input boxes for email ID and password are submitting to a doLogin. This method must be defined within the PersonController.groovy as well.

def doLogin = {
  def user = Person.findWhere(emailID:params['emailID'],loginPassword:params['loginPassword'])
  session.user = user
  if (user){
    redirect(controller:'person',action:'list')
    flash.message = "Logged in as <b>$user.firstName $user.lastName ($user.emailID)</b>"
  }else{
    redirect(controller:'person',action:'login')
    flash.message = "Invalid Username/Password, please try again."
  }
}

This method extracts values from params variable which will have all input boxes value. By checking using Person.findWhere by passing these parameters (Email ID &amp; Login Password) we will get some value to user object. If user variable was null then we assume that it is an invalid login and once more redirect to login page. If the validation was successfull, this will redirect to Person/List page.

Download Application Note: The application uses Grails 2

Bug Tracker Application - biTracker

Posted by Anantha Narayanan On 3:52 PM

This application can be used to track issues/bugs which might be arising in development.

The features include:
  • User defined resource names 
  • User defined browser names (in case of browser based application for checking compatibility) 
  • User defined pages/program units 
  • User defined environments (like uat/development etc) 
  • User defined severity status 
  • Issues/bugs are searchable using searchable plugin 

This application is intented to be a starting place wherein MS-Excel sheets can be replaced and the bugs/issues could be saved to Oracle database.

The configuration for connecting to oracle can be done by modifying the file DataSource.groovy inside grails-app/conf folder. 

Download the source and execute this application and serve your clients much better.

Request your help in improving this and making it a full-fledged application. Please share your valuable comments below.

What is SCAFFOLD?

Posted by Anantha Narayanan On 10:48 PM

Scaffold in normal English means

"scaf·fold·ing/ˈskafəldiNG/Noun:
  1. A temporary structure on the outside of a building, made of wooden planks and metal poles, used by workers while building, repairing, or...
  2. The materials used in such a structure."

In Grails and some more "Model-View-Controller (MVC for short)" frameworks this term is used to describe the automatic "Create-Read-Update-Delete" database functions that are constructed and executed at run time.

For example if you have defined a domain class in Grails, the table can be created by the framework. More, Grails also allows you to have web interface for the domain automatically for the said operations on your table:
  • CREATE (INSERT)
  • READ (QUERY)
  • UPDATE
  • DELETE
These above operations are termed as scaffolding or CRUD in Grails.

A real use of a SCAFFOLD is in prototyping your design, wherein most of these code does not make much importance to you. Once the design is frozen you may move to more secure and customized way of CRUD operations.

Automatic Scaffold Controller

Posted by Anantha Narayanan On 10:39 PM

By default if you are creating a controller using the following command:

grails create-controller org.example.DomainClass

Suppose your controller is based on an existing DomainClass, you might want to jump start using scaffolding.

You might be opening the controller file and commenting the code which Grails has created for you.

class DomainClassController {

  def index = { }

}
You might be adding the magic keyword that allows scaffolding later.

class DomainClassController {

  //def index = { }

  def scaffold = true

}
If you have many number of controllers to be created for prototyping and want to avoid this commenting and copy/paste activities use the following command:

grails create-scaffold-controller org.example.DomainClass

Grails will generate the controller with scaffold magic keyword by default.

Hope you like this tip (if you are a beginner of Grails and if you are cursing with prototyping for numerous controllers).

Recommended Post Slide Out For Blogger