Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix Framework - How to populate a map field through a form_for?

I'm trying to populate a field :params (from a Model/Schema) which is a map. I've got a working form_for and I'd like to populate this :params map through checkboxes so that when the form is submitted the controller will receive something like %{... params => %{"param1" => "true", "param2" => "false"}} ...

I've looked at inputs_for, but that doesn't seem to do what I need since it relies on nested schemas and models, and that would mean I need to create a new schema for each new set of parameters (I need something generic that doesn't need changes to the source code if the parameters change).

<%= form_for @changeset, audit_audit_path(@conn, :new_tool_request, @audit.id),
       fn f -> %>

  <%= render LayoutView, "changeset_error.html", conn: @conn, changeset: @changeset, f: f %>

  <div class="form-group"><label>Tool</label>
    <%= select f, :toolname, tools %>
  </div>
  <div class="form-group"><label>Parameter 1</label>
    <%= checkbox f, :param1 %>
  </div>
  <div class="form-group"><label>Parameter 2</label>
    <%= checkbox f, :param2 %>
  </div>

  <div class="form-group"><label>Date of Execution</label>
    <%= datetime_select f, :date %>
  </div>
  <div class="form-group">
    <%= hidden_input f, :audit_id, value: @audit.id %>
  </div>

  <%= submit "Request", class: "btn btn-primary" %>
<% end %>

So instead of having those checkboxes for param1 and param2, I need to get all those parameters into a map. If another form is rendered with different checkboxes for the parameters, it must populate without having any relationship to a schema.

Thanks!

like image 233
Sasha Fonseca Avatar asked Jan 20 '16 12:01

Sasha Fonseca


1 Answers

In fact, I think, if in situation like that:

  schema "checkmapss" do
    field :name, :string
    field :options, :map

    timestamps()
  end

We just need to do is in form.html.eex:

  <div class="form-group">
    <%= label f, :options, class: "control-label" %>
    <%= text_input f, :options_one, name: "checkmap[options][one]", class: "form-control" %>
    <%= error_tag f, :options %>
  </div>
  <div class="form-group">
    <%= label f, :options, class: "control-label" %>
    <%= text_input f, :options_two, name: "checkmap[options][two]", class: "form-control" %>
    <%= error_tag f, :options %>
  </div>

Then the changeset function will help us finish other thing.

like image 153
Bingoabs Avatar answered Oct 13 '22 14:10

Bingoabs