如何在 Lift 中动态生成输入表单

发布于 2024-11-01 06:45:19 字数 4952 浏览 4 评论 0 原文

我正在开发我的第一个 Lift 项目,并且需要动态生成表单。更准确地说,我有一些由对象表示的操作,这些对象附加了参数列表 - 其中一些是字符串,一些数字,一些布尔值,一些文件。我需要通过表单为其参数提供操作对象的具体值。目前,我只是遍历参数列表并直接以 XML 形式生成表单,但我知道这是极其糟糕的样式 - 我无法绑定输入值,无法绑定要提交的操作,无法应用验证。我被困在传递请求参数上,但我想解决这个问题。不幸的是我必须想出如何做到这一点,所以任何帮助将不胜感激。 我不断发现的所有示例都预先具有固定数量的输入参数。

这是一些相关代码。我希望它足够容易理解(而且我真的很羞于公开展示它:-))

def operationForm(): NodeSeq = {
    val operationCode = S.param("operation").openOr("")
    val operationVariant = S.param("operationVariant").openOr("")

    if (operationCode != "" && !operationVariant.isEmpty) {
      val operation = LighthouseDAOs.operationsRegistry.findByCode(operationCode)
      val params: List[Parameter] = if (operationVariant == "default") {
        operation.getParameters.toList
      } else {
        operation.getParameters.filter(p => p.getVariant == operationVariant).toList
      }

      <lift:surround with="closableBox" at="content">
        <form id="viewOperation" post={"/Deployment/" + S.param("location") + "/" + S.param("deployment")} method="post">
          {params.map(p => getInputElem(p))}
            <input type="submit" style="width: 150px;" value="Execute operation"/>
            <input type="hidden" name="executeOperation" value="true"/>
        </form>
      </lift:surround>
    } else {
      <span></span>
    }
  }

  private def getOperationVariants(operation: Operation): Set[String] = {
    operation.getParameters.map(_.getVariant).toSet
  }

  def operationVariants(deployment: Deployment): NodeSeq = {
    val operationCode = S.param("operation").openOr("")

    if (operationCode != "") {
      val operation = LighthouseDAOs.operationsRegistry.findByCode(operationCode)

      val variants = getOperationVariants(operation)

      if (variants.size > 1) {
        <lift:surround with="closableBox" at="content">
          <table cellspacing="0" cellpadding="0" border="0">
            <tr>
              <th style="width: 160px;">Operation
                {operation.getLongName}
                variants</th>
            </tr>{variants.map(v => {
            <tr>
              <td>
                <a href={Path.path + "Deployment/" + encode(deployment.getLocation) + "/" + encode(deployment.getDeployedComponent.getCode) + "?operation=" + encode(operation.getCode) + "&operationVariant=" + encode(v)}>
                  {v}
                </a>
              </td>
            </tr>
          })}
          </table>
        </lift:surround>
      } else {
        <span></span>
      }
    } else {
      <span></span>
    }
  }

  def getInputElem(param: Parameter): Node = {
    if (param.getChoice != null) {
      <div>
        <label for={param.getName}>
          {param.getName}
        </label>
        <select id={param.getName} name={param.getName}>
          {param.getChoice.flatMap(c => <option value={c}>
          {c}
        </option>)}
        </select>
      </div>
    } else {

      val paramType = param.getType match {
        case Parameter.PASSWORD => "password"
        case Parameter.BOOLEAN => "checkbox"
        case Parameter.CLOB => "file"
        case _ => "text"
      }

      <div>
        <label for={param.getName}>
          {param.getName}
          :</label> <input type={paramType} id={param.getName} name={param.getName} stype="width: 300px;">
        {param.getDefaultValue}
      </input>
      </div>
    }
  }

  def executeOperation(deployment: Deployment): Elem = {
    val operationCode = S.param("operation").openOr("")
    val operationVariant = S.param("operationVariant").openOr("")

    if (S.param("executeOperation").openOr("false") == "true") {
      val op = LighthouseDAOs.operationsRegistry.findByCode(operationCode)
      val params = op.getParameters

      LogLH3.info("Executing operation: " + op.getLongName)

      val operationInstallation = new OperationInstallation();
      operationInstallation.setInstallationLocation(deployment);
      operationInstallation.setInstalledOperation(op);

      val operationCall = new OperationCall(operationInstallation);
      if (operationVariant != "" && operationVariant != "default")
        operationCall.setVariant(operationVariant)

      params.filter(p => p.getVariant == operationVariant).foreach(p => operationCall.addParameterValue(op.createParameterValue(p.getName, S.param(p.getName).openOr(""))))

      try {
        LighthouseDAOs.operationInstallationRegistry.execute(operationCall)
        S.notice("Operation " + op.getLongName + " was executed successfully.")
      } catch {
        case e: Exception => S.error(e.getMessage)
      }
    }

    <span></span>
  }

只是为了记录我正在使用 Lift 2.2 &斯卡拉2.8.1

I'm working on my first Lift project and have the need to generate forms on the fly. To be more precise I have some operations which are represented by objects that have a list of parameters attached to them - some of them are strings, some numbers, some boolean, some files. I need to feed an operation object concrete values for its parameters via a form. Currently I simply traverse the parameter list and generate the form directly as XML, but I know this is extremely bad style - I cannot bind the input values, I cannot bind an action to submit, I cannot apply validation. I'm stuck passing around request params, but I want to fix this. Unfortunately I have to idea how to do this, so any help will be greatly appreciated.
All the example I keep finding have always a fixed number of input parameters upfront.

