使用播放框架的纯动态表单 [英] Purely Dynamic forms using play framework

查看:74
本文介绍了使用播放框架的纯动态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Play 2.2应用程序,该应用程序通过外部Web服务获取带有字段名称,类型和约束信息的JSON; JSON的内容每次都可以不同(尽管总体结构保持不变,只是字段数等不同). 现在的要求是根据收到的字段定义呈现HTML表单. 有人可以建议这样做的最好方法是什么(我认为通常的播放形式在这里不会非常有用,除非有人可以告诉您如何创建动态的MappingForm对象). 我的想法之一是将JSON发送到客户端,并使用Angular呈现表单,但是我不确定如何在服务器端进行验证.

I have a Play 2.2 application which gets, thru an external web service, a JSON with field name, type and constraints info ; the content of this JSON can be different every time (though the overall structure stays same, with just the difference in number of fields etc.). Now the requirement is to render a HTML form based on the field definition received. Can someone advise what would be the best way to do this (I don't think the usual play-forms can be very useful here, unless someone can tell how to create a dynamic Mapping, Form objects). One of the ideas I had was to send the JSON to client side and use Angular to render the form but then I am not sure how will I validate that on server side.

推荐答案

播放表单是类型安全的,这意味着表单内容是静态定义的(即元组或案例类).您将必须编写代码来动态生成表单并解析结果.

Play forms are type-safe, which means that the form contents are statically defined (i.e. a tuple or a case class). You will have to write code to generate the form dynamically and to parse the results.

为表单生成HTML太复杂了,无法在Scala模板中完成.我建议在对象中编写一个函数来执行此操作,例如:

Generating the HTML for the form is a bit too complex to do in a Scala template. I recommend writing a function in an object to do this, eg:

object MyHelpers {
  def makeForm(js: JsObject): Html = {
    val xml = 
    <form method="post">
      { js.values.map { e =>
        <input type=text name={e._1} value={e._2}/>
      }}
    </form>

    Html(xml.toString)
  }
}

然后将函数导入模板:@import MyHelpers.makeForm,并在页面中需要表单的位置调用它.

Then import the function in your template: @import MyHelpers.makeForm, and call it at the point in your page where you want the form.

使用Action(在这种情况下必须在您的路由文件中将其指定为POST)来解析表单结果:

Parse the form result with an Action (which in this case must be specified as a POST in your routes file) like so:

def myFormHandler(parse.multipartFormData) { request =>
  val data = for ((key, values) <- request.body.dataParts) yield {
    // validate and process field
  }

  OK(view.html.myform())
}

(如果您的操作是GET,而您可能不想使用,请使用parse.asFormUrlEncoded)

(If your action is a GET, which you probably don't want, use parse.asFormUrlEncoded)

这篇关于使用播放框架的纯动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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