【问题标题】:Phoenix Contact Form凤凰联络表
【发布时间】:2016-01-30 11:26:35
【问题描述】:

我刚刚开始使用 Phoenix,我正在浏览 Sending Email 并查看 Phoenix.HTML.Form 文档。我已经能够根据指南正确设置所有内容,并通过 iex 发送了一封测试电子邮件,但我还没有弄清楚如何在不使用表单中的@changset 的情况下发送电子邮件.我的印象是,只有在使用模型数据时才需要使用 @changest。对于我的场景,我只是尝试捕获用户单击发送时发送给我的姓名、电子邮件和消息。

帮助不胜感激!

【问题讨论】:

  • 感谢您的编辑,但您为什么要使用其他用户编辑问题?我批准了它,但它还需要其他一些用户批准才能显示...如果您使用同一用户进行编辑,它将立即显示。
  • 请将控制器添加到您的问题中。

标签: elixir phoenix-framework


【解决方案1】:

您可以通过使用Ecto.Schema 和虚拟字段来使用变更集而无需数据库支持:

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

使用这样的模块,您可以像对待模型一样简单地对待它,并且您的表单将被验证等。然后您可以将整个 %ContactForm{} 结构传递给您的邮件函数以发送电子邮件。

【讨论】:

  • 一个非常有帮助的答案,你太棒了
【解决方案2】:

我使用以下内容: 架构:

defmodule App.Form.ContactForm do
  use Ecto.Schema
  import Ecto.Changeset

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

  def changeset(model, params) do
    model
    |> cast(params, [:name, :email, :phone, :body])
    |> validate_required([:name, :phone])
  end
end

上下文:

defmodule App.Form do
  alias App.Form.ContactForm

  def change_contact(%ContactForm{} = contact \\ %ContactForm{}) do
    ContactForm.changeset(contact, %{})
  end

  def create_contact(attrs \\ %{}) do
    contact = ContactForm.changeset(%ContactForm{}, attrs)
    contact = Map.merge(contact, %{action: :create}) # because we don't have a Repo call, we need to manually set the action.
    if contact.valid? do
      # send email or whatever here.
    end
    contact
  end
end

在html中:

<%= form_for @contact, Routes.contact_path(@conn, :contact), [as: "contact"], fn f -> %>
# the form. I leave styling up to you. Errors should be working because we set the action.

在路由器中:

post "/contact", PageController, :contact, as: :contact

以及控制器中两个必要的功能:

  def index(conn, _params) do
    render(conn, "index.html", contact: App.Form.change_contact())
  end

  def contact(conn, %{"contact" => contact_params}) do
    with changeset <- App.Form.create_contact(contact_params),
         true <- changeset.valid?
      do
      conn
      |> put_flash(:success, gettext("We will get back to you shortly."))
      |> render("index.html", contact: changeset)
    else
      _ ->
      conn
      |> put_flash(:error, gettext("Please check the errors in the form."))
      |> render("index.html", contact: App.Form.create_contact(contact_params))
    end

  end

联系表单的代码很多,这就是我想发布此内容的原因,这样您就不必重写此内容。希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2016-10-12
    相关资源
    最近更新 更多