Search code examples
angularjsangular-schema-form

schemaform adding the user input to a schema array


Background

I am making a form using angular-schema-form

Setup

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

For now the items in the array contain a command type.

Command Type should be a dropdown containing SSH, REST, and whatever the user enters in as the personalized command type.

Code so far

SCHEMA

{
  "type": "object",
  "properties": {
    "personalizedCommandType": {
      "title": "Personalized Command Type",
      "type": "string"
    },
    "commands": {
      "type": "array",
      "title": "Actions",
      "items": {
        "type": "object",
        "properties": {
          "commandType": {
            "title": "Command Type",
            "type": "string",
            "enum": [
              "REST",
              "SSH"
            ]
          }
        }
      }
   }
  }
}

FORM

[
  {
    "type": "help",
    "helpvalue": "<h5>Command</h5>"
  },
  {
    "key":"personalizedCommandType"
  },
  {
    "title":"Command",
    "key": "commands",
    "items": [
      "commands[].commandType"
    ]
  }
]

One can test this code here: http://schemaform.io/examples/bootstrap-example.html . Just copy and paste in my code.

Question

As one can see, the code I have now has a field with Personalized Command Type and an array of dropdowns with the 2 options SSH and REST. But I want to drop to also contain the value of the Personalized Command Type once the user has entered it.

NOTE

copyValueTo does not seem to have the functionality that I want given that it can only change values in the model, but I want it to change the enum array in the schema.


Solution

  • Use the onChange option:

    [
      {
        "type": "help",
        "helpvalue": "<h5>Command</h5>"
      },
      {
        "key":"personalizedCommandType"
         onChange: "updateSchema(modelValue,form)"
      },
      {
        "title":"Command",
        "key": "commands",
        "items": [
          "commands[].commandType"
        ]
      }
    ]
    

    Update the Schema:

    var defaultEnum = ["REST","SSH"];
    
    $scope.updateSchema = function(modelValue,form) {
        var currentEnum = $scope.schema.commands.items.properties.commandType.enum;
        angular.copy(defaultEnum, currentEnum);
        if (modelValue) {
            currentEnum.push(modelValue);
        }; 
        $scope.$broadcast('schemaFormRedraw');
    };