Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Todo List

Creating a simple Todo List application with the Play Framework in Scala involves several steps, including setting up your Play project, defining the model, creating controllers and views, and setting up routes for handling HTTP requests. Here's a step-by-step guide to get you started:

1. Setting Up Your Play Project

First, create a new Play Framework project using sbt (Scala's build tool). Open a terminal and run:

sbt new playframework/play-scala-seed.g8

Follow the prompts to name your project. This creates a basic structure for your Play application.

2. Defining the Todo Model

Define a case class to represent a Todo item. You can create a Scala file Todo.scala in the models directory:

package models

case class Todo(id: Long, task: String, isDone: Boolean)

3. Creating the Application Controller

Create a controller to handle the logic for your Todo List application. You might name it TodoController.scala and place it under the controllers directory. Here's how you might start:

package controllers

import models.Todo
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import javax.inject._

@Singleton
class TodoController @Inject()(cc: MessagesControllerComponents) extends MessagesAbstractController(cc) {

  private val todos = scala.collection.mutable.ArrayBuffer(
    Todo(1, "Learn Play Framework", isDone = false),
    Todo(2, "Build a Todo List App", isDone = false)
  )

  private val todoForm: Form[Todo] = Form(
    mapping(
      "id" -> ignored(0L),
      "task" -> nonEmptyText,
      "isDone" -> boolean
    )(Todo.apply)(Todo.unapply)
  )

  def listTodos = Action { implicit request: MessagesRequest[AnyContent] =>
    Ok(views.html.listTodos(todos.toList, todoForm))
  }

  def addTodo = Action { implicit request: MessagesRequest[AnyContent] =>
    todoForm.bindFromRequest.fold(
      errorForm => BadRequest(views.html.listTodos(todos.toList, errorForm)),
      todo => {
        val newId = if (todos.isEmpty) 1L else todos.map(_.id).max + 1
        todos += todo.copy(id = newId)
        Redirect(routes.TodoController.listTodos)
      }
    )
  }
}

4. Defining Routes

In the conf/routes file, add routes for displaying the Todo List and adding a new Todo item:

GET     /todos              controllers.TodoController.listTodos
POST    /todos/add          controllers.TodoController.addTodo

5. Creating the Views

You need to create Scala HTML templates for displaying and adding Todo items. You can place these in the views directory. For instance, create listTodos.scala.html:

@(todos: List[Todo], todoForm: Form[Todo])(implicit request: MessagesRequestHeader)
@import helper._

@main("Todo List") {
    <h1>Todo List</h1>
    
    <ul>
    @for(todo <- todos) {
        <li>
            @if(todo.isDone) {
                <s>@todo.task</s>
            } else {
                @todo.task
            }
        </li>
    }
    </ul>
    
    <h2>Add a new task</h2>
    @form(routes.TodoController.addTodo) {
        @CSRF.formField
        
        @inputText(todoForm("task"))
        
        <button type="submit">Add</button>
    }
}

6. Running Your Application

Use sbt to run your Play application:

sbt run

After your application starts, you can access it by navigating to http://localhost:9000/todos in your web browser.

Notes:

  • This example uses an in-memory collection to store Todo items, which means your data won't persist across application restarts. For a real application, you would typically use a database.
  • Security measures like input validation and CSRF protection are included, but always consider additional security practices and validations based on your application's needs.
  • The UI is very basic. You can enhance it using CSS frameworks like Bootstrap for a better look and feel.