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

标签 scala lift

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

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

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 和 Scala 2.8.1

最佳答案

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

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

在您的模板中:

<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>
    }
  }
}

关于scala - 如何在 Lift 中动态生成输入表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5663058/

相关文章:

scala - 使用 Actor 时将普通方法调用与消息混合在一起?

json - 使用lift-json序列化和反序列化案例类

python - Scala类是否具有像Python这样的“ self ”?

scala - Akka Actor : Need an example to understand some basics

java - 如何禁用 Play 2.6 CSRFFilter

scala - Lift - 在字符串变量中获取模板的渲染输出

scala - (Lift) 在 CSS 选择器转换期间对项目进行分组?

Scala/Lift检查日期格式是否正确

scala - 为什么在抛出异常时 Scala 中的原子 block 会运行两次?