播放2-Scala-表单验证器和单选按钮 [英] Play 2 - Scala - Forms Validators and radio buttons

查看:74
本文介绍了播放2-Scala-表单验证器和单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为此模型提供一个带有验证器的表单:

I'm need render a Form with validators for this model:

型号:

    case class Service (
        name: String, description: String, unitcost: Long,
            typo: Char, isactive: Char, modifiedby: String)

控制器:

    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)
    )

此代码在[Char] 的每个上均失败,表示需要导入play.api.data.format.Formats._ 但是我是..

我的第二个疑问是如何为每个(对号和无效)设置单选按钮对 认为错字有"M"和"A"之类的选项,而无效的则有"Y"和"N".

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:我想在……之后使用持久性模型来解决这个问题.

PD: I think put this using a persistence model after...

推荐答案

该错误表明表单不知道如何处理Char类型.没有为Char类型定义默认值.

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. 将类型从Char更改为存在默认FormatterString
  2. Char提供一个Formatter
  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)
}

这篇关于播放2-Scala-表单验证器和单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