DarthBinks911 DarthBinks911 - 2 months ago 29
Scala Question

How to apply an `onclick` event to multiple radio button options in Scala Play?

I'm using the Play framework in Scala.
I have this radio button that lets you choose between two options from a form:

@helpers.inputRadioGroup(searchForm("options"), Seq("option1" -> "Option 1", "option2" -> "Option 2"))

I also have another form that doesn't use
and has
events that send data to Google Analytics depending on which option you choose:

<input type="radio" name="option1" onclick="ga('send', 'event', { eventCategory: 'searchForm', eventAction: 'options', eventLabel: 'option1'})" value="@searchForm("options")">Option 1<br>
<input type="radio" name="option2" onclick="ga('send', 'event', { eventCategory: 'searchForm', eventAction: 'options', eventLabel: 'option2'})" value="@searchForm("options")">Option 2<br>

My question is how do I apply the second form's
events to the first example?


Each of the helper objects like inputRadioGroup has an apply method as documented here, for example (for play 2.3): https://www.playframework.com/documentation/2.3.x/api/scala/index.html#views.html.helper.inputRadioGroup$

Here's the definition of apply:

def apply(
  field: Field,
  options: Seq[(String, String)],
  args: (Symbol, Any)*)(
  implicit handler: FieldConstructor, lang: Lang): 

and then an example from the documentation

  options = Seq("M"->"Male","F"->"Female"),
  '_label -> "Gender",
  '_error -> contactForm("gender").error.map(_.withMessage("select gender")))

we see that tag attributes are provided as varargs in the form of a pair of Symbol and Any. So, we can rewrite your tag as follows:

  Seq("option1" -> "Option 1", "option2" -> "Option 2"),
  'onclick -> "ga('send', 'event', { eventCategory: 'searchForm', eventAction: 'options', eventLabel: 'option1'})"