Understanding Forms and Changesets: Difference between revisions

From ElixirBlocks
Jump to: navigation, search
No edit summary
No edit summary
 
(19 intermediate revisions by the same user not shown)
Line 5: Line 5:
The methodology of this tutorial includes converting a conventional HTML form into a Phoenix template that uses Elixir to communicate with back end code. You also learn how changesets integrate with controllers.  
The methodology of this tutorial includes converting a conventional HTML form into a Phoenix template that uses Elixir to communicate with back end code. You also learn how changesets integrate with controllers.  


The setup for the tutorial requires the creation of a database table named '''Item''' and its Ecto "Context" data.  We walk through the entire process.


'''Glossary'''
* Changeset:
* Phoenix Template:


=Getting Started=
=Getting Started=
Line 17: Line 12:


[[How to Create an Empty Phoenix Application|How to Create an Empty Phoenix Application]]
[[How to Create an Empty Phoenix Application|How to Create an Empty Phoenix Application]]
When complete, run this command to create database tables and Ecto context code.
<source>




mix phx.gen.context Items Item items name:string


</source>
==Creating an HTML Form and Post Request==


Run the migrate command
In the [[router]] create these two routes:


<source>
<source>
mix ecto.migrate
  scope "/", AppWeb do
</source>
    pipe_through :browser
 
==Seed Data==
In the file named app/priv/repo/seeds.ex  type the following code to create "dummy data" for this exercise.


<source>
    get "/", PageController, :index      # First route
App.Items.create_item(%{name: "item-1"})
    post "/create", PageController, :new  # Second route
App.Items.create_item(%{name: "item-2"})
App.Items.create_item(%{name: "item-3"})




  end
</source>
</source>


In the terminal type:
mix run priv/repo/seeds.exs


==Routes==
Place the code below in a file named  '''page_controller.ex'''. Place the file in the controller directory.


In routes, add the the following routes.
'''app/lib/app_web/controllers/page_controller.ex'''


<source>
<source>
get "/items", ItemController, :index
</source>
==Controller==
In app/lib/app_web/controllers create a file controller named:


item_controller.ex
defmodule AppWeb.PageController do
 
Copy the following code into it.
 
<source>
defmodule AppWeb.ItemController do
   use AppWeb, :controller
   use AppWeb, :controller


   def index(conn, _params) do
   def index(conn, params) do
     # The home page is often custom made,
     IO.inspect params
     # so skip the default app layout.
     csrf_token = Plug.CSRFProtection.get_csrf_token()
     render(conn, :index, layout: false)
     render(conn, :index, data: "Hello World",form: %{},csrf_token: csrf_token)
   end
   end


  def new(conn, params) do
      IO.inspect params
      redirect(conn, to: "/")
  end
end
end


</source>
</source>




In the controllers directory create a file named '''page_html.ex'''


In the same directory create a file named:
In this file, copy this code.
 
'''item.html.ex'''
 
Open the file and type the following code:


<source>
<source>
defmodule AppWeb.ItemHTML do
defmodule AppWeb.PageHTML do
   use AppWeb, :html
   use AppWeb, :html


   embed_templates "item_html/*"
   embed_templates "page_html/*"
end
end


</source>
</source>


Create a folder named index_html in the same directory like this:


app/lib/app_web/controllers/'''index_html'''
In the controllers directory create another directory named '''page_html''' (technically you can place this directory outside the controllers and it will still work).


In '''index_html''' create a file named '''index.html.heex''' and copy type the following code into it.
'''app/lib/app_web/controllers/page_html'''


<source>
This directory will contain heex templates for the PageController.
<div> Items go here</div>
</source>


Start the app and make sure everything works.
In the page_html directory place a file named '''index.html.heex'''.


'''mix phx.server'''
Inside the file copy the following code.


In your browser go to:
<source>
<source>
http://localhost:4000/items
</source>
You will see the phrase "Items go here" in the upper left corner of the screen.


==Capture Parameter Data of URL Link==
<%=@data%>
When a user clicks a hyper-link you should know how to capture the url parameters via controller. To do so follow these steps:
 


Open the router file  '''router.ex'''.
Create a new route that looks like this:


'''get "/items/:item", ItemController, :index'''
<form method="POST" action="/create">
    <input type="hidden" name="_csrf_token" value={@csrf_token} />
    <input type="text" name="example" />
    <input type="submit">
  </form>


<source>


  scope "/", AppWeb do
    get "/items/:data", ItemController, :index  #:data is a variable
    get "/items", ItemController, :index
    get "/", PageController, :home
  end
</source>
</source>


The :item is a variable and represents a value that is unknown. When you type a URL like


localhost:4000/item/some-data 
Run the server:   mix phx.server


The value "some-data" is assigned to the variable  :data as a string and the variable is captured in the controller. Once in the controller, the data can be manipulated.  
You should see a form field and a submit button with the text "Hello World" above them. Type into the form and submit it, the terminal will display your input.  


Open the '''item_controller.ex'''


Place '''IO.inspect(_params)''' in the Item index controller body like this:
If you replace the form with the built in form helper, you can remove the csrf code. CSRF protection comes built in with the form helper. Delete or comment out the code in index.html.heex and replace it with the code below.


