DarthBinks911 DarthBinks911 - 9 months ago 63
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
helpers
and has
onclick
events that send data to Google Analytics depending on which option you choose:

<form>
<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>
</form>


My question is how do I apply the second form's
onclick
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): 
  play.twirl.api.HtmlFormat.Appendable

and then an example from the documentation

@inputRadioGroup(
  contactForm("gender"),
  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:

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