How to bind an exsiting DOM element to view Model?

Hey amigos! I’m using Elm on Ruby On Rails platform the thing is I have to fields called name and slug that needs to connect to Elm to do some slugify on the fly

module Main exposing (..)

import Browser
import Html exposing (Html, div, section, label, input, text)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)

-- MODEL


type alias Model =
  { name : String
  , slug : String
  }
-- INIT

init : Model
init =
  { name = ""
  , slug = "" }

-- VIEW


view : Model -> Html Msg
view model =
  div [] [
    div [] [ label [for "company_name"] [ text "Name"], input [ type_ "text", id "company_name", name "company[name]", value model.name, onInput Change ] [] ],
    div [] [ label [for "company_slug"] [ text "Slug"], input [ type_ "text", name "company[slug]", value (slugger model.name)] [] ]
  ]

-- MESSAGE

type Message
  = None

-- UPDATE
type Msg
  = Change String


slugger : String -> String
slugger name =
  name
  |> String.toLower
  |> String.toList
  |> List.filter Char.isAlpha
  |> String.fromList

update : Msg -> Model -> Model
update msg model =
  case msg of
    Change newContent ->
      { model | name = newContent }

-- SUBSCRIPTIONS

-- MAIN

main =
  Browser.sandbox
    {
      init = init,
      view = view,
      update = update
    }
<%= javascript_pack_tag "hello_elm" %>
<%= form_with(model: @company, local: true) do |f| %>
  <div id="here-elm">
  </div>
  <div>
    <%= f.label :name %>
    <%= f.text_field :name, id: "company_name" %>
    <%= error_message_for(@company, :name) %>
  </div>
  <div>
    <%= f.label :phone %>
    <%= f.text_field :phone, id: "company_phone" %>
    <%= error_message_for(@company, :phone) %>
  </div>
  <div>
    <%= f.label :location %>
    <%= f.text_field :location, id: "company_location" %>
    <%= error_message_for(@company, :location) %>
  </div>
  <div>
    <%= f.submit %>
  </div>
<% end %>

but I loose the errors from Rails side when there’s a validation error is there a way if I don’t create the elmenets in Elmm and just bind them to the existing one come from rails?

I’ve used HTML.Keyed to in order to have Javascript work on elements created by Elm without having them changed further by Elm, but overall I don’t think Elm is really suited to the unobtrusive javascript style where you bind some behavior to existing elements.

Your best bet may be to have Rails render the error messages as JSON somewhere, and grab that to pass as flags to your Elm program so it can render them properly.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.