Cate-Lukner

Cate-Lukner

Hi all!

I am working on including a contact form in my Phoenix web application that uses Liveview. The contact form is rendered with a bootstrap modal. When the form is submitted, it sends an email using Bamboo (GitHub - beam-community/bamboo: Testable, composable, and adapter based Elixir email library for devs that love piping. · GitHub).

Here is the contact-form.html.leex that contains the form:

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

    <div class="form-group">
    <%= label f, :first_name, class: "control-label" %>
    <%= text_input f, :first_name,
        class: "form-control",
        value: @form_data["first_name"],
        minlength: "2",
        required: "required",
        step: "1"
    %>
    <%= error_tag f, :first_name %>
  </div>

  <div class="form-group">
    <%= label f, :last_name, class: "control-label" %>
    <%= text_input f, :last_name,
        class: "form-control",
        value: @form_data["last_name"],
        type: "text",
        minlength: "2",
        required: "required",
        step: "2"
    %>
    <%= error_tag f, :last_name %>
  </div>

  <div class="form-group">
    <%= label f, :email_address, class: "control-label" %>
    <%= email_input f, :email_address,
        class: "form-control",
        value: @form_data["email_address"],
        minlength: "2",
        required: "required",
        step: "3"
    %>
    <%= error_tag f, :email_address %>
  </div>

  <div class="form-group">
    <%= label f, :subject, class: "control-label" %>
    <%= text_input f, :subject,
        class: "form-control",
        value: @form_data["subject"],
        minlength: "2",
        required: "required",
        step: "4"
    %>
    <%= error_tag f, :subject %>
  </div>

  <%= label f, :message, class: "control-label" %>
  <%= textarea f, :message,
      class: "form-control",
      value: @form_data["message"],
      minlength: "2",
      required: "required",
      step: "5"
  %>
  <%= error_tag f, :message %>

  <br>

  <div>
    <%= submit "Send", phx_disable_with: "Air pigeons prepping for delivery...", class: "btn btn-primary" %>
  </div>
<% end %>

Here is client_live.ex that contains the ClientLive module:

defmodule LarcWebsiteWeb.ClientLive do
    use Phoenix.LiveView

    alias LarcWebsiteWeb.Router.Helpers, as: Routes
    # alias LarcWebsiteWeb.ClientView
    alias LarcWebsiteWeb.ContactView
    alias LarcWebsite.Accounts
    alias LarcWebsite.Accounts.Client

    def mount(_params, _session, socket) do
      IO.inspect(connected?(socket), label: "CONNTECTION STATUS")
      assigns = [
        conn: socket,
        changeset: Accounts.change_client(%Client{}),
        form_data: %{                # This is the form data to be captured and utilized to create a new client
          "first_name" => "",
          "last_name" => "",
          "email_address" => "",
          "subject" => "",
          "message" => "",
        },
      ]

      {:ok, assign(socket, assigns)}
    end

    def render(assigns) do
      ContactView.render("contact-form.html", assigns)
    end

    def handle_event("save", %{"client" => params}, socket) do
      params
      |> Accounts.create_client()
      |> case do
          {:ok, _user} ->
            {:noreply,
            socket
            |> Client.send_contact_email(params)
            |> put_flash(:info, "Your message is sent! Expect a reply soon.")
            |> redirect(to: Routes.page_path(LarcWebsiteWeb.Endpoint, :index))}

          {:error, %Ecto.Changeset{} = changeset} ->
            {:noreply, assign(socket, changeset: changeset)}
      end
    end
end

Here is the create_client function in the Accounts module:

defmodule LarcWebsite.Accounts do
  @moduledoc """
  The Accounts context.
  """

  import Ecto.Changeset
  import Ecto.Query, warn: false
  alias LarcWebsite.Repo

  alias LarcWebsite.Accounts.Client
---SNIP---
  def create_client(attrs \\ %{}) do
    %Client{}
    |> Client.changeset(attrs)
    |> Repo.insert()

  end
---SNIP---

Here is the Accounts.Client module:

defmodule LarcWebsite.Accounts.Client do
  use Ecto.Schema
  import Ecto.Changeset

  alias LarcWebsite.{Mailer, Email}

  schema "clients" do
    field :email_address, :string
    field :first_name, :string
    field :last_name, :string
    field :message, :string
    field :subject, :string

    timestamps()
  end

  @doc false
  def changeset(client, attrs) do

    email_regex = ~r"[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*"

    client
    |> cast(attrs, [:first_name, :last_name, :email_address, :subject, :message])
    |> validate_required([:first_name, :last_name, :email_address, :subject, :message])
    |> validate_format(:email_address, email_regex)
    |> validate_length(:first_name, min: 2)
    |> validate_length(:last_name, min: 2)
    |> validate_length(:subject, min: 2)
    |> validate_length(:message, min: 2)
  end
  def send_contact_email(socket, params) do
    # Specific to the handle event for "save"
    # Send the email and returns the socket that will be
    # passed to put_flash and the redirect

     Email.contact_email(params)
     |> Mailer.deliver_later()

     socket
  end
