Did you know with two commands you can add a new feature to your Phoenix app? Phoenix code generators – also known as scaffolding – create a skeleton of code upon which your programming work can be performed.
In a previous article, we installed Elixir Phoenix in our local development environment and created an empty Phoenix application. This article builds on that previous article, so if you do not yet have an empty Phoenix application running, see that article first.
In this article, we will add something useful to that application.
The Phoenix generator that creates controller, views, and context for a web app is:
mix phx.gen html
This generator is perfect for our html-based todo list and is fully documented here. In a future article I will explain each of the items created with the scaffold in context of the Elixir Phoenix request and response cycle.
However, for now, I think it’s important – and fun – to get something running! Let’s do it!
We would like each of our ToDos to have the following:
- a name
- room for notes
- a completion due date
- a completion checkbox
Each of these attributes can be sent into the html generator. In your console, go to the directory where your starter Phoenix app lives and type the following (bold lines are to be entered. Non-bold likes are the output from Phoenix as a result of entering the command.)
$ mix phx.gen.html Todos Todo todos name:string notes:text due_date:date completed:boolean
* creating lib/demo_web/controllers/todo_controller.ex
* creating lib/demo_web/templates/todo/edit.html.eex
Phoenix and Elixir in general is great at providing useful feedback in response to commands. In this case, the html generator tells us the next steps to run, so do those next steps now.
Add the resource to your browser scope in lib/demo_web/router.ex:
resources “/todos”, TodoController
Your file lib/demo_web/router.ex should now look like this.
Run the database migrations which will update your database.
$ mix ecto.migrate
08:50:09.425 [info] == Running 20191025144448 Demo.Repo.Migrations.CreateTodos.change/0 forward
08:50:09.427 [info] create table todos
08:50:09.433 [info] == Migrated 20191025144448 in 0.0s
Run the App!
Start up your app with the following command.
$ mix phx.server
and see the todo list running in your browser at http://localhost:4000/todos!
(Note the url for todos is http://localhost:4000/todos. When starting up the Phoenix server, it will point you to the homepage of the app – http://localhost:4000/. Add /todos to the end to reach the todos page.)
In a future article we’ll dive into the controller, views, and context files that this generator created. For now, create some todos in your new app including one to remember to check back here later for more details!