venomnert

venomnert

LiveView Form debugging - phx_submit not getting triggered

Context:

I am trying to setup a simple liveview form.

Help:

When I visit the form /client/new and submit an entry, phx_submit event doesn’t get triggered. It instead makes a post request to /client/new which doesn’t exist.

lib/contact_us_web/live/client_live/index.ex

defmodule ContactUsWeb.ClientLive.Index do
  use Phoenix.LiveView

  alias ContactUsWeb.Router.Helpers, as: Routes
  alias ContactUsWeb.ClientView
  alias ContactUs.Accounts
  alias ContactUs.Accounts.Client

  def mount(_session, socket) do
    changeset = Accounts.change_client(%Client{})
    {:ok, assign(socket, :changeset, changeset)}
  end

  def render(assigns) do
    Phoenix.View.render(ClientView, "form.html", assigns)
  end

  def handle_event("save", args, socket) do
    IO.inspect(args, label: "VALDIATE DATA")

    {:noreply, socket}
  end
end

lib/contact_us_web/templates/client/form.html.leex

<%= form_for @changeset, "#", [phx_submit: "save"], fn f -> %>

  <%= label f, :first_name %>
  <%= text_input f, :first_name %>
  <%= error_tag f, :first_name %>

  <%= label f, :last_name %>
  <%= text_input f, :last_name %>
  <%= error_tag f, :last_name %>

  <%= label f, :email_address %>
  <%= text_input f, :email_address %>
  <%= error_tag f, :email_address %>

  <%= label f, :phone_number %>
  <%= text_input f, :phone_number %>
  <%= error_tag f, :phone_number %>

  <%= label f, :company %>
  <%= text_input f, :company %>
  <%= error_tag f, :company %>

  <%= label f, :service %>
  <%= text_input f, :service %>
  <%= error_tag f, :service %>

  <div>
    <%= submit "Save", phx_disable_with: "Saving..." %>
  </div>
<% end %>

I made sure everything is setup properly. However, I’m unable to determine what the issue is.

Marked As Solved

venomnert

venomnert

Hey @mindok I have resolved the issue.

The problem was with this code socket "/live", Phoenix.LiveView.Socket, websocket: true within the endpoint.ex

I had to provide it the same session info that was provided to plug Plug.Session.

I was able to solve this after carefully reading Phoenix error messaging, which was clear and concise :+1:t5:

Here are the following update:
contact_us/lib/contact_us_web/endpoint.ex

defmodule ContactUsWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :contact_us
  @session_options [
    store: :cookie,
    key: "_contact_us_key",
    signing_salt: "piqiBzEh"
  ]

  socket "/live", Phoenix.LiveView.Socket,
  websocket: [connect_info: [session: @session_options]]

  socket "/socket", ContactUsWeb.UserSocket,
    websocket: true,
    longpoll: false

  # Serve at "/" the static files from "priv/static" directory.
  #
  # You should set gzip to true if you are running phx.digest
  # when deploying your static files in production.
  plug Plug.Static,
    at: "/",
    from: :contact_us,
    gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt)

  # Code reloading can be explicitly enabled under the
  # :code_reloader configuration of your endpoint.
  if code_reloading? do
    socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
    plug Phoenix.LiveReloader
    plug Phoenix.CodeReloader
  end

  plug Plug.RequestId
  plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]

  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Phoenix.json_library()

  plug Plug.MethodOverride
  plug Plug.Head

  # The session will be stored in the cookie and signed,
  # this means its contents can be read but not tampered with.
  # Set :encryption_salt if you would also like to encrypt it.
  plug Plug.Session, @session_options

  plug ContactUsWeb.Router
end

contact_us/assets/js/app.js

import css from "../css/app.css"
import "phoenix_html"

import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}});
liveSocket.connect()

contact_us/lib/contact_us_web/templates/layout/app.html.eex

  <head>
    <meta charset="utf-8"/>
    <%= csrf_meta_tag() %>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>ContactUs · Phoenix Framework</title>
    <link rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
    <%= csrf_meta_tag() %>
  </head>

Also Liked

mindok

mindok

Hi @venomnert,

Have you verified that your liveview is mounting correctly? Put an IO.inspect in the mount (you should see the message twice - once for the initial render and once when the websocket connection is made) and render functions. If it itsn’t, then double-check your router setup.

Also, do you have any other liveview functionality behaving properly in the application? You may have issues with javascript library versions etc…

venomnert

venomnert

Sounds good, I will check it out. Once again thanks for you help :smiley: :+1:

fklement

fklement

I just solved it. Probably it was just too late yesterday and I was sitting too long in front of the computer :smile:
The problem was that I messed up the webpack.config.js. And therefore the /js/ parts were not copied correct to the statics folder.

Last Post!

larshei

larshei

Just found this after I had run into the same problem. The JS not being executed was a good hint.

I had chosen to use a CSS framework and replaced the original CSS/JS loading in the root template, but the original app.js is required to establish the socket connection.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42716 114
New

We're in Beta

About us Mission Statement