简体   繁体   English

如何使用羊驼创建一个必需的条件字段?

[英]How to create a required conditional field using Alpaca?

Does anyone know how I can define a required field which is dependant on another field? 有谁知道如何定义一个依赖于另一个字段的必填字段?

For example if field1 is marked true then field2 must be required, otherwise field 2 should not be filled. 例如,如果field1标记为true则必须使用field2 ,否则不应填充字段2。

Here is my current attempt: 这是我目前的尝试:

"field1": {
    "title": "Field1:",
    "type": "string",
    "enum": ["true", "false"]
},
"field2": {
    "title": "Field2:",
    "type": "integer",
    "dependencies": "field1",
    "required": true
}

Alpaca's dependency system hides the dependant field if the dependency is not met, otherwise the field is shown and any options assigned to it such as validation options are also required. 如果不满足依赖关系,羊驼的依赖系统会隐藏依赖字段,否则会显示该字段,并且还需要分配给它的任何选项,例如验证选项。

After looking through the documentation I noticed that you have to set the dependencies in both the schema and the options objects. 查看完文档后,我注意到您必须在架构和选项对象中设置依赖关系。

JSON JSON

{
  "view": "bootstrap-edit",
  "schema": {
    "type": "object",
    "properties": {
      "description_required": {
        "enum": [
          "Y",
          "N"
        ],
        "required": true
      },
      "description": {
        "required": true
      }
    },
    "dependencies": {
      "description": ["description_required"] // Specify the field that your conditional field is dependant on
    }
  },
  "options": {
    "fields": {
      "description_required": {
        "type": "select",
        "noneLabel": "Select an Option",
        "label": "Description Required"
      },
      "description": {
        "type": "textarea",
        "cols": 5,
        "label": "Description",
        "dependencies": {
          "description_required": "Y" // Specify the required value for the dependant field to show
        }
      }
    }
  }
}

In the above example, we have a simple select with the options of Y and N . 在上面的例子中,我们有一个带有YN选项的简单选择。 If Y is selected then we show a required textarea, otherwise the textarea is not displayed. 如果选择Y ,则显示所需的textarea,否则不显示textarea。

Live Example 实例

JSFiddle - Take note of the comments in the form object. JSFiddle - 记下表单对象中的注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM