Design Forms In Play2.0 using Scala and Mongodb


The play.api.data package contains several helpers to handle HTTP form data submission and validation.

In This blog we would learn how to design forms with validations in play2.0 using scala and how to communicate  with database using mongodb.

Step 1: Create New Project in play2.0 lets say FormDemoInPlay

Step 2: Dependency for Mongodb In Build.scala


"com.novus" %% "salat" % "1.9.1"

Step 3: API for login in routes file

routes file contains:

conf/routes


POST   /login        controllers.Application.authenticateUser

Step 4: Design a SiginForm with validations.

For this quick sample, let’s define the following view:

app/views/index.scala.html


@(loginForm:Form[LoginForm],message:String)
@import helper._
@import helper.twitterBootstrap._

@title = {
 Form Demo in Play2.0
}

@main(title) {
 @helper.form(action = routes.Application.authenticateUser) {
 <fieldset>
 <legend>@message</legend>

 @inputText(
 loginForm("email"), '_label -> "Email ",
 '_help -> "Enter a valid email address."
 )

 @inputPassword(
 loginForm("password"),
 '_label -> "Password",
 '_help -> "A password must be at least 6 characters. "
 )

 </fieldset>

 <div>
<input type="submit" value="Log in ">
Or
<small><a href="@routes.Application.siginUpForm">Sign Up </a></small>
</div>

 }
}

Step 5: Code For Controller

The scala version, accessing the body:

app/controllers/Application.scala


//Case Class to map with Form

case class LoginForm(email: String, password: String)

object Application extends Controller {

//Play Form for emailid & password
 val loginForm = Form(
 Forms.mapping(
 "email" -> email,
 "password" -> nonEmptyText(minLength = 6))(LoginForm.apply)(LoginForm.unapply))

def index = Action {
 Ok(views.html.index(loginForm, "Form Demo in Play2.0"))
 }

//Code to authenticate User
 def authenticateUser = Action { implicit request =>
 loginForm.bindFromRequest.fold(
 errors => BadRequest(views.html.index(errors, "There is some error")),
 logInForm => {
 val email = logInForm.email
 val password = logInForm.password
 val users = User.findUser(email, password)
 users.isEmpty match {
 case true => Ok(views.html.index(loginForm, "Invalid Credentials"))
 case false =>
 val userEntity = users(0)
 Ok(views.html.userDetail(userEntity))
 }
 })
 }

Step 6: Code For User Model & For Connectivity with MongoDb

Model code for connectivity with database:

models.User


import com.mongodb.casbah.commons.MongoDBObject
import org.bson.types.ObjectId
import com.novus.salat.dao.SalatDAO
import com.novus.salat.global.ctx
import com.mongodb.casbah.Imports.WriteConcern
import com.mongodb.casbah.MongoConnection
import com.novus.salat.annotations.Key
import utils.MongoHQConfig

case class UserEntity(
 @Key("_id") id: ObjectId,
 emailId: String,
 password: String)

object User {

/**
 * Authenticate User By Credentials Provided
 *
 * @param emailId is emailId of user to be searched
 * @param password is password of user to be searched
 */
 def findUser(emailId: String, password: String): List[UserEntity] = {
 UserDAO.find(MongoDBObject("emailId" -> emailId, "password" -> password)).toList
 }

}
/**
 * Instantiate UserDAO
 * Access the settings from MongoHQConfig file
 */
object UserDAO extends SalatDAO[UserEntity, ObjectId](collection = MongoHQConfig.mongoDB("user"))

Output of above snippets :

Form View :

Selection_003

Validations Applied View :

Selection_002

Entire code can be found here: https://github.com/knoldus/FormDemoInPlay

About ruchijindal

Software Engineer in Knoldus
This entry was posted in Scala and tagged , , . Bookmark the permalink.

3 Responses to Design Forms In Play2.0 using Scala and Mongodb

  1. Pingback: Formulários em Play2.0 : Scala + Mongodb | Blog de Programação Literati

  2. Pingback: Votre application Scala, Play 2 et MongoDB en six étapes | Loïc Knuchel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s