1

我附上了我的代码

应用程序(控制器)

package controllers

import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models.Task
import java.io._

object Application extends Controller {

 val taskForm = Form(
    tuple(
  "id"    -> number,
  "label" -> nonEmptyText(minLength = 4),
  "add"   -> nonEmptyText
  )
  )
def index = Action {
  Redirect(routes.Application.tasks)
}
def tasks = Action {
  Ok(views.html.index(Task.all(),taskForm))
}
def showTask= Action {
  Ok(views.html.test(Task.all(), taskForm))
}

def newTask = Action { implicit request =>
  taskForm.bindFromRequest.fold(
    errors => BadRequest(views.html.index(Task.all(), errors)),
    {
    case(id,label,add) => {
      Task.create(id,label,add)
      Redirect(routes.Application.showTask)
    }
  }
  )
}

  def deleteTask(id: Int) = Action {
  Task.delete(id)
  Redirect(routes.Application.showTask)
}

}

任务(模型)

package models
import anorm._
import anorm.SqlParser._
import play.api.db._
import play.api.Play.current



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

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

}

我不知道在哪里声明编写器函数。请帮助我的语法,我需要将表单元素写入文本文件.. 提前谢谢

4

1 回答 1

2

假设您想在添加新任务时附加文本(即newTask由 Play 调用)。

你可以在你的方法中定义一个辅助函数object Application并使用这个辅助newTask方法。

object Application extends Controller {
//...
import java.io.FileWriter

  val filePath = """ path to file """
  def writingToFile(str: String) = {
     val fw = new FileWriter(filePath, true)
    try {
      fw.write(str)
    } finally {
      fw.close()
    }
  }

  def newTask = Action { implicit request =>
  taskForm.bindFromRequest.fold(
    errors => BadRequest(views.html.index(Task.all(), errors)),
    {
    case(id,label,add) => {
      /* Call the helper function to append to the file */
      writingToFile(s"id : $id, label : $label, add : $add \n")
      Task.create(id,label,add)
      Redirect(routes.Application.showTask)
    }
  }
  )
}
//..
}

同样,当调用其他方法时,您可以以类似的方式附加到文件中。
希望能帮助到你 :)

于 2013-09-25T12:51:45.023 回答