Play 2 - Scala - Forms Validators and radio buttons

倾然丶 夕夏残阳落幕 提交于 2020-01-03 16:37:01

问题


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:

  1. Change the type from Char to String for which a default Formatter exists
  2. Supply a Formatter for Char

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!