Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix Contact Form

I'm just getting started with Phoenix and I'm going through the Sending Email & also viewing the Phoenix.HTML.Form docs. I've been able to set up everything correctly based on the guide and have sent a test email via iex but I've yet to figure out how to send an email without using the @changset in the form. I was under the impression that using @changest is only needed when I'm using model data. For my scenario I'm simply trying to capture a name, email and message that gets sent to me when the user clicks send.

Help greatly appreciated!


1 Answers

You can use a changeset without it being backed by the database by using Ecto.Schema and virtual fields:

defmodule ContactForm do      
  use Ecto.Schema

  schema "" do
    field :email, :string, virtual: true
    field :name, :string, virtual: true
    field :body, :binary, virtual: true
  end

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, ["email", "name", "binary"], [])
    #|> validate_length(:body, min: 5) - any validations, etc. 
  end   
end

With a module like this you can simply treat it as you would a model and your form will be validated, etc. You can then pass the whole %ContactForm{} struct to your mailer function for sending the email.

like image 69
Gazler Avatar answered Nov 18 '25 20:11

Gazler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!