如何扩展 elixir phoenixframework html 表单助手

how to extend elixir phoenixframework html form helper

我尝试扩展 phoenixframework. My intension is to wrap the html form helper text_input to create a text input field for a timex date value to use it with bootstrap-datepicker 的 Phoenix.HTML.Form 模块。

我是 elixir 的新手,但我阅读了有关扩展 elixir 模块的协议。所以我尝试了:

defprotocol Phoenix.HTML.Form.Extension do
  def timex_date_input(form, field, opts \ [])
end

defimpl Phoenix.HTML.Form.Extension, for: Phoenix.HTML.Form do
  def timex_date_input(%{model: model, params: params}, field, opts \ []) do
    # my logic goes here
    form = %{model: model, params: params}
    text_input(form, field, opts)
  end
end

但是,它不起作用,因为:"function text_input/3 undefined"。什么是正确的解决方案?

您需要导入 Phoenix.HTML.Form 模块才能使用 text_input - 您会发现它已经导入到您的视图中(以及您的模板,因为它们是您视图中的函数)在你的 web.ex 文件中。

如果你想添加一个新的表单函数,你可以简单地定义函数(不需要协议 - 这些通常被用作扩展库的方式 - phoenix_ecto 是一个很好的例子这个):

defmodule MyApp.FormHelpers
  def timex_date_input(form, field, opts \ [])   do
    # my logic goes here
    form = %{model: model, params: params}
    Phoenix.HTML.Form.text_input(form, field, opts)
  end

然后您可以将其导入您的视图 (import MyApp.FormHelpers),或在您的模板中使用完整的函数名称:

<%= timex_date_input(f, :date, ...) %>