The Form Component
Let's learn how form handling is done in Phoenix using generators.
The job of the modal component is a simple one. It shows a modal pop-up with whatever component we choose to put inside, and it knows how to close it. The content we put inside our modal window may have its own state, markup, and events, so we’ll use another component-the form component. In this way, we can compose components into layers, each of which has a single responsibility. This is just one more way that the Phoenix Live generator provides us with an organized foundation for writing code that is capable of handling complex states while being easy to maintain.
The form component is a bit more complex than the modal component. It allows us to collect the fields for a product a user wants to create or update. The form component will also have events related to submitting and validating the form.
Let’s look at the form component in three steps:
- Rendering the template
- Setting up the socket
- Processing events.
How to render the form component
We’ll begin by tracing how the form component is rendered from within the modal component. This next bit of code flow is a little complex. Take your time to read through this lesson and let the provided code snippets guide you.
Remember, there are two kinds of components, stateful and stateless. Components with id
keys are stateful. Those without are stateless. It’s been a while since we saw the code, but we actually specify the attributes for our form component within the pento/lib/pento_web/live/product_live/index.html.leex
template, like this:
<%= if @live_action in [:new, :edit] do %><%= live_modal @socket, PentoWeb.ProductLive.FormComponent,id: @product.id || :new,title: @page_title,action: @live_action,product: @product,return_to: Routes.product_index_path(@socket, :index)%><% end %>
Notice there’s an :id
key, along with a :component
key on line 3 that specifies the FormComponent
that will be rendered inside the modal. These attributes are passed into the modal component with the call of PentoWeb.LiveHelpers.live_modal/3
to live_component/3
...