我刚刚开始学习凤凰城,我正在浏览发送电子邮件 &也可以查看Phoenix.HTML.Form文档。我已经能够根据指南正确设置所有内容,并通过 in 发送了一封测试邮件,但我还没有弄清楚如何在不使用表单中的@changset的情况下发送电子邮件。我的印象是,只有当我使用模型数据时,才需要使用@changest。对于我的场景,我只是试图捕获一个名称,电子邮件和消息,当用户点击发送给我。
非常感谢你的帮助!
发布于 2015-10-30 09:15:21
通过使用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{}结构传递给你的邮件发送程序函数。
发布于 2020-02-12 14:24:49
我使用以下方法:模式:
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这是一个联系人表单的大量代码,这就是为什么我想发布这个,这样你就不用重写这个了。希望能帮上忙。
https://stackoverflow.com/questions/33429174
复制相似问题