formsscalacheckboxsprayspray-routing

Spray - Parsing forms with checkboxes


I am setting up a simple API part of which accepts POST requests via form submission. The form requires the user to select one or more checkboxes all sharing the same name e.g.

<form>
  <input type='text' name='textval'>
  <input type='checkbox' name='cbox' value='val1'> Value 1
  <input type='checkbox' name='cbox' value='val2'> Value 2
  <button type='submit'>Submit</button>
</form>

I am attempting to handle the request in Spray like so:

path("mypath") {
  post {
    formFields('textval, 'cbox) { (textval, cbox) =>
      // Now what?
    }
  }
}

I cannot find documentation in the Spray Docs on how to handle such inputs. In fact, this seemed to be an issue that has now been fixed, but I am unsure how to handle this form field with the Spray API


Solution

  • I have found a somewhat hacky solution to meet my needs. I have changed the names of my checkboxes to represent the values associated with them, and I use optional form fields in my spray route

    Here is my new form

    <form>
      <input type='text' name='textval'>
      <input type='checkbox' name='cbox1' value='val1'> Value 1
      <input type='checkbox' name='cbox2' value='val2'> Value 2
      <button type='submit'>Submit</button>
    </form>
    

    The route changes accordingly

    path("mypath") {
      post {
        formFields('textval, 'cbox1.?, 'cbox2.?) { (textval, cbox1, cbox2) =>
          complete(s"textval:'$textval', cbox1:'$cbox1', cbox2:'$cbox2'")
        }
      }
    }
    

    The optional fields get mapped to type Option[String] which can then be easily checked with .isEmpty or something similar to determine whether the checkbox was checked.

    However, one issue is that it will allow forms to be posted with no checkboxes selected since they are all optional. You could perhaps set one as default.