Here's a bit of related code. I hope it's understandable enough(and I'm really ashamed to publicly show it :-) )

def operationForm(): NodeSeq = {
    val operationCode = S.param("operation").openOr("")
    val operationVariant = S.param("operationVariant").openOr("")

    if (operationCode != "" && !operationVariant.isEmpty) {
      val operation = LighthouseDAOs.operationsRegistry.findByCode(operationCode)
      val params: List[Parameter] = if (operationVariant == "default") {
        operation.getParameters.toList
      } else {
        operation.getParameters.filter(p => p.getVariant == operationVariant).toList
      }

      <lift:surround with="closableBox" at="content">
        <form id="viewOperation" post={"/Deployment/" + S.param("location") + "/" + S.param("deployment")} method="post">
          {params.map(p => getInputElem(p))}
            <input type="submit" style="width: 150px;" value="Execute operation"/>
            <input type="hidden" name="executeOperation" value="true"/>
        </form>
      </lift:surround>
    } else {
      <span></span>
    }
  }

  private def getOperationVariants(operation: Operation): Set[String] = {
    operation.getParameters.map(_.getVariant).toSet
  }

  def operationVariants(deployment: Deployment): NodeSeq = {
    val operationCode = S.param("operation").openOr("")

    if (operationCode != "") {
      val operation = LighthouseDAOs.operationsRegistry.findByCode(operationCode)

      val variants = getOperationVariants(operation)

      if (variants.size > 1) {
        <lift:surround with="closableBox" at="content">
          <table cellspacing="0" cellpadding="0" border="0">
            <tr>
              <th style="width: 160px;">Operation
                {operation.getLongName}
                variants</th>
            </tr>{variants.map(v => {
            <tr>
              <td>
                <a href={Path.path + "Deployment/" + encode(deployment.getLocation) + "/" + encode(deployment.getDeployedComponent.getCode) + "?operation=" + encode(operation.getCode) + "&operationVariant=" + encode(v)}>
                  {v}
                </a>
              </td>
            </tr>
          })}
          </table>
        </lift:surround>
      } else {
        <span></span>
      }
    } else {
      <span></span>
    }
  }

  def getInputElem(param: Parameter): Node = {
    if (param.getChoice != null) {
      <div>
        <label for={param.getName}>
          {param.getName}
        </label>
        <select id={param.getName} name={param.getName}>
          {param.getChoice.flatMap(c => <option value={c}>
          {c}
        </option>)}
        </select>
      </div>
    } else {

      val paramType = param.getType match {
        case Parameter.PASSWORD => "password"
        case Parameter.BOOLEAN => "checkbox"
        case Parameter.CLOB => "file"
        case _ => "text"
      }

      <div>
        <label for={param.getName}>
          {param.getName}
          :</label> <input type={paramType} id={param.getName} name={param.getName} stype="width: 300px;">
        {param.getDefaultValue}
      </input>
      </div>
    }
  }

  def executeOperation(deployment: Deployment): Elem = {
    val operationCode = S.param("operation").openOr("")
    val operationVariant = S.param("operationVariant").openOr("")

    if (S.param("executeOperation").openOr("false") == "true") {
      val op = LighthouseDAOs.operationsRegistry.findByCode(operationCode)
      val params = op.getParameters

      LogLH3.info("Executing operation: " + op.getLongName)

      val operationInstallation = new OperationInstallation();
      operationInstallation.setInstallationLocation(deployment);
      operationInstallation.setInstalledOperation(op);

      val operationCall = new OperationCall(operationInstallation);
      if (operationVariant != "" && operationVariant != "default")
        operationCall.setVariant(operationVariant)

      params.filter(p => p.getVariant == operationVariant).foreach(p => operationCall.addParameterValue(op.createParameterValue(p.getName, S.param(p.getName).openOr(""))))

      try {
        LighthouseDAOs.operationInstallationRegistry.execute(operationCall)
        S.notice("Operation " + op.getLongName + " was executed successfully.")
      } catch {
        case e: Exception => S.error(e.getMessage)
      }
    }

    <span></span>
  }

Just for the record I'm using Lift 2.2 & Scala 2.8.1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宁愿没拥抱 2024-11-08 06:45:19

您可以改进这个示例,使其对设计人员更加友好,但这是基本思想。当然,您需要以某种形式包装它。

基本上,您有一个模板,并将其内容替换为使用 CSS 选择器绑定动态生成的内容。

在您的模板中:

<div class="lift:MyForm.render">
  Form will go here
</div>

片段:

class MyForm extends Snippet {
  def render = {
    val fields = List("a", "b", "c")
    var params: Map[String, String] = ... //or whatever

    def setf(key: String)(value: String) = params = params.updated(key, value)
    def getf(key: String)() = params.get(key)

    "*" #> fields map {
      field =>
        <p>
          <label>{field}</label>{SHtml.text(getf(field) _, setf(field) _)}
        </p>
    }
  }
}

You could improve this example and make it a little bit more designer friendly but here is the basic idea. You will need to wrap this in some kind of form of course.

Basically you have a template and replace its contents with something dynamically generated using CSS selector binding.

In your template:

<div class="lift:MyForm.render">
  Form will go here
</div>

The snippet:

class MyForm extends Snippet {
  def render = {
    val fields = List("a", "b", "c")
    var params: Map[String, String] = ... //or whatever

    def setf(key: String)(value: String) = params = params.updated(key, value)
    def getf(key: String)() = params.get(key)

    "*" #> fields map {
      field =>
        <p>
          <label>{field}</label>{SHtml.text(getf(field) _, setf(field) _)}
        </p>
    }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文