本文整理汇总了Scala中play.api.data.Form类的典型用法代码示例。如果您正苦于以下问题:Scala Form类的具体用法?Scala Form怎么用?Scala Form使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Form类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CreateUserData
//设置package包名称以及导入依赖的类
package forms
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.validation.Constraints._
case class CreateUserData(
name: String,
email: String,
password: String,
passwordConfirmation: String
)
object CreateUserForm {
val userForm: Form[CreateUserData] = Form {
mapping(
"name" -> text.verifying(nonEmpty, maxLength(50)),
"email" -> email.verifying(maxLength(255)),
"password" -> text.verifying(minLength(6)),
"passwordConfirmation" -> text.verifying(minLength(6))
)(CreateUserData.apply)(CreateUserData.unapply)
.verifying("Password does not match", data => data.password == data.passwordConfirmation)
}
}
示例2: UserFeedback
//设置package包名称以及导入依赖的类
package controllers
import play.api.data.Form
import play.api.mvc.{Flash, RequestHeader}
import UserFeedback.{Feedback, Success, Yes, No}
case class UserFeedback(message: String, isError: Boolean) {
def toSeq: Seq[(String, String)] = Seq(
Feedback -> message,
Success -> (if (isError) No else Yes)
)
}
object UserFeedback {
val Feedback = "feedback"
val Success = "success"
val Yes = "yes"
val No = "no"
def success(message: String) = UserFeedback(message, isError = false)
def error(message: String) = UserFeedback(message, isError = true)
def flashed(request: RequestHeader): Option[UserFeedback] =
flashed(request.flash)
def flashed(flash: Flash, textKey: String = Feedback): Option[UserFeedback] =
for {
message <- flash get textKey
isError = (flash get Success) contains No
} yield UserFeedback(message, isError)
def formed(form: Form[_]) =
form.globalError.orElse(form.errors.headOption)
.map(formError => error(formError.message))
}
示例3: getArticles
//设置package包名称以及导入依赖的类
package articles
import play.api.libs.json.Json
import play.api.data.Form
import play.api.data.Forms._
implicit val articleFormatter = Json.format[Article]
private var articles = List(
Article(
"First article",
"Julien",
"""Now that there is the Tec-9, a crappy spray gun from South Miami. This gun is advertised as the most popular gun in American crime. Do you believe that shit? It actually says that in the little book that comes with it: the most popular gun in American crime. Like they're actually proud of that shit. """
),
Article(
"Second awesome blog post",
"Miss Catapulte",
"""You think water moves fast? You should see ice. It moves like it has a mind. Like it knows it killed the world once and got a taste for murder. After the avalanche, it took us a week to climb out. Now, I don't know exactly when we turned on each other, but I know that seven of us survived the slide... and only five made it out. Now we took an oath, that I'm breaking now. We said we'd say it was the snow that killed the other two, but it wasn't. Nature is lethal but it doesn't hold a candle to man."""
)
)
def getArticles = articles
def addArticle(article: Article): Unit = {
articles = articles :+ article
}
def newArticleForm = Form(
mapping(
"title" -> nonEmptyText,
"author" -> nonEmptyText,
"content" -> nonEmptyText
)(Article.apply)(Article.unapply)
)
}
case class Article(title: String, author: String, content: String)
示例4: UserFormData
//设置package包名称以及导入依赖的类
package forms
import play.api.Play
import play.api.data.Form
import play.api.data.Forms._
case class UserFormData(login: String, password: String, user_type: Boolean)
object UserForm {
val form = Form(
mapping(
"login" -> email,
"password" -> nonEmptyText,
"user_type" -> boolean
)(UserFormData.apply)(UserFormData.unapply)
)
}
示例5: MerchantProfileEditForm
//设置package包名称以及导入依赖的类
package forms
import play.api.data.Form
import play.api.data.Forms._
object MerchantProfileEditForm {
val form = Form(
mapping(
"name" -> nonEmptyText,
"about" -> nonEmptyText,
"site" -> nonEmptyText,
"city" -> nonEmptyText
)(Data.apply)(Data.unapply)
)
case class Data(
name: String,
about: String,
site: String,
city: String)
}
示例6: ContactUsController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import model.ContactFormTemplate
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import play.api.Play.current
import play.api.data.validation._
import play.api.i18n.Messages.Implicits._
import services._
import scala.concurrent.Future
class ContactUsController @Inject()(validator: Validation) extends Controller {
val contactUsForm: Form[ContactFormTemplate] = Form(
mapping(
"name" -> nonEmptyText(maxLength = 20),
"email" -> nonEmptyText(maxLength = 30).verifying(validator.emailCheckConstraint),
"description" -> nonEmptyText(maxLength = 50)
)(ContactFormTemplate.apply)(ContactFormTemplate.unapply)
)
def entry = Action {
Ok(views.html.contact(contactUsForm))
}
def postForm = Action.async { implicit request =>
println(request.body)
contactUsForm.bindFromRequest.fold(
formWithErrors => {
Future.successful(BadRequest(views.html.contact(formWithErrors)))
},
UserData => {
Future.successful(Redirect(routes.ContactUsController.success(UserData.name, UserData.email, UserData.description)))
}
)
}
def success(name: String, email: String, description: String) = Action {
Ok(views.html.contactFormConfirmation(name, email, description))
}
}
示例7: SettingsForm
//设置package包名称以及导入依赖的类
package forms
import play.api.data.Form
import play.api.data.Forms._
object SettingsForm {
val form = Form(
mapping(
"piecetype" -> nonEmptyText,
"note" -> text
)(Data.apply)(Data.unapply)
)
case class Data(
piecetype: String,
note: String
)
}
示例8: User
//设置package包名称以及导入依赖的类
package models
import akka.actor.FSM.->
import play.api.data.validation.Constraints._
import play.api.data.format.Formats._
import reactivemongo.bson.{BSONDocumentReader, BSONDocument, BSONDocumentWriter, BSONObjectID}
import play.api.data.{Form, Mapping}
import play.api.data.Forms._
import reactivemongo.bson._
case class User(id:Option[BSONObjectID], user:String,password:String)
object User{
val fldId = "_id"
val fldName = "user"
val fldPassword = "password"
implicit object UserWriter extends BSONDocumentWriter[User]{
def write(user:User):BSONDocument = BSONDocument(
fldId -> user.id.getOrElse(BSONObjectID.generate),
fldName -> user.user,
fldPassword -> user.password
)
}
implicit object UserReader extends BSONDocumentReader[User]{
def read(doc:BSONDocument):User = User(
doc.getAs[BSONObjectID](fldId),
doc.getAs[String](fldName).getOrElse(""),
doc.getAs[String](fldPassword).getOrElse("")
)
}
val form = Form(
mapping(
fldId -> optional(of[String] verifying pattern(
"""[a-fA-F0-9]{24}""".r,
"constraint.objectId",
"error.objectId")),
fldName -> nonEmptyText,
fldPassword -> nonEmptyText){ (id,user,password) =>
User(
id.map(BSONObjectID(_)) ,user,password
)
}{user => Some(user.id.map(_.stringify), user.user, user.password)}
)
}
示例9:
//设置package包名称以及导入依赖的类
package forms
import models.Employee
import play.api.data.Form
import play.api.data.Forms._
val employeeForm = Form(
mapping(
"id" -> optional(longNumber),
"name" -> text.verifying("Name Required", _.nonEmpty),
"address" -> text.verifying("Address Required", _.nonEmpty),
"city" -> text.verifying("City Required", _.nonEmpty),
"county" -> text.verifying("County Required", _.nonEmpty),
"country" -> text.verifying("Country Required", _.nonEmpty),
"postcode" -> text.verifying("Post Code Required", _.nonEmpty),
"phone" -> longNumber,
"email" -> text.verifying("E-Mail Required", _.nonEmpty),
"status" -> text.verifying("Status Required", _.nonEmpty )
)
(Employee.apply)(Employee.unapply)
verifying("Status must equal Active OR Archived", employee => employee.status.matches("Active") || employee.status.matches("Archived"))
)
}
示例10: Products
//设置package包名称以及导入依赖的类
package controllers
import play.api.mvc._
import javax.inject.Inject
import play.api.i18n.{Messages, MessagesApi, I18nSupport}
import play.api.data.Form
import play.api.data.Forms.{mapping, longNumber, nonEmptyText}
import models.Product
class Products @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
def list = Action { implicit request =>
val products = Product.findAll
Ok(views.html.products.list(products))
}
def show(ean: Long) = Action {
implicit request => Product.findByEan(ean).map {
// rendering product details
product => Ok(views.html.products.details(product))
}.getOrElse(NotFound) // return page 404
}
private val productForm: Form[Product] = Form(
mapping(
"ean" -> longNumber.verifying("validation.ean.duplicate", Product.findByEan(_).isEmpty), // form? field? ????
"name" -> nonEmptyText,
"description" -> nonEmptyText
)(Product.apply)(Product.unapply) // form? model ?? mapping
)
def save = Action {
implicit request => val newProductForm = productForm.bindFromRequest()
newProductForm.fold(
hasErrors = {
form => Redirect(routes.Products.newProduct()).
flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
},
success = {
newProduct => Product.add(newProduct)
val message = Messages("products.new.success", newProduct.name)
Redirect(routes.Products.show(newProduct.ean)).flashing("success" -> message)
}
)
}
def newProduct = Action {
implicit request => val form = if (request2flash.get("error").isDefined)
productForm.bind(request2flash.data)
else
productForm
Ok(views.html.products.editProduct(form))
}
}
示例11: SportCenter
//设置package包名称以及导入依赖的类
package controllers
import akka.actor.ActorSystem
import frontend.AuthorizationConfig
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc._
import javax.inject.{Inject, Singleton}
import scala.concurrent.Future
import frontend.AccountModel._
//http://www.tzavellas.com/techblog/2015/02/10/action-composition-in-play-framework/
@Singleton class SportCenter @Inject()(val conf: play.api.Configuration, system: ActorSystem) extends Controller
with jp.t2v.lab.play2.auth.LoginLogout with AuthorizationConfig {
val log: org.slf4j.Logger = akka.event.slf4j.Logger("sport-center")
implicit val ex = system.dispatchers.lookup("akka.stream-dispatcher")
import scala.concurrent.duration._
implicit val timeout = 3 seconds
val loginForm = Form {
mapping(
("login" -> nonEmptyText),
("password" -> nonEmptyText))(authenticate2(log))(_.map(account => (account.login, account.password)))
.verifying("Invalid login or password", _.isDefined)
}
def login(loginError: Boolean) = Action { implicit request =>
if(loginError) BadRequest(views.html.login.login(authenticationErrorForm("authentication error")))
else Ok(views.html.login.login(loginForm))
}
def logout = Action.async { implicit request =>
gotoLogoutSucceeded.map(_.flashing(
("success", "You've been logged out")
))
}
def authenticate = Action.async { implicit request =>
loginForm.bindFromRequest.fold(
{ formWithErrors =>
Future.successful(BadRequest(views.html.login.login(authenticationErrorForm("Login or password is missing"))))
}, { user =>
gotoLoginSucceeded(s"${user.get.id},${user.get.login},${user.get.password},${user.get.permission},${user.get.token}")
}
)
}
}
示例12: conf
//设置package包名称以及导入依赖的类
package frontend
import controllers.routes
import jp.t2v.lab.play2.auth._
import org.joda.time.{DateTime, Interval}
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.Results._
import play.api.mvc._
import scala.collection.mutable
import scala.concurrent.{Future, ExecutionContext}
import scala.reflect.ClassTag
trait AuthorizationConfig extends AuthConfig {
mixin: { def conf: play.api.Configuration } =>
override type Id = String
override type User = frontend.Account
override type Authority = frontend.Permission
override val idTag: ClassTag[Id] = scala.reflect.classTag[Id]
override val sessionTimeoutInSeconds = tokenMaxAge
lazy val intervals: mutable.LinkedHashMap[Interval, String] = loadStages(conf.getObjectList("stages"))
override def resolveUser(id: Id)(implicit ctx: ExecutionContext): Future[Option[User]] = {
val fields = id.split(",")
val id0 = fields(0)
val login = fields(1)
val password = fields(2)
val permission = fields(3)
val token = fields(4)
Future.successful(Option(Account(id0.toInt, login, password, permission, token)))
}
cookieName = conf.getString("http-session.header").getOrElse("AUTH_SESS_ID"),
cookieSecureOption = play.api.Play.isProd(play.api.Play.current),
cookieMaxAge = Some(sessionTimeoutInSeconds)
)
def authenticationErrorForm(errorMessage: String) = Form {
mapping(("login" -> nonEmptyText), ("password" -> nonEmptyText))({(l,r) => None: Option[frontend.Account]})(_ => None)
.verifying("Invalid login or password", result => result.isDefined)
}.withGlobalError(errorMessage)
def loginUrl: String = conf.getString("url.login").get
//should be equal to backend Max-Age
def tokenMaxAge: Int = conf.getInt("http-session.max-age").get
}
示例13: UserFormModel
//设置package包名称以及导入依赖的类
package models
import play.api.data.Form
import play.api.data.Forms._
case class UserFormModel (email: String, password: String)
object UserForm {
var form = Form {
mapping(
"email" -> email,
"password" -> text.verifying("??????4~32????", { p => p.length() >= 4 && p.length <= 32 })
)(UserFormModel.apply)(UserFormModel.unapply)
}
}
case class User(user_id: Option[Long], email: String, password: String, verifyId: String, isVerified: Boolean)
示例14: User
//设置package包名称以及导入依赖的类
package model
import play.api.Play
import play.api.data.Form
import play.api.data.Forms._
case class User(id: Long, firstName: String, lastName: String, mobile: Long, email: String)
case class UserFormData(firstName: String, lastName: String, mobile: Long, email: String)
object UserForm {
val form = Form(
mapping(
"firstName" -> nonEmptyText,
"lastName" -> nonEmptyText,
"mobile" -> longNumber,
"email" -> email
)(UserFormData.apply)(UserFormData.unapply)
)
}
object Users {
var users: Seq[User] = Seq()
def add(user: User): String = {
users = users :+ user.copy(id = users.length) // manual id increment
"User successfully added"
}
def delete(id: Long): Option[Int] = {
val originalSize = users.length
users = users.filterNot(_.id == id)
Some(originalSize - users.length) // returning the number of deleted users
}
def get(id: Long): Option[User] = users.find(_.id == id)
def listAll: Seq[User] = users
}
示例15: LoginData
//设置package包名称以及导入依赖的类
package controllers.landing
import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.{ Inject, Singleton }
import jp.t2v.lab.play2.auth.{ AuthElement, LoginLogout }
import models.document.DocumentService
import models.user.UserService
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Action, Controller }
import scala.concurrent.{ ExecutionContext, Future }
case class LoginData(usernameOrPassword: String, password: String)
@Singleton
class LoginLogoutController @Inject() (
val config: Configuration,
val users: UserService,
implicit val ctx: ExecutionContext,
val messagesApi: MessagesApi
) extends Controller with AuthElement with HasConfig with HasUserService with Security with LoginLogout with I18nSupport {
private val MESSAGE = "message"
private val INVALID_LOGIN = "Invalid Username or Password"
val loginForm = Form(
mapping(
"username" -> nonEmptyText,
"password" -> nonEmptyText
)(LoginData.apply)(LoginData.unapply)
)
def showLoginForm(destination: Option[String]) = Action { implicit request =>
destination match {
case None => Ok(views.html.landing.login(loginForm))
case Some(dest) => Ok(views.html.landing.login(loginForm)).withSession("access_uri" -> dest)
}
}
def processLogin = Action.async { implicit request =>
loginForm.bindFromRequest.fold(
formWithErrors =>
Future(BadRequest(views.html.landing.login(formWithErrors))),
loginData =>
users.validateUser(loginData.usernameOrPassword, loginData.password).flatMap {
case Some(validUser) => gotoLoginSucceeded(validUser.getUsername)
case None => Future(Redirect(routes.LoginLogoutController.showLoginForm()).flashing(MESSAGE -> INVALID_LOGIN))
}
)
}
def logout = Action.async { implicit request =>
gotoLogoutSucceeded
}
}