Q&A: How do you update relations in Phoenix forms?

This episode answers a student's question about how to use Phoenix forms to create and update things that have belongs_to or has_one associations.

The short answer is:

use a <%= inputs_for f, :your_association, fn f2 -> %> block inside your form and put the labels and inputs for the associated inside of that.

Here's an example form for a User where users have the fields username and is_activated along with a belongs_to: Credential association (and the Credential schema includes a field for email along with the virtual fields password and password_confirmation:

<%= form_for @changeset, @action, fn f -> %>
  <%= if @changeset.action do %>
    <div class="alert alert-danger">
      <p>Oops, something went wrong! Please check the errors below.</p>
    </div>
    <% error_keys = Keyword.keys(f.errors) %>
    <%= inspect error_keys %>
  <% end %>

  <div class="form-group">
    <%= label f, :username, class: "control-label" %>
    <%= text_input f, :username, class: "form-control" %>
    <%= error_tag f, :username %>
  </div>

  <div class="form-group">
    <%= inputs_for f, :credential, fn cf -> %>
      <%= label cf, :email, class: "control-label" %>
      <%= text_input cf, :email, class: "form-control" %>
      <%= error_tag cf, :email %>

      <%= label cf, :password, class: "control-label" %>
      <%= password_input cf, :password, class: "form-control" %>
      <%= error_tag cf, :password %>

      <%= label cf, :password_confirmation, class: "control-label" %>
      <%= password_input cf, :password_confirmation, class: "form-control" %>
      <%= error_tag cf, :password_confirmation %>
    <% end %>
  </div>

  <div class="form-group">
    <%= label f, :is_activated, class: "control-label" %>
    <%= checkbox f, :is_activated %>
    <%= error_tag f, :is_activated %>
  </div>

  <div class="form-group">
    <%= submit "Submit", class: "btn btn-primary" %>
  </div>
<% end %>

Also see: Building a CMS YT series

Back to index

No Comments