如何将枚举绑定到播放框架表单? [英] How to bind an enum to a playframework form?

查看:99
本文介绍了如何将枚举绑定到播放框架表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下形式的枚举:

I have an enum of the form:

object MatchFilterType extends Enumeration {
  type MatchFilterType = Value
  val gt = Value("gt")
  val lt = Value("lt")
  val eq = Value("eq")
}

尝试在控制器中创建表单val:

Trying to create a form val in my controller:

 case class SearchRequest(mft: MatchFilterType, queryText: String, locations: List[String])

 val searchForm: Form[SearchRequest] = Form(
    mapping(
      "mft" -> ????????,
      "queryText" -> nonEmptyText,
      "locations" -> list(text)
    )(SearchRequest.apply)(SearchRequest.unapply)
  )

我正在为此项目使用play 2.6.x.

I am using play 2.6.x for this project.

如何在Form val中映射枚举?

How do I map my enumeration in my Form val?

推荐答案

首先创建一个隐式Formatter,该隐式Formatter使用枚举withName方法,该方法采用字符串并将其转换为枚举:

First create an implicit Formatter that uses the enums withName method which takes a string and turns it into an enum:

implicit def matchFilterFormat: Formatter[MatchFilterType] = new Formatter[MatchFilterType] {

  override def bind(key: String, data: Map[String, String]) =
    data.get(key)
        .map(MatchFilterType.withName(_))
        .toRight(Seq(FormError(key, "error.required", Nil)))

  override def unbind(key: String, value: MatchFilterType) = 
    Map(key -> value.toString)
}

然后使用Forms.of创建FieldMapping:

Form(...,
     "mft" -> Forms.of[MatchFilterType],
     ...)

请记住,如果字符串不是枚举成员,则MatchFilterType.withName(_)会引发异常,因此请更新bind方法以根据需要进行处理.

Bear in mind that MatchFilterType.withName(_) will thrown an exception if the string is not an enum member, so update the bind method to handle this as you need.

这篇关于如何将枚举绑定到播放框架表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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