<source>
  def index(conn, _params) do
    IO.inspect _params
    render(conn, :index, layout: false)
  end
</source>
Open the Item template in '''app_web/controllers/item_html/index.html.heex'''
Write a hyper link like this:


<source>
<source>
<a href ="items/some-data-goes-here>Click me</a>
</source>
Start the server, go to localhost:4000/items/some-data-goes-here
Open the terminal. While it is open click the link in the website that says '''Click me'''.


In the terminal the the following text is presented:
  <.form :let={f} action={~p"/create"}>
 
    <.input field={f[:x]} name="submitted-data" />
<source>
  </.form>
%{"data" => "some-data-goes-here"}
</source>
</source>


The key is the name of the variable you placed in the route (data) and the string is the data assigned to it in the hyper link (some-data-goes-here)
Delete or comment out the code in page_controller.ex and replace it with the code below.
 
 
== Submitting Data Through an HTML Form to a Controller==
You are now going to write code that lets you submit data through a form and inspect that data from within a controller.
 
 
Elixir Phoenix has it's own syntax for writing forms. This syntax is named Embedded Elixir or Heex for short. It lets you write Elixir code in your HTML template files to work with data from the server, database and user interface.
 
An example of a form with Heex used looks like this:
 
<source>
<source>
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
defmodule AppWeb.PageController do
   <%= text_input f, :name %>
   use AppWeb, :controller


   <%= inputs_for f, :permalink, fn fp -> %>
   def index(conn, params) do
    <%= text_input fp, :url %>
    IO.inspect params
   <% end %>
    render(conn, :index, data: "Hello World",form: %{})
<% end %>
   end


</source>
  def new(conn, params) do
 
      IO.inspect params
 
      redirect(conn, to: "/")
Prior to using Heex, you will create a working HTML form ''without'' Heex, and gradually integrate Heex into it.
   end
 
end
 
Go to your item index template: '''app_web/controllers/item_html/index.html.heex'''
 
Create basic HTML form.
 
<source>
<form method="POST" action="/submit">
   <input type="text" name="example" />
  <input type="submit">
</form>


</source>
</source>




In your router, create the following route. The endpoint must match the action attribute of the form - "submit".
When you run the server and visit the landing page, you should see the page render without error.
 
<source>
post "/submit", ItemController, :index
</source>




===Form Changesets===
Without Changesets we have these two problems:


* We lose what we typed.
* The app doesn’t tell us what our errors were.


{{In_progress}}
Changesets solve both of these problems.

Latest revision as of 10:30, 29 December 2024

This page is in progress

This tutorial assumes you have a basic understanding of Elixir and that you have explored Phoenix. It also assumes that you understand HTML forms.

The methodology of this tutorial includes converting a conventional HTML form into a Phoenix template that uses Elixir to communicate with back end code. You also learn how changesets integrate with controllers.


Getting Started

To begin, create a new empty Phoenix app named app. If you do not know how to do that follow this tutorial:

How to Create an Empty Phoenix Application


Creating an HTML Form and Post Request

In the router create these two routes:

  scope "/", AppWeb do
    pipe_through :browser

    get "/", PageController, :index       # First route
    post "/create", PageController, :new  # Second route


  end


Place the code below in a file named page_controller.ex. Place the file in the controller directory.

app/lib/app_web/controllers/page_controller.ex


defmodule AppWeb.PageController do
  use AppWeb, :controller

  def index(conn, params) do
    IO.inspect params
    csrf_token = Plug.CSRFProtection.get_csrf_token()
    render(conn, :index, data: "Hello World",form: %{},csrf_token: csrf_token)
  end

  def new(conn, params) do
      IO.inspect params
      redirect(conn, to: "/")
  end
end


In the controllers directory create a file named page_html.ex

In this file, copy this code.

defmodule AppWeb.PageHTML do
  use AppWeb, :html

  embed_templates "page_html/*"
end


In the controllers directory create another directory named page_html (technically you can place this directory outside the controllers and it will still work).

app/lib/app_web/controllers/page_html

This directory will contain heex templates for the PageController.

In the page_html directory place a file named index.html.heex.

Inside the file copy the following code.


<%=@data%>



<form method="POST" action="/create">
    <input type="hidden" name="_csrf_token" value={@csrf_token} />
    <input type="text" name="example" />
    <input type="submit">
  </form>


Run the server: mix phx.server

You should see a form field and a submit button with the text "Hello World" above them. Type into the form and submit it, the terminal will display your input.


If you replace the form with the built in form helper, you can remove the csrf code. CSRF protection comes built in with the form helper. Delete or comment out the code in index.html.heex and replace it with the code below.



  <.form :let={f} action={~p"/create"}>
    <.input field={f[:x]} name="submitted-data" />
  </.form>

Delete or comment out the code in page_controller.ex and replace it with the code below.

defmodule AppWeb.PageController do
  use AppWeb, :controller

  def index(conn, params) do
    IO.inspect params
    render(conn, :index, data: "Hello World",form: %{})
  end

  def new(conn, params) do
      IO.inspect params
      redirect(conn, to: "/")
  end
end


When you run the server and visit the landing page, you should see the page render without error.


Form Changesets

Without Changesets we have these two problems:

  • We lose what we typed.
  • The app doesn’t tell us what our errors were.

Changesets solve both of these problems.