end

Here is the HTML code in app.html.eex that references the ClientLive module:

<!-- Contact Model -->
<div class="modal fade" id="Mymodal" tabindex="-1">
	<div class="modal-dialog modal-md">
		<div class="modal-content bg-light">
			<div class="modal-header text-left">
        <h1 class="modal-title w-100">
            Contact Us
        </h1> 
        <div class="text-left">
          <button type="button" class="close" data-dismiss="modal">
            <span aria-hidden="true">&times;</span>
          </button> 
        </div>
			</div> 
			<div class="modal-body">
          <%= live_render(@conn, LarcWebsiteWeb.ClientLive) %>
			</div>   
		</div>                                                                       
	</div>                                      
</div>
</div>

Here is the output of the terminal when I submit the form:

[debug] QUERY OK db=3.2ms queue=0.1ms idle=1578.9ms
INSERT INTO `clients` (`email_address`,`first_name`,`last_name`,`message`,`subject`,`inserted_at`,`updated_at`) VALUES (?,?,?,?,?,?,?) ["email@email.edu", "Catherine", "Lukner", "New Message. ", "It worked!", ~N[2020-07-07 19:53:27], ~N[2020-07-07 19:53:27]]
[debug] Sending email with Bamboo.SendGridAdapter:

%Bamboo.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: {nil, "email@gmail.com"}, headers: %{"Reply-To" => "email@email.edu"}, html_body: "\n    <p>Catherine Lukner wrote,</p>\n    <br>\n    <p>New Message. </p>\n    <br>\n    <p>Reply-To: email@email.edu</p>\n    ", private: %{}, subject: "Contact Submission: It worked!", text_body: nil, to: [nil: "email@gmail.com"]}

[debug] QUERY OK db=2.9ms queue=0.1ms idle=1580.1ms
INSERT INTO `clients` (`email_address`,`first_name`,`last_name`,`message`,`subject`,`inserted_at`,`updated_at`) VALUES (?,?,?,?,?,?,?) ["email@email.edu", "Catherine", "Lukner", "New Message. ", "It worked!", ~N[2020-07-07 19:53:27], ~N[2020-07-07 19:53:27]]
[debug] Sending email with Bamboo.SendGridAdapter:

%Bamboo.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: {nil, "email@gmail.com"}, headers: %{"Reply-To" => "email@email.edu"}, html_body: "\n    <p>Catherine Lukner wrote,</p>\n    <br>\n    <p>New Message. </p>\n    <br>\n    <p>Reply-To: email@email.edu</p>\n    ", private: %{}, subject: "Contact Submission: It worked!", text_body: nil, to: [nil: "email@gmail.com"]}

As you can see, the form is submitted twice and Bamboo is sending two emails. However, this behavior does not occur whenever I submit the form in its own template seperate from app.html.eex or index.html.eex.

Versions

Elixir: 1.9.2
Phoenix: 1.5.3
Phoenix Liveview: 0.13.3
Bamboo: 1.5

Expected Behavior
The form submits once and Bamboo sends one email.

Actual Behavior
The form is submitted twice and Bamboo sends two emails.

Any help is much appreciated!

Showing Posts 1 to 6

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hi @Cate-Lukner every time this has happened to me it’s because I was accidentally including the javascript on the page twice, and so live view would bind to everything twice. You can validate this by looking in your browser network tab, you’ll see 2 live view websocket connections. You’ll also see two websocket connection events in the logs. I’d check that first.

Cate-Lukner

Cate-Lukner OP

In the logs, I do see two websocket connections, so that may be a clue to the problem. What did you have to change to fix the problem?

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Fortunately it’s quite simple. Look at the HTML (view source) and figure out where you are including your app.js twice. Then, simply remove whichever one shouldn’t be there.

Cate-Lukner

Cate-Lukner OP

That worked! I had my app.js both in my index.html.eex and app.html.eex files, so I simply deleted the app.js from the head in index.html.eex. Thank you for you help!

sebasortiz

sebasortiz

@Cate-Lukner @benwilson512 Thank you very much for this! We’ve been looking for this “double form submit” with Phoenix and LiveView for two weeks.

a8t

a8t

Just ran into this too. For me, it’s because I didn’t understand the layout and root_layout options, so I did this silly thing which included the root layout twice, including app.js:

  def live_view do
    quote do
      use Phoenix.LiveView,
        layout: {RelinkerWeb.Layouts, :root} # the offending line

      unquote(html_helpers())
    end
  end

and fixed it by removing it (right)

  def live_view do
    quote do
      use Phoenix.LiveView

      unquote(html_helpers())
    end
  end
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews