6

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.

Here is my current attempt:

"field1": {
    "title": "Field1:",
    "type": "string",
    "enum": ["true", "false"]
},
"field2": {
    "title": "Field2:",
    "type": "integer",
    "dependencies": "field1",
    "required": true
}
Script47
  • 14,230
  • 4
  • 45
  • 66
Miguel Camargo
  • 103
  • 1
  • 8
  • I am struggling with the same problem. When you require dependend field its visible all the time and brake the sense of dependency. – amonowy Oct 09 '17 at 13:40
  • I think what you need is to associate `required` with a function that checks if the value of `field1` is `true`. I have [a similar/related problem](/questions/46663203/how-do-i-make-alpaca-conditional-dependencies-use-a-function-instead-of-an-array), about which I have asked. Exactly *how* one writes that function (how to get the value of `field1`), I don't know. – Agi Hammerthief Oct 10 '17 at 09:54

1 Answers1

3

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

{
  "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. If Y is selected then we show a required textarea, otherwise the textarea is not displayed.

Live Example

JSFiddle - Take note of the comments in the form object.

Script47
  • 14,230
  • 4
  • 45
  • 66