问题
I'm need render a Form with validators for this model:
Model:
case class Service (
name: String, description: String, unitcost: Long,
typo: Char, isactive: Char, modifiedby: String)
Controller:
import play.api.data.Form
import play.api.data._
import play.api.data.format.Formats._
import play.api.data.Forms._
object Services extends Controller {
....
....
private val servicesForm[Service] = Form(
mapping(
"name" -> nonEmptyText.verifying(
"validation.name.duplicate", Service.findByName(_).isEmpty),
"description" -> nonEmptyText,
"unitcost" -> longNumber,
"typo" -> of[Char],
"isactive" -> of[Char],
"modifiedby" -> nonEmptyText
) (Service.apply)(Service.unapply)
)
This code fails on every of[Char] saying that its needed import play.api.data.format.Formats._
but I was..
My second doubt is about how to put a radio button pair for each (typo and isactive)
thinking that typo has "M" and "A" like options and isactive has "Y" and "N".
PD: I think put this using a persistence model after...
回答1:
The error indicates that the Form does not know how to handle the Char
type. There is no default defined for the Char
type.
To solve the problem you have two options:
- Change the type from
Char
toString
for which a defaultFormatter
exists - Supply a
Formatter
forChar
A formatter would look something like this (note that it does not have the correct error handling)
implicit val charFormat = new Formatter[Char] {
def bind(key: String, data: Map[String, String]):Either[Seq[FormError], Char] =
data.get(key)
.filter(_.length == 1)
.map(_.head)
.toRight(Seq(FormError(key, "error.required", Nil)))
def unbind(key: String, value: Char) = Map(key -> value.toString)
}
来源:https://stackoverflow.com/questions/13054920/play-2-scala-forms-validators-and-radio-buttons