Search code examples
angularjsangular-schema-form

SchemaForm array conditional


Background

I am making a form using http://schemaform.io/

Setup

I am trying to make an array of objects that a user can make using a form. So, the user can add as many items into the array as they want.

The array of items contains a type, then another field depending on what the type was.

If the user clicks REST, I want it to offer a field called method.

If the user clicks SSH, I want it to offer a field called path.

Code so far

SCHEMA

{
  "type": "object",
  "title": "Command Asset",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "commands": {
      "type": "array",
      "title": "Actions",
      "items": {
        "type": "object",
        "properties": {
          "commandType": {
            "title": "Command Type",
            "type": "string",
            "enum": [
              "REST",
              "SSH"
            ]
          },
          "path": {
            "title": "Path",
            "type": "string"
          },
          "method": {
            "title": "Method",
            "type": "string"
          }
        }
      }
   }
  }
}

FORM

[
  {
    "type": "help",
    "helpvalue": "<h5>Command</h5>"
  },
  "name",
  {
    "title":"Command",
    "key": "commands",
    "items": [
      "commands[].commandType",
      {
        "type": "conditional",
        "condition": "modelData.commands[0].commandType=='SSH'",
        "items": [
          {
            "key": "commands[].path"
          }
        ]
      },
      {
        "type": "conditional",
        "condition": "modelData.commands[0].commandType=='REST'",
        "items": [
          {
            "key": "commands[].method"
          }
        ]
      }
    ]
  }
]

One can test this code here: http://schemaform.io/examples/bootstrap-example.html

Question

As one can see, the code I have now makes all the items' secondary properties (path or method) dependent on the first item in the array's commandType (at [0]), but I want it to depend on the commandType of the corresponding item. So, if item one has commandType of REST, it offers a method field and if item two has a command type of SSH it offers a field of path and so on.


Solution

  • I found an answer.

    Replace the [0] with [arrayIndex].

    I found it from here: https://github.com/json-schema-form/angular-schema-form/commit/21f6d3ab64435b032456dfe19e03f96b29366320