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

[sourcecode language=”scala” wraplines=”false” collapse=”false”]

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

[/sourcecode]

Step 3: API for login in routes file

routes file contains:

conf/routes

[sourcecode language=”scala” wraplines=”false” collapse=”false”]

POST   /login        controllers.Application.authenticateUser

[/sourcecode]

Step 4: Design a SiginForm with validations.

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

app/views/index.scala.html

[sourcecode language=”scala” wraplines=”false” collapse=”false”]

@(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>

}
}

[/sourcecode]

Step 5: Code For Controller

The scala version, accessing the body:

app/controllers/Application.scala

[sourcecode language=”scala” wraplines=”false” collapse=”false”]

//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))
}
})
}[/sourcecode]

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

Model code for connectivity with database:

models.User

[sourcecode language=”scala” wraplines=”false” collapse=”false”]

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"))[/sourcecode]

Output of above snippets :

Form View :

Selection_003

Validations Applied View :

Selection_002

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

3 thoughts on “Design Forms In Play2.0 using Scala and Mongodb

Leave a Reply

%d bloggers like this: