字段构造函数 - 使用重复元素获取表单约束

时间:2014-08-05 17:58:16

标签: forms scala playframework-2.1

我的最终目标是将*附加到相关字段必填的每个标签上。

问题是如果我有一个元素列表,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附加*。没有任何地址字段具有预期的*。

以下是日志的输出:

[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添加到应用程序中的每个列表实例中?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

我今天一直在努力解决这个问题:我使用@repeat帮助器,我发现约束与单个重复字段的名称相关(即&#34 ; 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
                ))
    }

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

希望有所帮助, 彼得