Ignacio
Ignacio

Reputation: 37

Can't make Stimulus JS data-action in collection_select Rails 6

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!

Upvotes: 1

Views: 5015

Answers (1)

Lyzard Kyng
Lyzard Kyng

Reputation: 1568

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

Upvotes: 2

Related Questions