Skip to content

Instantly share code, notes, and snippets.

@dbreunig
Created December 15, 2023 19:46
Show Gist options
  • Save dbreunig/a8e100ff240610a1bdf1787d7b50e14a to your computer and use it in GitHub Desktop.
Save dbreunig/a8e100ff240610a1bdf1787d7b50e14a to your computer and use it in GitHub Desktop.
Automatically Set Form Time Zone in Rails with Stimulus Controller

Setting a Form's Time Zone Using StimulusJS

First, create a new Stimulus controller. Here, we've title it time_zone_setter_controller.js. This controller does one thing: when the controller connects, it updates the value of the field target to the browser's reported time zone.

It reads:

import { Controller } from "@hotwired/stimulus"

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

  connect() {
    this.fieldTarget.value = Intl.DateTimeFormat().resolvedOptions().timeZone
  }
}

In your erb (or whatever) template, set up a hidden field to instantiate the controller and set it to the field target.

<%= form_with model: @user do |f| %>
  
  <%# All your other form fields... %>
  
  <%= f.hidden_field :time_zone, value: "UTC", data: { controller: "time-zone-setter", time_zone_setter_target: "field" } %>
  
<% end %>

Adjust the hidden field's name as needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment