|
| 1 | +package controllers |
| 2 | + |
| 3 | +import play.api._ |
| 4 | +import play.api.mvc._ |
| 5 | +import play.api.data._ |
| 6 | +import play.api.data.Forms._ |
| 7 | +import play.api.data.validation.Constraints._ |
| 8 | + |
| 9 | +import views._ |
| 10 | + |
| 11 | +import models._ |
| 12 | + |
| 13 | +import play.api.i18n._ |
| 14 | +import scala.jsvalidation.PlayLMS._ |
| 15 | + |
| 16 | +object Comments extends Controller { |
| 17 | + |
| 18 | + val commentForm: Form[Comment] = Form( |
| 19 | + mapping( |
| 20 | + "firstname" -> nonEmptyText, |
| 21 | + "lastname" -> nonEmptyText, |
| 22 | + "company" -> optional(text), |
| 23 | + "email" -> email, |
| 24 | + "phone" -> optional(text verifying jsPattern("""[0-9.+]+""", "constraint.phone", "A valid phone number is required")), |
| 25 | + "message" -> nonEmptyText |
| 26 | + )(Comment.apply)(Comment.unapply) |
| 27 | + ) |
| 28 | + |
| 29 | + lazy val js = generateJS(Messages(_), twitterBootstrap = true, playDefaults = true)(commentForm.mapping) |
| 30 | + |
| 31 | + /** |
| 32 | + * Display an empty form. |
| 33 | + */ |
| 34 | + def form = Action { |
| 35 | + Ok(html.comment.form(js, commentForm)); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Display a form pre-filled with an existing Comment. |
| 40 | + */ |
| 41 | + def editForm = Action { |
| 42 | + val existingComment = Comment( |
| 43 | + "Nada", "Amin", Some("EPFL"), "namin@alum.mit.edu", Some("41.79.275.15.35"), "I love Scala." |
| 44 | + ) |
| 45 | + Ok(html.comment.form(js, commentForm.fill(existingComment))) |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Handle form submission. |
| 50 | + */ |
| 51 | + def submit = Action { implicit request => |
| 52 | + commentForm.bindFromRequest.fold( |
| 53 | + errors => BadRequest(html.comment.form(js, errors)), |
| 54 | + comment => Ok(html.comment.summary(comment)) |
| 55 | + ) |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments