Understanding Forms and Changesets: Difference between revisions

From ElixirBlocks
Jump to: navigation, search
No edit summary
No edit summary
Line 1: Line 1:
{{In_progress}}
{{In_progress}}


This tutorial assumes you have a basic understanding of Elixir and that you have explored Phoenix.
The methodology of this tutorial includes converting a conventional HTML form into a Phoenix template that uses Elixir code to communicate with back end code. Therefore, you need to be familiar with conventional HTML forms. You also learn how changesets integrate with controllers.
The setup code for the tutorial requires the creation of a database table named Item and its Ecto "Context" data.


In this tutorial you create a database table named Item and its Ecto "Context" data. You learn how changesets work by writing controllers, template and forms.


This tutorial assumes you have a basic understanding of Elixir and that you have explored Phoenix.


The methodology of this tutorial includes converting a convention HTML form into a Phoenix template that uses Elixir code to communicate with back end code.


To begin, create a new empty Phoenix app named app.
To begin, create a new empty Phoenix app named app.

Revision as of 12:02, 13 October 2023

This page is in progress

This tutorial assumes you have a basic understanding of Elixir and that you have explored Phoenix.

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

The setup code for the tutorial requires the creation of a database table named Item and its Ecto "Context" data.



To begin, create a new empty Phoenix app named app.

When complete, run this command to create database tables and Ecto context code.



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

Seed Data

In the file named app/priv/repo/seeds.ex type the following code to create "dummy data" for this exercise.

App.Items.create_item(%{name: "item-1"})
App.Items.create_item(%{name: "item-2"})
App.Items.create_item(%{name: "item-3"})

In the terminal type:

mix run priv/repo/seeds.exs

Routes

In routes, add the the following routes.

post "/items", ItemController, :create
get "/items", ItemController, :index


Controller

In app/lib/app_web/controllers create a file controller named:

item_controller.ex

Copy the following code into it.

defmodule AppWeb.ItemController do
  use AppWeb, :controller

  def index(conn, _params) do
    # The home page is often custom made,
    # so skip the default app layout.
    render(conn, :index, layout: false)
  end

end


In the same directory create a file named:

item.htem.ex

Open the file and type the following code:

defmodule AppWeb.ItemHTML do
  use AppWeb, :html

  embed_templates "item_html/*"
end