Design Forms: Play2.0 Scala Mysql                                                                           Ruchi Jindal  ...
Agenda  Create a new Project In play                                           Design Signup Template  Connectivity wit...
Create a new Project In play
Create a new Project In play
Create a new Project In play$:~/Desktop/knolx $ play new FormDemoInPlaySelect Application nameSelect application TemplateA...
Application hierarchy would be like this
Connectivity With Mysql
Steps Required for Mysql ConnectivityStep #1 create new schemamysql> create database FORMDEMOStep #2 add mysql connector d...
Step #4 Add 1.sqlconf → evolutions → default → 1.sqlStep #5 Add mysql driver and default url in application.confdb.default...
use `FORMDEMO`;DROP TABLE if exists EMPLOYEE_DETAIL;DROP TABLE if exists EMPLOYEE;CREATE TABLE `FORMDEMO`.`EMPLOYEE` (  `E...
CREATE TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` (  `EMPLOYEE_DETAIL_ID` INT NOT NULL AUTO_INCREMENT ,  `EMPLOYEE_ID` INT NOT NUL...
Add Twitter Bootstrap
Steps Required To Add twitter BootstrapStep #1 Download bootstrap.min.css fromhttp://twitter.github.com/bootstrap/Step #2 ...
Design Main template
Steps Required To Desin Main templateStep #1 Add Title and Content@(title: Html)(content: Html)Step #2 Set Header,Navigati...
@(title: Html)(content: Html)<!DOCTYPE html><html>    <head>        <title>@title</title>        <link rel="stylesheet" me...
Main Template View
Design index.html.scala template
Steps Required To Design Index FormStep #1 add case class for employee in app->models->Models.scalacase class Employee(id:...
@(signinForm:Form[Employee],message:String)@import helper._@import helper.twitterBootstrap._@title = {    Form Demo in Pla...
Design Model For Employee Entityobject Employee {/**      * Parse a Employee from a ResultSet      */    val simple = {   ...
Sign In authenticate controller in Application.scala/**    * Authenticate User For Login    */  def authenticateUser = Act...
Design SignUp Form
Steps Required To Design SignUp FormStep #1 Already Have case class for employee in app->models->Models.scalacase class Em...
Step #3 redirect to SignUp pagedef siginUpForm = Action {   val alert: Alert = new Alert("", "")   Common.setAlert(alert) ...
@(signupForm: Form[Employee],message:String)@import helper._@import helper.twitterBootstrap._@title = {    Sign Up Form in...
Design Model For To Register A new User/**  * Register a new employee.  *  * @param employee The computer values.  */ def ...
/**    * Register a new Employee    */  def createEmployee = Action { implicit request =>     signupForm.bindFromRequest.f...
Form demoinplaywithmysql
Form demoinplaywithmysql
Form demoinplaywithmysql
Upcoming SlideShare
Loading in …5
×

Form demoinplaywithmysql

13,310 views

Published on

This presentation emphasis on How to connect a Play Application with Mysql as database in Scala.Play includes a simple data access layer called Anorm that uses plain SQL to interact with the database and provides an API to parse and transform the resulting datasets.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
13,310
On SlideShare
0
From Embeds
0
Number of Embeds
4,448
Actions
Shares
0
Downloads
48
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Form demoinplaywithmysql

  1. 1. Design Forms: Play2.0 Scala Mysql   Ruchi Jindal                                Software Consultant    Knoldus
  2. 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. 3. Create a new Project In play
  4. 4. Create a new Project In play
  5. 5. Create a new Project In play$:~/Desktop/knolx $ play new FormDemoInPlaySelect Application nameSelect application TemplateApplication would be created with name FormDemoInPlay$:~/Desktop/knolx $ cd FormDemoInPlay/To open project in eclipse$:~/Desktop/knolx /FormDemoInPlay$ play eclipsify
  6. 6. Application hierarchy would be like this
  7. 7. Connectivity With Mysql
  8. 8. Steps Required for Mysql ConnectivityStep #1 create new schemamysql> create database FORMDEMOStep #2 add mysql connector dependency in Build.scala"mysql" % "mysql-connector-java" % "5.1.18"Step #3 create default directoryconf → evolutions → default
  9. 9. Step #4 Add 1.sqlconf → evolutions → default → 1.sqlStep #5 Add mysql driver and default url in application.confdb.default.driver=com.mysql.jdbc.Driverdb.default.url="jdbc:mysql://localhost/FORMDEMO?characterEncoding=UTF-8"db.default.user=rootdb.default.password=rootStep #6 Add mysql script in 1.sql
  10. 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. 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 ;
  12. 12. Add Twitter Bootstrap
  13. 13. Steps Required To Add twitter BootstrapStep #1 Download bootstrap.min.css fromhttp://twitter.github.com/bootstrap/Step #2 Add bootstrap.min.csspublic → stylesheets -> bootstrap.min.css from
  14. 14. Design Main template
  15. 15. Steps Required To Desin Main templateStep #1 Add Title and Content@(title: Html)(content: Html)Step #2 Set Header,Navigation,Content,FooterDecide the page layoutStep #3 Add CSS and Javascripts and add ContentFull code to design main template is as follows:
  16. 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>
  17. 17. Main Template View
  18. 18. Design index.html.scala template
  19. 19. Steps Required To Design Index FormStep #1 add case class for employee in app->models->Models.scalacase class Employee(id: Pk[Int] = NotAssigned, email: String, password: String)Step #2 add play.api.data.Form For SignIn in Application Controllerval signinForm = Form( Forms.mapping( "id" -> ignored(NotAssigned: Pk[Int]), "email" -> email, "password" -> nonEmptyText(minLength = 6))(Employee.apply)(Employee.unapply))Step #3 redirect to index pagedef index = Action { Ok(views.html.index(signinForm, "Form Demo in Play2.0 With Mysql As Database")) }Step #4 set routesGET / controllers.Application.indexPOST /login controllers.Application.authenticateUser
  20. 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. 21. Design Model For Employee Entityobject 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. 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 someerror")), 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) } } }) }
  23. 23. Design SignUp Form
  24. 24. Steps Required To Design SignUp FormStep #1 Already Have case class for employee in app->models->Models.scalacase 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 dont match", passwords => passwords._1 == passwords._2)) { // Binding: Create a User from the mapping result (ignore the second password and the acceptfield) (email, passwords) => Employee(NotAssigned, email, passwords._1) }{ // Unbinding: Create the mapping values from an existing User value user => Some(user.email, (user.password, ""))})
  25. 25. Step #3 redirect to SignUp pagedef siginUpForm = Action { val alert: Alert = new Alert("", "") Common.setAlert(alert) Ok(views.html.signUpForm(signupForm, "Sign Up Form")) }Step #4 set routesPOST /signUp controllers.Application.createEmployee
  26. 26. @(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> }}
  27. 27. 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() } }
  28. 28. /** * Register a new Employee */ def createEmployee = Action { implicit request => signupForm.bindFromRequest.fold( errors => BadRequest(views.html.signUpForm(errors, "There issome 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 IdAlready Exist")) } }) }

×