DarthBinks911 DarthBinks911 - 1 year ago 110
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?

Answer Source

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'})"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download