Understanding Forms and Changesets

From ElixirBlocks
Revision as of 00:50, 15 March 2024 by Admin (talk | contribs)
Jump to: navigation, search

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


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



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