Rails - Temp switch a form to CSV download form

03 Oct 2020

The strategy is simple: add a hidden field to the form

import { Controller } from 'stimulus'

export default class extends Controller {
  static = targets = ['form']

  download(event) {
    event.preventDefault();

    this._formWithCSVMode(function(form){
      form.submit();
    })
  }

  _formWithCSVMode(callback) {
    const csvSubmitField = this._buildCSVCommitField()
    this.formTarget.append(csvSubmitField)

    callback(this.formTarget);

    csvSubmitField.remove();
  }

  _buildCSVCommitField() {
    const field = document.createElement('input')
    field.type = 'hidden'
    field.id = 'temp-commit'
    field.name = 'commit'
    field.value = 'export-csv'

    return field;
  }
}
Back to top