SlideShare une entreprise Scribd logo
1  sur  31
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)
              }
          }
       })
  }
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

Contenu connexe

Tendances

Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayConRuby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
heikowebers
 

Tendances (18)

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

Similaire à Form demoinplaywithmysql

Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
Azharul Haque Shohan
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
references
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 

Similaire à Form demoinplaywithmysql (20)

Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 
Login and Registration form using oop in php
Login and Registration form using oop in phpLogin and Registration form using oop in php
Login and Registration form using oop in php
 
Practical PHP by example Jan Leth-Kjaer
Practical PHP by example   Jan Leth-KjaerPractical PHP by example   Jan Leth-Kjaer
Practical PHP by example Jan Leth-Kjaer
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Tutorial asp.net
Tutorial  asp.netTutorial  asp.net
Tutorial asp.net
 
Pengenalan AngularJS
Pengenalan AngularJSPengenalan AngularJS
Pengenalan AngularJS
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
PHP || [Student Result Management System]
PHP || [Student Result Management System]PHP || [Student Result Management System]
PHP || [Student Result Management System]
 
Training in Asp.net mvc3 platform-apextgi,noida
Training in Asp.net mvc3 platform-apextgi,noidaTraining in Asp.net mvc3 platform-apextgi,noida
Training in Asp.net mvc3 platform-apextgi,noida
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Web2py
Web2pyWeb2py
Web2py
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 

Plus de Knoldus Inc.

Plus de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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) } } }) }
  • 23.
  • 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")) } }) }