Dynamic nested forms

Hi, yeah I’ll try to remember cause it has been a while :slight_smile:

add this to your model

use Formex.Ecto.Schema

add this to your schema

formex_collection_child()

then you create a form type like so

defmodule Assistant.Web.ServiceType do
  use Formex.Type
  use Formex.Ecto.Type
  use Formex.Ecto.ChangesetValidator
  use Arc.Ecto.Schema
  import Ecto.Changeset, only: [cast: 3]

  def build_form(form) do
    form
    |> add(:name, :text_input, label: "Service Name", validation: [:required])
    |> add(:description, :textarea, label: "Service Description",
      phoenix_opts:
        [
          rows: 5
        ],
      validation: [:required])
    |> add(:image, :file_input, label: "Image",
      validation: [:required])

in the controller you use the create form module you created

 |> create_form(%Detail{}, detail_params)
    |> insert_form_data
    |> case do
      {:ok, detail} ->
        conn
        |> put_flash(:info, "Clinic's Details created successfully.")
        |> Map.put(detail, :id, 1)
        |> redirect(to: clinic_detail_path(conn, :index))
      {:error, form} ->
        render(conn, "new.html", form: form)
      end

then in the template you use the helper methods provided

<%= formex_form_for @form, @action, [multipart: true], fn f -> %>

  <%= if @form.submitted? do %>Oops, something went wrong!<% end %>

  <%= formex_row f, :name %>
  <%= formex_row f, :motto %>
  <%= formex_row f, :logo %>
  <%= formex_row f, :brief %>
  <%= formex_row f, :opening_hours %>
  <%= formex_row f, :contact %>
  <%= formex_row f, :image %>
  


  <% collection = fn collection -> %>
    <div class="form-horizontal">
      <%= formex_collection_items collection %>
      <%= formex_collection_add collection, "Add Service" %>
    </div>
  <% end %>

  <% collection_item = fn subform -> %>
    <%= formex_collection_remove {:safe, "&times;"}, "Are you sure you want to remove?" %>
    <%= formex_row subform, :name %>
    <%= formex_row subform, :description %>
    <%= formex_row subform, :image %>
  <% end %>

  <%= formex_collection f, :services, [template: Formex.Template.BootstrapHorizontal], collection, collection_item %>

  <%= formex_row f, :save %>
  
<% end %>

for more in depth and precise information the library page is really good formex github

I hope I have been able to help, as I mentioned it has been a while. Any questions just ask :slight_smile:
Good luck!