Search code examples
conditional-statementsformsalpacajs

How to show same field based on an or condition on alpaca by binding a field to multiple dependencies


I am using alpacajs to render an HTML form. My requirement is to show certain fields based on a checkbox. there are three checkboxes in my form and I want to show some fields if any of the checkboxes are checked.

I went through alpaca documentation on conditional dependencies and couldn't find a soution to my problem. I can solve this by creating same fields with different names but that's against dry principle.

My code looks like below.

"myCheckBox1": {
    "type": "boolean"
},
"myCheckBox2": {
    "type": "boolean"
},
"usernameField": {
    "label": "Username *",
    "order": 6,
    "type": "string"
    "disallowOnlyEmptySpaces": true,
    "showMessages": false,
    "disallowEmptySpaces": true,
}

I want to show usernameField if either of myCheckBox1 or myCheckBox2 is checked. I altered schema to show conditional dependencies.

"dependencies": {
  "usernameField": [
    "myCheckBox1"
  ],
  "usernameField": [
    "myCheckBox2"
  ]
}

But that consider only last given condition ie, it will display usernameField only if myCheckBox2 is checked and does not consider myCheckBox1. I tried below code also:

"dependencies": {
  "usernameField": [
    "myCheckBox1", "myCheckBox2"
  ]
}

But that evaluates to an and condition. Is there a way to show same field using different dependencies?


Solution

  • Why you don't use a group of checkboxes using enum type like the following :

    // schema
    "check": {
        "title": "Select...",
        "type": "string",
        "enum": ["First", "Second"]
    },
    ...
    // options
    "check": {
        "type": "checkbox"
    }
    

    Then you use conditional dependencies like this:

    "username": {
       "dependencies": {
          "check": [
              'First', // if First is selected
              'Second', // if Second is selected
              'First,Second' // if both First and Second are selected
          ] 
       }
    }
    

    Here's a working fiddle for this.

    Please tell me if this isn't what you're looking for.