1

I'm new to Stimulus JS. I'm a little stuck trying to make a simple event fire using collection_select in a form (created with rails g scaffold).

Here's my dropdown-controller.js (stimulus) file:

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = ["target"];

  handleChange() {
    console.log('works!')
  }
}

Here's my _forms.html.erb file:

<%= form_with(model: stock_order, local: true) do |form| %>
  ...

  <section data-controller="dropdown">
    <div class="field">
      <%= form.label :company_id %>
      <%= form.collection_select :company_id, Company.all, :id, :name, data: {action: "change->dropdown#handleChange"} %>
    </div>
  </section>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

I've tried many things:

<%= form.collection_select :company_id, Company.all, :id, :name, data: {action: "change->dropdown#handleChange"} %>

<%= form.collection_select :company_id, Company.all, :id, :name, {data: {action: "change->dropdown#handleChange"}} %>

<%= form.collection_select :company_id, Company.all, :id, :name, data: {action: "dropdown#handleChange"} %> ...etc

I can only get to fire the console.log('works!) if I use html select tags instead of rails' collection_select. The event fires if I create a test button or if I use form.check_box instead.

Any ideas? Sorry if it's a stupid question, I'm out of ideas.

Thanks!

Ignacio
  • 37
  • 1
  • 9
  • Note that according to Stimulus [naming conventions](https://stimulus.hotwired.dev/reference/actions#naming-conventions), you should not name your callback function `handleChange`. Instead find something more related to what you want to happen when the select changes. – Francois Sep 27 '21 at 12:36

1 Answers1

2

The data- are html attributes, so you miss one parameter in form.collection_select call

<%= form.collection_select :company_id, Company.all, :id, :name, nil, data: {action: "change->dropdown#handleChange"} %>

See the method description

Lyzard Kyng
  • 1,518
  • 1
  • 9
  • 14