dwyl / dwyl/learn-phoenix

Changesets and methods in forms

Open
#27 2 comments 2 reactions 0 assignees View on GitHub
discuss help wanted
Dominant language
No language data
Stars
664
Forks
41
PR merge metrics
No merged PRs in 30d

Description

There were a few questions that came up when I was working with forms. One is outlined in detail in #25 for when you need to pass actions to the form in the controllers, or in the form itself.

Another was why the changeset needed to be defined in the controller and passed in at the beginning of the form. One reason I found for this (there may be others so please add!), is for when the form is being validated, adding in the changeset allows the error_tags to be rendered based on if fields are required & not filled in, or not the correct length, etc. `form_for` is a function which can take the changeset and convert it to a form (`f`).

```
<%= form_for @changeset, user_path(@conn, :create), fn f -> %>

Name: <%= text_input f, :name %>


Age: <%= select f, :age, 18..100 %>

<%= submit "Submit" %>
<% end %>
```

The form can then be passed to other functions (eg `select` or `text_input` in the example above), which can generate the input fields by taking information from the changeset.
See [here](https://hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html) for more information.

The form method is usually derived from the action, however I found in some cases this wasn't working. The form was defaulting to "post" when it should have been "put" when updating users. A line can be added below the first to override the default form method so it is the correct one:

```
<%= form_for @changeset, @action, fn f -> %>

```

Contributor guide

Open the contributing guide

Research direction

Start by reading the detailed discussion in #25 and the linked Phoenix.HTML.Form documentation, then verify the changeset and form-method behavior described in the examples. The issue does not identify a documentation target or acceptance criteria, so completion would require clarifying what should be documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
elixir
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.