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.

Where Next?

Popular in Questions Top

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
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
Tee
can someone please explain to me how Enum.reduce works with maps
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement