我有一张表格
case class UserUpdateForm(
id:Long, name: String,
remark: Option[String], location: Option[String])
我将字段定义为
"id" -> of[Long],
"remarks" -> optional(text)
备注字段为None
,而不是Some("")
我除外,
那么,如何将空字符串绑定到可选文本字段
答案 0 :(得分:2)
case class OptionalText(wrapped: Mapping[String], val constraints: Seq[Constraint[Option[String]]] = Nil) extends Mapping[Option[String]] {
override val format: Option[(String, Seq[Any])] = wrapped.format
val key = wrapped.key
def verifying(addConstraints: Constraint[Option[String]]*): Mapping[Option[String]] = {
this.copy(constraints = constraints ++ addConstraints.toSeq)
}
def bind(data: Map[String, String]): Either[Seq[FormError], Option[String]] = {
data.keys.filter(p => p == key || p.startsWith(key + ".") || p.startsWith(key + "[")).map(k => data.get(k)).collect { case Some(v) => v }.headOption.map { _ =>
wrapped.bind(data).right.map(Some(_))
}.getOrElse {
Right(None)
}.right.flatMap(applyConstraints)
}
def unbind(value: Option[String]): (Map[String, String], Seq[FormError]) = {
val errors = collectErrors(value)
value.map(wrapped.unbind(_)).map(r => r._1 -> (r._2 ++ errors)).getOrElse(Map.empty -> errors)
}
def withPrefix(prefix: String): Mapping[Option[String]] = {
copy(wrapped = wrapped.withPrefix(prefix))
}
val mappings: Seq[Mapping[_]] = wrapped.mappings
}
val textOpt = new OptionalText(text)
最后,我复制了OptionalMapping类并排除了空的过滤器部分
答案 1 :(得分:0)
基本上,"remarks" -> optional(text)
当None
为空字符串时,将始终返回text
。因此,不要将空字符串视为无更新的标志,而是使用原始值填充表单中的remarks
字段,然后在将其取回后:
remarks match {
case None => // set remarks to ""
case originalRemark => // do nothing
case _ => // set remarks to the new value
}
希望它有所帮助。这是我在Stack Overflow上的第一篇文章:)
答案 2 :(得分:-1)
使用
"remarks" -> default(text, "")