Creating Posts

Building an app with Phoenix : part 6 of 9 published on Aug 10, 2015

New Post Route

We first need to create the /posts/new route so we can display the new post form.

# /web/router.ex
  scope "/", Readdit do 
    ...
    get "/posts", PostsController, :index
    get "/posts/new", PostsController, :new
  end

New Post Controller Endpoint

Then we need to create our endpoint on our controller.

# /web/controllers/posts_controller.ex
defmodule Readdit.PostsController do
  use Readdit.Web, :controller
  ...
  def new(conn, _params) do
    post = %Readdit.Post{title: "", content: ""}
    render conn, "new.html", post: post
  end
  ...
end

New Post Template

Next we will add a form to the template.

<!-- /web/templates/posts/new.html.eex -->

<%= form_for @conn, "/posts", [name: :post], fn form -> %>
  <div class="form-group">
    <%= label(form, :title, "Title") %>
    <%= text_input(form, :title, value: @post.title, class: "form-control") %>
  </div>
  <div class="form-group">
    <%= label(form, :content, "Content") %>
    <%= textarea(form, :content, value: @post.content, class: "form-control") %>
  </div>
  <%= submit "Save", class: "btn btn-primary" %>
<% end %>

Now if we go to http://localhost:4000/posts/new we should see our newly created form.

Create Post Route

Our form will POST /posts so we need to add that route to our Phoenix router.

# /web/router.ex
  scope "/", Readdit do 
    ...
    get "/posts", PostsController, :index
    get "/posts/new", PostsController, :new
    post "/posts", PostsController, :create
  end

Create Post Controller Endpoint

We need to create our create endpoint now on our controller.

# /web/controllers/posts_controller.ex
defmodule Readdit.PostsController do
  use Readdit.Web, :controller
  ...
  def create(conn, params) do
    post = %Readdit.Post{
      title: params["post"]["title"],
      content: params["post"]["content"]
    }
    Readdit.Repo.insert!(post)
    redirect conn, to: "/posts"
  end
  ...
end

Add a link to our new post page

<!-- /web/templates/posts/index.html.eex -->
<h1>Posts</h1>

<a class="btn btn-default" href="/posts/new">New Post</a>
...

Creating a post through the browser

Now on our /posts page we can click our New Post link to go to our newly created form.

From there we can type in our new post’s title and content. After hitting save, should be redirected back to our /posts page and see our newly created post.

Next: Viewing a Post