Play2.0:TODOリストを作成する

こちらで紹介されているTODOリストが最終的にどうなるかをまとめました
初めて作ったときにどこのソースに追加するのか少し迷ったので参考までに。

Application.scala

package controllers

import play.api._
import play.api.mvc._

object Application extends Controller {
  
  def index = Action {
    Redirect(routes.Application.tasks)
  }
  
  def tasks = Action {
    Ok(views.html.index(Task.all(), taskForm))
  }
  
  def newTask = Action { implicit request =>
    taskForm.bindFromRequest.fold(
      errors => BadRequest(views.html.index(Task.all(), errors)),
      label => {
        Task.create(label)
        Redirect(routes.Application.tasks)
      }
    )
  }
  
  def deleteTask(id: Long) = Action {
    Task.delete(id)
    Redirect(routes.Application.tasks)
  }
  
}

Task.scala

package models

import play.api.data._
import play.api.data.Forms._
import anorm._
import anorm.SqlParser._

case class Task(id: Long, label: String)

object Task {

  val taskForm = Form(
    "label" -> nonEmptyText
  )

  val task = {
    get[Long]("id") ~ 
    get[String]("label") map {
      case id~label => Task(id, label)
    }
  }
  
  def all(): List[Task] = DB.withConnection { implicit c =>
    SQL("select * from task").as(task *)
  }
  
  def create(label: String) {
    DB.withConnection { implicit c =>
      SQL("insert into task (label) values ({label})").on(
        'label -> label
      ).executeUpdate()
    }
  }

  def delete(id: Long) {
    DB.withConnection { implicit c =>
      SQL("delete from task where id = {id}").on(
        'id -> id
      ).executeUpdate()
    }
  }
  
}

index.scala.html

@(tasks: List[Task], taskForm: Form[String])

@import helper._

@main("Todo list") {
    
    <h1>@tasks.size task(s)</h1>
    
    <ul>
        @tasks.map { task =>
            <li>
                @task.label
                
                @form(routes.Application.deleteTask(task.id)) {
                    <input type="submit" value="Delete">
                }
            </li>
        }
    </ul>
    
    <h2>Add a new task</h2>
    
    @form(routes.Application.newTask) {
        
        @inputText(taskForm("label")) 
        
        <input type="submit" value="Create">
        
    }
}

以上に加えて

  • conf/application.conf
  • conf/routes
  • conf/evolutions/default/1.sql

を編集することで、アプリケーションを起動できるようになるかと思います。
自分でアプリケーションを作っていろいろいじって遊んでみましょう!

近いうちにTODOリストへのテストやログイン画面の作成なんかをやります。たぶん。