Design Forms: Play2.0 Scala Mysql




                                         
                                  Ruchi Jindal
                                Software Consultant     
                                    Knoldus
Agenda


  Create a new Project In play      
                                     Design Signup Template

  Connectivity with Mysql              – SignUpForm

  Add Twitter Bootstrap                – Models

  Design Main Template                 – Controllers

  Design Index Template                – Routing
    – SignInForm
    – Models
    – Controllers
    – Routing
Create a new Project In play
Create a new Project In play
Create a new Project In play
$:~/Desktop/knolx $ play new FormDemoInPlay

Select Application name

Select application Template

Application would be created with name FormDemoInPlay

$:~/Desktop/knolx $ cd FormDemoInPlay/

To open project in eclipse

$:~/Desktop/knolx /FormDemoInPlay$ play eclipsify
Application hierarchy would be like this
Connectivity With Mysql
Steps Required for Mysql Connectivity
Step #1 create new schema

mysql> create database FORMDEMO

Step #2 add mysql connector dependency in Build.scala

"mysql" % "mysql-connector-java" % "5.1.18"

Step #3 create default directory

conf → evolutions → default
Step #4 Add 1.sql

conf → evolutions → default → 1.sql

Step #5 Add mysql driver and default url in application.conf

db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/FORMDEMO?characterEncoding=UTF-
8"
db.default.user=root
db.default.password=root

Step #6 Add mysql script in 1.sql
use `FORMDEMO`;

DROP TABLE if exists EMPLOYEE_DETAIL;
DROP TABLE if exists EMPLOYEE;


CREATE TABLE `FORMDEMO`.`EMPLOYEE` (
  `EMPLOYEE_ID` INT NOT NULL AUTO_INCREMENT ,
  `EMAIL` VARCHAR(45) NOT NULL ,
  `PASSWORD` VARCHAR(100) NOT NULL ,
  PRIMARY KEY (`EMPLOYEE_ID`) )
ENGINE = InnoDB;
CREATE TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` (
  `EMPLOYEE_DETAIL_ID` INT NOT NULL AUTO_INCREMENT ,
  `EMPLOYEE_ID` INT NOT NULL ,
  `NAME` VARCHAR(45) NOT NULL ,
  `DESIGNATION` VARCHAR(45) NOT NULL ,
  `ADDRESS` VARCHAR(100) NOT NULL ,
  `CONTACT_NO` VARCHAR(20) NOT NULL ,
  PRIMARY KEY (`EMPLOYEE_DETAIL_ID`) ,
  INDEX `fk_EMPLOYEE_DETAIL_1_idx` (`EMPLOYEE_ID` ASC) ,
  CONSTRAINT `fk_EMPLOYEE_DETAIL_1`
    FOREIGN KEY (`EMPLOYEE_ID` )
    REFERENCES `FORMDEMO`.`EMPLOYEE` (`EMPLOYEE_ID` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

ALTER TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` CHANGE COLUMN
`NAME` `NAME` VARCHAR(100) NOT NULL ;
ALTER TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` CHANGE COLUMN
`NAME` `NAME` VARCHAR(80) NOT NULL ;
Add Twitter Bootstrap
Steps Required To Add twitter Bootstrap
Step #1 Download bootstrap.min.css from

http://twitter.github.com/bootstrap/

Step #2 Add bootstrap.min.css

public → stylesheets -> bootstrap.min.css from
Design Main template
Steps Required To Desin Main template
Step #1 Add Title and Content

@(title: Html)(content: Html)

Step #2 Set Header,Navigation,Content,Footer

Decide the page layout

Step #3 Add CSS and Javascripts and add Content

Full code to design main template is as follows:
@(title: Html)(content: Html)
<!DOCTYPE html>
<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen"
href="@routes.Assets.at("stylesheets/bootstrap.min.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")"
type="text/javascript"></script>
        <script src="@routes.Assets.at("javascripts/bootstrap-alert.js")"
type="text/javascript"></script>
    </head>
    <header class="topbar">
             <h1 class="fill">
                 <a href="/">Play 2.0 Form Demo &mdash; MySql</a>
                 <a href="signout" style="float: right;"><input type="button" class="btn primary"
value="Signout"></a>
             </h1>
   </header>
   <section id="main">
   @if(Common.alert.alertType != ""){
         <div class="alert-message @Common.alert.alertType">
               <a class="close" data-dismiss="alert">×</a>
               <strong style="text-transform: capitalize;">@Common.alert.alertType !
</strong>@Common.alert.message
</div>
}
             @content
              <footer><a href="/">Back To Home Page</a></footer>
   </section>
</html>
Main Template View
Design index.html.scala template
Steps Required To Design Index Form
Step #1 add case class for employee in app->models->Models.scala
case class Employee(id: Pk[Int] = NotAssigned, email: String, password: String)
Step #2 add play.api.data.Form For SignIn in Application Controller
val signinForm = Form(
  Forms.mapping(
   "id" -> ignored(NotAssigned: Pk[Int]),
   "email" -> email,
   "password" -> nonEmptyText(minLength = 6))(Employee.apply)(Employee.unapply))
Step #3 redirect to index page
def index = Action {
   Ok(views.html.index(signinForm, "Form Demo in Play2.0 With Mysql As Database"))
 }
Step #4 set routes
GET /                    controllers.Application.index
POST /login              controllers.Application.authenticateUser
@(signinForm:Form[Employee],message:String)
@import helper._
@import helper.twitterBootstrap._
@title = {
    Form Demo in Play2.0 With Mysql As Database
}
@main(title) {
@helper.form(action = routes.Application.authenticateUser) {
        <fieldset>
            <legend>@message</legend>
            @inputText(
                signinForm("email"), '_label -> "Email ",
                '_help -> "Enter a valid email address."
            )
            @inputPassword(
                signinForm("password"),
                '_label -> "Password",
                '_help -> "A password must be at least 6 characters. "
            )
        </fieldset>
         <div class="actions">
            <input type="submit" class="btn primary" value="Log in ">
            Or
            <small><a href="@routes.Application.siginUpForm">Sign Up </a></small>

       </div>

       }


}
Design Model For Employee Entity
object Employee {

/**
      * Parse a Employee from a ResultSet
      */
    val simple = {
       get[Pk[Int]]("employee.employee_id") ~
         get[String]("employee.email") ~
         get[String]("employee.password") map {
           case id ~ email ~ password => Employee(id, email, password)
         }
    }

/**
      * Find Employee Via Email and password
      */
    def authenticate(employee: Employee) = {
       DB.withConnection { implicit connection =>
         val employeeFound = SQL(
           """
             select * from EMPLOYEE
             where EMAIL = {email} and PASSWORD= {password}
           """).on(
             'email -> employee.email,
             'password -> employee.password).as(Employee.simple.singleOpt)
         employeeFound
       }
    }
}
Sign In authenticate controller in Application.scala
/**
    * Authenticate User For Login
    */
  def authenticateUser = Action { implicit request =>
     val alert: Alert = new Alert("", "")
     Common.setAlert(alert)
     signinForm.bindFromRequest.fold(
       errors => BadRequest(views.html.index(errors, "There is some
error")),
       employee => {
          val employeeOpt = Employee.authenticate(employee)
          employeeOpt match {
            case None =>
              Ok("Invalid Credentials")
            case Some(authemployee: Employee) =>
              val userSession = request.session + ("userId" ->
authemployee.id.toString)
                  Ok("Valid User").withSession(userSession)
              }
          }
       })
  }
Form demoinplaywithmysql
Design SignUp Form
Steps Required To Design SignUp Form
Step #1 Already Have case class for employee in app->models->Models.scala
case class Employee(id: Pk[Int] = NotAssigned, email: String, password: String)
Step #2 add play.api.data.Form For SignUp in Application Controller
 val signupForm: Form[Employee] = Form(
   mapping(
    "email" -> email,
    "password" -> tuple(
      "main" -> text(minLength = 6),
      "confirm" -> text).verifying(
        // Add an additional constraint: both passwords must match
        "Passwords don't match", passwords => passwords._1 == passwords._2)) {
      // Binding: Create a User from the mapping result (ignore the second password and the accept
field)
      (email, passwords) => Employee(NotAssigned, email, passwords._1)
    }{
      // Unbinding: Create the mapping values from an existing User value
      user => Some(user.email, (user.password, ""))})
Step #3 redirect to SignUp page
def siginUpForm = Action {
   val alert: Alert = new Alert("", "")
   Common.setAlert(alert)
   Ok(views.html.signUpForm(signupForm, "Sign Up Form"))
 }

Step #4 set routes
POST /signUp                      controllers.Application.createEmployee
@(signupForm: Form[Employee],message:String)
@import helper._
@import helper.twitterBootstrap._
@title = {
    Sign Up Form in Play2.0
}
@main(title) {
    @helper.form(action = routes.Application.createEmployee) {
        <fieldset>
            <legend>@message</legend>
           @inputText(
                signupForm("email"), '_label -> "Email",
                '_help -> "Enter a valid email address."
            )
            @inputPassword(
                signupForm("password.main"),
                '_label -> "Password",
                '_help -> "A password must be at least 6 characters. "
            )
            @inputPassword(
                signupForm("password.confirm"),
                '_label -> "Repeat password",
                '_help -> "Please repeat your password again.",
                '_error -> signupForm.error("password")
            )

        </fieldset>
               <div class="actions">
            <input type="submit" class="btn primary" value="Sign Up">
        </div>

    }

}
Design Model For To Register A new User
/**
  * Register a new employee.
  *
  * @param employee The computer values.
  */

 def insert(employee: Employee): Int = {
   DB.withConnection { implicit connection =>
     SQL(
       """
          insert into EMPLOYEE(EMAIL,PASSWORD) values (
            {email}, {password}
          )
       """).on(
          'email -> employee.email,
          'password -> employee.password).executeUpdate()
   }
 }
/**
    * Register a new Employee
    */
  def createEmployee = Action { implicit request =>
     signupForm.bindFromRequest.fold(
       errors => BadRequest(views.html.signUpForm(errors, "There is
some error")),
       employee => {
          Employee.findByEmployeeEmail(employee.email).isEmpty match {
            case true =>
              Employee.insert(employee)
              val employee_Id = Employee.findMaxEmployeeId
              val userSession = request.session + ("userId" ->
employee_Id.toString)
              Ok("Employee Registered").withSession(userSession)
            case false =>
              val emailExistForm =
Application.signupForm.fill(Employee(NotAssigned, employee.email,
""))
              Ok(views.html.signUpForm(emailExistForm, "Email Id
Already Exist"))
          }
       })
  }
Form demoinplaywithmysql
Form demoinplaywithmysql

More Related Content

KEY
Building Web Service Clients with ActiveModel
KEY
Building Web Service Clients with ActiveModel
PDF
Dig Deeper into WordPress - WD Meetup Cairo
PDF
Presentation technico-commercial-ruby-on-rails
PDF
날로 먹는 Django admin 활용
PDF
Desenvolvimento web com Ruby on Rails (extras)
PDF
Improving state of M2 front-end - Magento 2 Community Project
PDF
Taming forms with React
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
Dig Deeper into WordPress - WD Meetup Cairo
Presentation technico-commercial-ruby-on-rails
날로 먹는 Django admin 활용
Desenvolvimento web com Ruby on Rails (extras)
Improving state of M2 front-end - Magento 2 Community Project
Taming forms with React

What's hot (18)

PDF
Introduction to Active Record - Silicon Valley Ruby Conference 2007
PDF
Contagion的Ruby/Rails投影片
 
PDF
Documentation For Tab Setup
DOCX
Chat php
PPTX
HTML Form Part 1
PDF
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
PDF
[ WrocLoveRb 2012] user perspective testing using ruby
PPTX
Data Binding: Is It the Next Big Thing?
PDF
Acceptance Testing with Webrat
PDF
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
PDF
Rails <form> Chronicle
PDF
ASP.Net, move data to and from a SQL Server Database
TXT
Shell
PDF
Polymer
PDF
AI: Mobile Apps That Understands Your Intention When You Typed
PDF
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
ODP
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Contagion的Ruby/Rails投影片
 
Documentation For Tab Setup
Chat php
HTML Form Part 1
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
[ WrocLoveRb 2012] user perspective testing using ruby
Data Binding: Is It the Next Big Thing?
Acceptance Testing with Webrat
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
Rails <form> Chronicle
ASP.Net, move data to and from a SQL Server Database
Shell
Polymer
AI: Mobile Apps That Understands Your Intention When You Typed
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Ad

Similar to Form demoinplaywithmysql (20)

PPT
Intoduction on Playframework
PDF
Scaling business app development with Play and Scala
PPT
Intorduction of Playframework
PDF
KAAccessControl
PDF
Beyond MVC
PDF
07-spring-boot-spring-mvc-crud spring mvc
PPT
Sample app
PPTX
Angularjs Live Project
PDF
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
PDF
Creating a Facebook Clone - Part XXVIII - Transcript.pdf
PDF
Tapestry: State of the Union
PPT
Play!ng with scala
PDF
full stack practical assignment msc cs.pdf
PPTX
A Groovy Way to Interface With Cascade Server
PDF
Lift Framework
PDF
document
PDF
Dive into Play Framework
PDF
Penetration Testing with Improved Input Vector Identification
PDF
CT xam.pdf
PDF
Scala Frustrations
Intoduction on Playframework
Scaling business app development with Play and Scala
Intorduction of Playframework
KAAccessControl
Beyond MVC
07-spring-boot-spring-mvc-crud spring mvc
Sample app
Angularjs Live Project
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
Creating a Facebook Clone - Part XXVIII - Transcript.pdf
Tapestry: State of the Union
Play!ng with scala
full stack practical assignment msc cs.pdf
A Groovy Way to Interface With Cascade Server
Lift Framework
document
Dive into Play Framework
Penetration Testing with Improved Input Vector Identification
CT xam.pdf
Scala Frustrations
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Recently uploaded (20)

PDF
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
PDF
Human Computer Interaction Miterm Lesson
PDF
Domain-specific knowledge and context in large language models: challenges, c...
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PPTX
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
PPTX
maintenance powerrpoint for adaprive and preventive
PDF
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PDF
State of AI in Business 2025 - MIT NANDA
PPTX
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
PDF
substrate PowerPoint Presentation basic one
PDF
Addressing the challenges of harmonizing law and artificial intelligence tech...
PPTX
How to use fields_get method in Odoo 18
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
Introduction to c language from lecture slides
PDF
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
PDF
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
PDF
Altius execution marketplace concept.pdf
PDF
Ebook - The Future of AI A Comprehensive Guide.pdf
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
Human Computer Interaction Miterm Lesson
Domain-specific knowledge and context in large language models: challenges, c...
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
maintenance powerrpoint for adaprive and preventive
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
State of AI in Business 2025 - MIT NANDA
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
substrate PowerPoint Presentation basic one
Addressing the challenges of harmonizing law and artificial intelligence tech...
How to use fields_get method in Odoo 18
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Introduction to c language from lecture slides
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
Altius execution marketplace concept.pdf
Ebook - The Future of AI A Comprehensive Guide.pdf

Form demoinplaywithmysql

  • 1. Design Forms: Play2.0 Scala Mysql   Ruchi Jindal                                 Software Consultant    Knoldus
  • 2. Agenda  Create a new Project In play  Design Signup Template  Connectivity with Mysql – SignUpForm  Add Twitter Bootstrap – Models  Design Main Template – Controllers  Design Index Template – Routing – SignInForm – Models – Controllers – Routing
  • 3. Create a new Project In play
  • 4. Create a new Project In play
  • 5. Create a new Project In play $:~/Desktop/knolx $ play new FormDemoInPlay Select Application name Select application Template Application would be created with name FormDemoInPlay $:~/Desktop/knolx $ cd FormDemoInPlay/ To open project in eclipse $:~/Desktop/knolx /FormDemoInPlay$ play eclipsify
  • 8. Steps Required for Mysql Connectivity Step #1 create new schema mysql> create database FORMDEMO Step #2 add mysql connector dependency in Build.scala "mysql" % "mysql-connector-java" % "5.1.18" Step #3 create default directory conf → evolutions → default
  • 9. Step #4 Add 1.sql conf → evolutions → default → 1.sql Step #5 Add mysql driver and default url in application.conf db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost/FORMDEMO?characterEncoding=UTF- 8" db.default.user=root db.default.password=root Step #6 Add mysql script in 1.sql
  • 10. use `FORMDEMO`; DROP TABLE if exists EMPLOYEE_DETAIL; DROP TABLE if exists EMPLOYEE; CREATE TABLE `FORMDEMO`.`EMPLOYEE` ( `EMPLOYEE_ID` INT NOT NULL AUTO_INCREMENT , `EMAIL` VARCHAR(45) NOT NULL , `PASSWORD` VARCHAR(100) NOT NULL , PRIMARY KEY (`EMPLOYEE_ID`) ) ENGINE = InnoDB;
  • 11. CREATE TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` ( `EMPLOYEE_DETAIL_ID` INT NOT NULL AUTO_INCREMENT , `EMPLOYEE_ID` INT NOT NULL , `NAME` VARCHAR(45) NOT NULL , `DESIGNATION` VARCHAR(45) NOT NULL , `ADDRESS` VARCHAR(100) NOT NULL , `CONTACT_NO` VARCHAR(20) NOT NULL , PRIMARY KEY (`EMPLOYEE_DETAIL_ID`) , INDEX `fk_EMPLOYEE_DETAIL_1_idx` (`EMPLOYEE_ID` ASC) , CONSTRAINT `fk_EMPLOYEE_DETAIL_1` FOREIGN KEY (`EMPLOYEE_ID` ) REFERENCES `FORMDEMO`.`EMPLOYEE` (`EMPLOYEE_ID` ) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; ALTER TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` CHANGE COLUMN `NAME` `NAME` VARCHAR(100) NOT NULL ; ALTER TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` CHANGE COLUMN `NAME` `NAME` VARCHAR(80) NOT NULL ;
  • 13. Steps Required To Add twitter Bootstrap Step #1 Download bootstrap.min.css from http://twitter.github.com/bootstrap/ Step #2 Add bootstrap.min.css public → stylesheets -> bootstrap.min.css from
  • 15. Steps Required To Desin Main template Step #1 Add Title and Content @(title: Html)(content: Html) Step #2 Set Header,Navigation,Content,Footer Decide the page layout Step #3 Add CSS and Javascripts and add Content Full code to design main template is as follows:
  • 16. @(title: Html)(content: Html) <!DOCTYPE html> <html> <head> <title>@title</title> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/bootstrap.min.css")"> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"> <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")"> <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script> <script src="@routes.Assets.at("javascripts/bootstrap-alert.js")" type="text/javascript"></script> </head> <header class="topbar"> <h1 class="fill"> <a href="/">Play 2.0 Form Demo &mdash; MySql</a> <a href="signout" style="float: right;"><input type="button" class="btn primary" value="Signout"></a> </h1> </header> <section id="main"> @if(Common.alert.alertType != ""){ <div class="alert-message @Common.alert.alertType"> <a class="close" data-dismiss="alert">×</a> <strong style="text-transform: capitalize;">@Common.alert.alertType ! </strong>@Common.alert.message </div> } @content <footer><a href="/">Back To Home Page</a></footer> </section> </html>
  • 19. Steps Required To Design Index Form Step #1 add case class for employee in app->models->Models.scala case class Employee(id: Pk[Int] = NotAssigned, email: String, password: String) Step #2 add play.api.data.Form For SignIn in Application Controller val signinForm = Form( Forms.mapping( "id" -> ignored(NotAssigned: Pk[Int]), "email" -> email, "password" -> nonEmptyText(minLength = 6))(Employee.apply)(Employee.unapply)) Step #3 redirect to index page def index = Action { Ok(views.html.index(signinForm, "Form Demo in Play2.0 With Mysql As Database")) } Step #4 set routes GET / controllers.Application.index POST /login controllers.Application.authenticateUser
  • 20. @(signinForm:Form[Employee],message:String) @import helper._ @import helper.twitterBootstrap._ @title = { Form Demo in Play2.0 With Mysql As Database } @main(title) { @helper.form(action = routes.Application.authenticateUser) { <fieldset> <legend>@message</legend> @inputText( signinForm("email"), '_label -> "Email ", '_help -> "Enter a valid email address." ) @inputPassword( signinForm("password"), '_label -> "Password", '_help -> "A password must be at least 6 characters. " ) </fieldset> <div class="actions"> <input type="submit" class="btn primary" value="Log in "> Or <small><a href="@routes.Application.siginUpForm">Sign Up </a></small> </div> } }
  • 21. Design Model For Employee Entity object Employee { /** * Parse a Employee from a ResultSet */ val simple = { get[Pk[Int]]("employee.employee_id") ~ get[String]("employee.email") ~ get[String]("employee.password") map { case id ~ email ~ password => Employee(id, email, password) } } /** * Find Employee Via Email and password */ def authenticate(employee: Employee) = { DB.withConnection { implicit connection => val employeeFound = SQL( """ select * from EMPLOYEE where EMAIL = {email} and PASSWORD= {password} """).on( 'email -> employee.email, 'password -> employee.password).as(Employee.simple.singleOpt) employeeFound } } }
  • 22. Sign In authenticate controller in Application.scala /** * Authenticate User For Login */ def authenticateUser = Action { implicit request => val alert: Alert = new Alert("", "") Common.setAlert(alert) signinForm.bindFromRequest.fold( errors => BadRequest(views.html.index(errors, "There is some error")), employee => { val employeeOpt = Employee.authenticate(employee) employeeOpt match { case None => Ok("Invalid Credentials") case Some(authemployee: Employee) => val userSession = request.session + ("userId" -> authemployee.id.toString) Ok("Valid User").withSession(userSession) } } }) }
  • 25. Steps Required To Design SignUp Form Step #1 Already Have case class for employee in app->models->Models.scala case class Employee(id: Pk[Int] = NotAssigned, email: String, password: String) Step #2 add play.api.data.Form For SignUp in Application Controller val signupForm: Form[Employee] = Form( mapping( "email" -> email, "password" -> tuple( "main" -> text(minLength = 6), "confirm" -> text).verifying( // Add an additional constraint: both passwords must match "Passwords don't match", passwords => passwords._1 == passwords._2)) { // Binding: Create a User from the mapping result (ignore the second password and the accept field) (email, passwords) => Employee(NotAssigned, email, passwords._1) }{ // Unbinding: Create the mapping values from an existing User value user => Some(user.email, (user.password, ""))})
  • 26. Step #3 redirect to SignUp page def siginUpForm = Action { val alert: Alert = new Alert("", "") Common.setAlert(alert) Ok(views.html.signUpForm(signupForm, "Sign Up Form")) } Step #4 set routes POST /signUp controllers.Application.createEmployee
  • 27. @(signupForm: Form[Employee],message:String) @import helper._ @import helper.twitterBootstrap._ @title = { Sign Up Form in Play2.0 } @main(title) { @helper.form(action = routes.Application.createEmployee) { <fieldset> <legend>@message</legend> @inputText( signupForm("email"), '_label -> "Email", '_help -> "Enter a valid email address." ) @inputPassword( signupForm("password.main"), '_label -> "Password", '_help -> "A password must be at least 6 characters. " ) @inputPassword( signupForm("password.confirm"), '_label -> "Repeat password", '_help -> "Please repeat your password again.", '_error -> signupForm.error("password") ) </fieldset> <div class="actions"> <input type="submit" class="btn primary" value="Sign Up"> </div> } }
  • 28. Design Model For To Register A new User /** * Register a new employee. * * @param employee The computer values. */ def insert(employee: Employee): Int = { DB.withConnection { implicit connection => SQL( """ insert into EMPLOYEE(EMAIL,PASSWORD) values ( {email}, {password} ) """).on( 'email -> employee.email, 'password -> employee.password).executeUpdate() } }
  • 29. /** * Register a new Employee */ def createEmployee = Action { implicit request => signupForm.bindFromRequest.fold( errors => BadRequest(views.html.signUpForm(errors, "There is some error")), employee => { Employee.findByEmployeeEmail(employee.email).isEmpty match { case true => Employee.insert(employee) val employee_Id = Employee.findMaxEmployeeId val userSession = request.session + ("userId" -> employee_Id.toString) Ok("Employee Registered").withSession(userSession) case false => val emailExistForm = Application.signupForm.fill(Employee(NotAssigned, employee.email, "")) Ok(views.html.signUpForm(emailExistForm, "Email Id Already Exist")) } }) }