获取带有重复元素的表单约束



我的最终目标是将*附加到每个相关字段为强制性的标签后面。

问题是,在FieldElements.constraints中,如果我有一个元素列表,则没有约束。

下面的代码示例显示了带有地址列表的表单:

object Forms {
  val testForm: Form[TestForm] = Form {
    val address = mapping(
      "addressLine" -> nonEmptyText,
      "city"        -> nonEmptyText,
      "country"     -> nonEmptyText.verifying(nonEmpty)
    )(Address.apply _)(Address.unapply)
    // to form mapping for TestForm  
    mapping(
      "mand_string" -> nonEmptyText,
      "non_mand_string" -> optional(text),
      "address_history" -> list(address) // repeated values are allowed for addresses
    )( TestForm.apply _ )( TestForm.unapply )
  }
}

下面是将*s添加到必填字段的字段构造函数逻辑:

object MyHelpers {
  implicit val myFields = FieldConstructor( fieldElem => {
    Logger.debug( "Label = " + fieldElem.label )
    Logger.debug( "Constraints = " + fieldElem.field.constraints )
    val new_elem = fieldElem.copy( args = appendAsteriskToMandatoryFields(fieldElem) )
    views.html.fs1(new_elem)
  })
  /** Adds a * to the end of a label if the field is mandatory
   * 
   */
  private def appendAsteriskToMandatoryFields(fieldElem: FieldElements): Map[Symbol,Any] = {
    fieldElem.args.map{ case(symbol, any) => 
      if(symbol == '_label && isRequiredField(fieldElem)){ 
        (symbol, any + "*")
      } else { 
        symbol -> any 
      }
    }
  }
  /** Does this element have the constraint that it is required?
   * 
   */
  private def isRequiredField(fieldElem: FieldElements): Boolean = {
    fieldElem.field.constraints.exists{case(key, _) => key == "constraint.required"}
  }
}

我希望看到*s附加到除non_mand_string以外的所有表单元素,但这里是结果页面:http://s29.postimg.org/5kb5u2hjb/Screen_Shot_2014_08_05_at_1_49_17_PM.png

只有man_string有一个*。地址字段中没有预期的*s

下面是日志的输出:

[debug] application - Label = Mandatory String
[debug] application - Constraints = List((constraint.required,WrappedArray()))
[debug] application - Label = Non-Mandatory String
[debug] application - Constraints = List()
[debug] application - Label = Address Line
[debug] application - Constraints = List()
[debug] application - Label = City
[debug] application - Constraints = List()
[debug] application - Label = Country
[debug] application - Constraints = List()

是否有可能分配这些约束,这样我就不必手动添加*s到我的应用程序中的每个列表实例?

提前感谢。

我今天一直在努力解决这个问题:我正在使用@repeat helper,我发现约束被绑定到单个重复字段的名称(即。"field_name"),而不是每个重复字段(例如:"field_name[0]")

到目前为止,我找到的解决方案只是重建字段,使用正确的约束。

@repeat(theForm("repeated_field")) { field =>
            @myInputNumber(
                Field(
                    form = theForm, name = "name", 
                    constraints = theForm.constraints.find(_._1 == "repeated_field").get._2,
                    format = field("field_name").format,
                    errors = field("field_name").errors,
                    value = field("field_name").value
                ))
    }

当然,这段代码只是一个示例,您可能应该检查空约束或现有约束。

希望能有所帮助,Pietro

最新更新